下面是一个使用Pygame编写的简单小游戏程序,它是一个打地鼠游戏,玩家需要尽可能多地打击出现的地鼠,每次打中会获得一定分数,游戏时间结束后会显示最终得分。
importpygame
importrandom
importtime
#初始化Pygame
pygame.init()
#游戏窗口大小
WIDTH=
HEIGHT=
#颜色定义
BLACK=(0,0,0)
WHITE=(,,)
RED=(,0,0)
#创建游戏窗口
screen=pygame.display.set_mode((WIDTH,HEIGHT))
#设置窗口标题
pygame.display.set_caption("Whack-a-Mole")
#设置游戏时钟
clock=pygame.time.Clock()
#加载图像
mole_image=pygame.image.load("mole.png")
#设置图像位置
mole_x=0
mole_y=0
#地鼠出现间隔时间
spawn_time=
#上一次地鼠出现的时间
last_spawn_time=time.time()
#游戏时间
game_time=30
#得分
score=0
#游戏状态
game_over=False
#创建字体对象
font=pygame.font.SysFont("Arial",40)
#创建文本对象
score_text=font.render("Score:{}".format(score),True,WHITE)
time_text=font.render("Time:{}".format(game_time),True,WHITE)
#游戏开始时间
start_time=time.time()
#游戏循环
whilenotgame_over:
#处理事件
foreventinpygame.event.get():
ifevent.type==pygame.QUIT:
#关闭窗口退出游戏
pygame.quit()
exit()
elifevent.type==pygame.MOUSEBUTTONDOWN:
#判断是否击中地鼠
ifmole_rect.collidepoint(pygame.mouse.get_pos()):
score+=1
#更新地鼠出现位置
iftime.time()-last_spawn_timespawn_time/:
mole_x=random.randint(0,WIDTH-mole_image.get_width())
mole_y=random.randint(0,HEIGHT-mole_image.get_height())
last_spawn_time=time.time()
#绘制背景
screen.fill(BLACK)
#绘制地鼠
mole_rect=screen.blit(mole_image,(mole_x,mole_y))
#绘制得分和时间
score_text=font.render("Score:{}".format(score),True,WHITE)
time_text=font.render("Time:{}".format(int(game_time)),True,WHITE)
screen.blit(score_text,(10,10))
screen.blit(time_text,(WIDTH-time_text.get_width()-10,10))
#更新游戏时间
iftime.time()-start_time1:
game_time-=1
start_time=time.time()
#判断游戏是否结束
ifgame_time=0:
game_over=True
#刷新屏幕
pygame.display.flip()
#控制游戏帧率
clock.tick(60)
#显示最终得分
game_over_text=font.render("GameOver.FinalScore:{}".format(score),True,RED)