学习目标:
`
- 学习做个小游戏
学习内容:
import pygame
import sys
import random
from pygame.locals import*
pygame.init()
screen = pygame.display.set_mode((640,780),0,32)
ball_x,ball_y = random.randint(30,320),-50
vel_y = random.randint(0,10)
vel_x = random.randint(0,10)
rect_x,rect_y,rect_w,rect_h = 300,740,220,40
lives = 3
score = 0
white = 250,255,250
def print_text(src,font,x,y,text,color=white):
imgText = font.render(text,True,color)
src.blit(imgText,(x,y))
font = pygame.font.Font(“c:/windows/Fonts/Stzhongs.ttf”,32)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
rect_x -= 5
if keys[pygame.K_d]:
rect_x += 5
if keys[pygame.K_w]:
rect_y -= 5
if keys[pygame.K_s]:
rect_y += 5
if ball_x > 640 or ball_y > 780 :
lives-=1
ball_x,ball_y = random.randint(30,320),-50
if rect_x < 0 or rect_x > 640 or rect_y > 780 or rect_y < 0:
rect_x,rect_y,rect_w,rect_h = 300,740,220,40
elif (rect_y-ball_y)<30 and ball_x>rect_x and ball_x<(rect_x+rect_w):
score+=1
ball_x,ball_y = random.randint(30,320),-50
if lives <= 0:
print_text(screen,font,100,100,"重新开始")
screen.fill((255, 0, 255))
ball_y += vel_y
ball_x += vel_x
pygame.draw.rect(screen,(30,0,0),(rect_x,rect_y,rect_w,rect_h),0)
pygame.draw.circle(screen, (0, 250, 100), (ball_x, ball_y), 50)
print_text(screen,font,20,0,"lives:"+str(lives))
print_text(screen,font,500,0,