import pygame,sys,random from pygame.locals import * #定义文本函数 def print_text(font,x,y,text,color=(255,255,255)): imgText = font.render(text,True,color) screen.blit(imgText,(x,y)) #初始化参数 pygame.init() screen = pygame.display.set_mode((600,500))#窗口大小 pygame.display.set_caption('接小球')#窗口标题,图标从哪里来的 font1 = pygame.font.Font(None,24)#默认字体 24号 pygame.mouse.set_visible(True)#窗口是否显示鼠标 white = 255,255,255 red = 220,50,50 yellow = 230,230,50 blue = 0,0,100 holl = 0 lives = 3 score = 0 game_over = True mouse_x = mouse_y = 0 #初始化挡板位置 pos_x = 300 pos_y = 460 #小球的位置 水平方向随机,垂直方向降落 bomb_x = random.randint(0,500) bomb_y = -50 vel_y = 0.7 while True: screen.fill(blue) for event in pygame.event.get():#从队列当中获得所有的事件 if event.type == QUIT: sys.exit() elif event.type == MOUSEMOTION:#如果是鼠标的类型 mouse_x,mouse_y = event.pos elif event.type == MOUSEBUTTONUP:#如果鼠标抬起,则定义开始的参数 if game_over: game_over = False lives = 3 score = 0 keys = pygame.key.get_pressed() if keys[K_ESCAPE]: sys.exit() if game_over==True: #此处当前是FLSE,只见过默认是True的情况?这个老师讲错,本处是True print_text(font1,100,200,'CLICK TO PLAY') else:#如果没接到小球 bomb_y += vel_y#程序中并没有用时间限制循环速度,那么速度快的电脑是不是更快一点? if bomb_y > 500: bomb_x = random.randint(0,500) bomb_y = -50 lives -=1 if lives == 0: game_over = True #如果接住小球 elif bomb_y > pos_y: if bomb_x > pos_x and bomb_x < pos_x +120: score += 10 bomb_x = random.randint(0,500) bomb_y = -50 #绘制小球 pygame.draw.circle(screen,yellow,(bomb_x,int(bomb_y)),30,0) pos_x = mouse_x if pos_x < 0: pos_x = 0 elif pos_x > 500: pos_x = 500 #画挡板 pygame.draw.rect(screen,red,(pos_x,pos_y,120,40),0)#0是实心1是空心 holl = holl+1 print_text(font1,0,0,'LIVES:'+str(lives)) print_text(font1,500,0,'SCORE:'+str(score)) print_text(font1, 400, 0, 'HOLL:' + str(holl)) pygame.display.update()