AI科技大本营|玩出花儿了!一文教你用 Python 制作吃豆人游戏! | 附代码,Python( 四 )


hero_sprites,ghost_sprites=level.setupPlayers(HEROPATH,[BlinkyPATH,ClydePATH,InkyPATH,PinkyPATH])
food_sprites=level.setupFood(YELLOW,WHITE)
is_clearance=False
whileTrue:
foreventinpygame.event.get:
ifevent.type==pygame.QUIT:
sys.exit(-1)
pygame.quit
ifevent.type==pygame.KEYDOWN:
ifevent.key==pygame.K_LEFT:
forheroinhero_sprites:
hero.changeSpeed([-1,0])
hero.is_move=True
elifevent.key==pygame.K_RIGHT:
forheroinhero_sprites:
hero.changeSpeed([1,0])
hero.is_move=True
elifevent.key==pygame.K_UP:
forheroinhero_sprites:
hero.changeSpeed([0,-1])
hero.is_move=True
elifevent.key==pygame.K_DOWN:
forheroinhero_sprites:
hero.changeSpeed([0,1])
hero.is_move=True
ifevent.type==pygame.KEYUP:
if(event.key==pygame.K_LEFT)or(event.key==pygame.K_RIGHT)or(event.key==pygame.K_UP)or(event.key==pygame.K_DOWN):
hero.is_move=False
screen.fill(BLACK)
forheroinhero_sprites:
hero.update(wall_sprites,gate_sprites)
hero_sprites.draw(screen)
forheroinhero_sprites:
food_eaten=pygame.sprite.spritecollide(hero,food_sprites,True)
SCORE+=len(food_eaten)
wall_sprites.draw(screen)
gate_sprites.draw(screen)
food_sprites.draw(screen)
forghostinghost_sprites:
#幽灵随机运动(效果不好且有BUG)
'''
res=ghost.update(wall_sprites,None)
whilenotres:
ghost.changeSpeed(ghost.randomDirection)
res=ghost.update(wall_sprites,None)
'''
#指定幽灵运动路径
ifghost.tracks_loc[1]<ghost.tracks[ghost.tracks_loc[0]][2]:
ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0:2])
ghost.tracks_loc[1]+=1
else:
ifghost.tracks_loc[0]<len(ghost.tracks)-1:
ghost.tracks_loc[0]+=1
elifghost.role_name=='Clyde':
ghost.tracks_loc[0]=2
else:
ghost.tracks_loc[0]=0
ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0:2])
ghost.tracks_loc[1]=0
ifghost.tracks_loc[1]<ghost.tracks[ghost.tracks_loc[0]][2]:
ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0:2])
else:
ifghost.tracks_loc[0]<len(ghost.tracks)-1:
loc0=ghost.tracks_loc[0]+1
elifghost.role_name=='Clyde':
loc0=2
else:
loc0=0
ghost.changeSpeed(ghost.tracks[loc0][0:2])
ghost.update(wall_sprites,None)
ghost_sprites.draw(screen)
score_text=font.render("Score:%s"%SCORE,True,RED)
screen.blit(score_text,[10,10])
iflen(food_sprites)==0:
is_clearance=True
break
ifpygame.sprite.groupcollide(hero_sprites,ghost_sprites,False,False):
is_clearance=False
break
pygame.display.flip
clock.tick(10)
returnis_clearance
'''显示文字'''
defshowText(screen,font,is_clearance,flag=False):
clock=pygame.time.Clock
msg='GameOver!'ifnotis_clearanceelse'Congratulations,youwon!'
positions=[[235,233],[65,303],[170,333]]ifnotis_clearanceelse[[145,233],[65,303],[170,333]]
surface=pygame.Surface((400,200))
surface.set_alpha(10)


推荐阅读