python实现贪吃蛇游戏
本文实例为大家分享了python实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下
本文稍作改动,修复一些bug,原文链接:python实现贪吃蛇游戏
#!/usr/bin/envpython #__*__coding:utf-8__*__ importpygame,sys,time,random frompygame.localsimport* redColour=pygame.Color(255,0,0) blackColour=pygame.Color(0,0,0) whiteColour=pygame.Color(255,255,255) greyColour=pygame.Color(150,150,150) defgameOver(playSurface): gameOverFont=pygame.font.Font('arial.ttf',72) gameOverSurf=gameOverFont.render('GameOver',True,greyColour) gameOverRect=gameOverSurf.get_rect() gameOverRect.midtop=(320,10) playSurface.blit(gameOverSurf,gameOverRect) pygame.display.flip() time.sleep(5) pygame.quit() sys.exit() defmain(): pygame.init() playSurface=pygame.display.set_mode((640,480)) fpsClock=pygame.time.Clock() pygame.display.set_caption('SnakeLiu') snakePosition=[100,100] snakeSegments=[[100,100],[80,100],[60,100]] raspberryPosition=[300,300] raspberrySpawned=1 direction='right' changeDirection=direction whileTrue: foreventinpygame.event.get(): ifevent.type==QUIT: sys.exit() elifevent.type==KEYDOWN: ifevent.key==K_RIGHTorevent.key==ord('d'): changeDirection='right' ifevent.key==K_LEFTorevent.key==ord('a'): changeDirection='left' ifevent.key==K_UPorevent.key==ord('w'): changeDirection='up' ifevent.key==K_DOWNorevent.key==ord('s'): changeDirection='down' ifevent.key==K_ESCAPE: pygame.event.post(pygame.event.Event(QUIT)) #判断是否输入了反方向,与原文有改动 ifchangeDirection=='right': direction=changeDirection ifchangeDirection=='left': direction=changeDirection ifchangeDirection=='up': direction=changeDirection ifchangeDirection=='down': direction=changeDirection #根据方向移动蛇头的坐标 ifdirection=='right': snakePosition[0]+=20 ifdirection=='left': snakePosition[0]-=20 ifdirection=='up': snakePosition[1]-=20 ifdirection=='down': snakePosition[1]+=20 #增加蛇的长度 snakeSegments.insert(0,list(snakePosition)) #判断是否吃掉了树莓 ifsnakePosition[0]==raspberryPosition[0]andsnakePosition[1]==raspberryPosition[1]: raspberrySpawned=0 else: snakeSegments.pop() #如果吃掉树莓,则重新生成树莓 ifraspberrySpawned==0: x=random.randrange(1,32) y=random.randrange(1,24) raspberryPosition=[int(x*20),int(y*20)] raspberrySpawned=1 #刷新pygame显示层 playSurface.fill(blackColour) forpositioninsnakeSegments: pygame.draw.rect(playSurface,whiteColour,Rect(position[0],position[1],20,20)) pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0],raspberryPosition[1],20,20)) pygame.display.flip() #判断是否死亡,后面几行和原文有改动 ifsnakePosition[0]>620orsnakePosition[0]<0: gameOver(playSurface) ifsnakePosition[1]>460orsnakePosition[1]<0: gameOver(playSurface) forsnakeBodyinsnakeSegments[1:]: ifsnakePosition[0]==snakeBody[0]andsnakePosition[1]==snakeBody[1]: gameOver(playSurface) fpsClock.tick(5) if__name__=="__main__": main()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。