1、python贪吃蛇报告_python实现贪吃蛇游戏本实例为家分享了python实现贪吃蛇游戏的具体代码,供家参考,具体内容如下本稍作改动,修复些bug,原链接:python实现贪吃蛇游戏#!/usr/bin/env python#_*_ coding:utf-8 _*_import pygame,sys,time,randomfrom pygame.locals import*redColour=pygame.Color(255,0,0)blackColour=pygame.Color(0,0,0)whiteColour=pygame.Color(255,255,255)greyColour=
2、pygame.Color(150,150,150)def gameOver(playSurface):gameOverFont=pygame.font.Font(arial.ttf,72)gameOverSurf=gameOverFont.render(Game Over,True,greyColour)gameOverRect=gameOverSurf.get_rect()gameOverRect.midtop=(320,10)playSurface.blit(gameOverSurf,gameOverRect)pygame.display.flip()time.sleep(5)pygame
3、.quit()sys.exit()def main():pygame.init()playSurface=pygame.display.set_mode(640,480)fpsClock=pygame.time.Clock()pygame.display.set_caption(Snake Liu)snakePosition=100,100snakeSegments=100,100,80,100,60,100raspberryPosition=300,300raspberrySpawned=1direction=rightchangeDirection=directionwhile True:
4、for event in pygame.event.get():if event.type=QUIT:sys.exit()elif event.type=KEYDOWN:if event.key=K_RIGHT or event.key=ord(d):changeDirection=rightif event.key=K_LEFT or event.key=ord(a):changeDirection=leftif event.key=K_UP or event.key=ord(w):changeDirection=upif event.key=K_DOWN or event.key=ord(
5、s):changeDirection=downif event.key=K_ESCAPE:pygame.event.post(pygame.event.Event(QUIT)#判断是否输了反向,与原有改动if changeDirection=right:direction=changeDirectionif changeDirection=left:direction=changeDirectionif changeDirection=up:direction=changeDirectionif changeDirection=down:direction=changeDirection#根据
6、向移动蛇头的坐标if direction=right:snakePosition0+=20if direction=left:snakePosition0-=20if direction=up:snakePosition1-=20if direction=down:snakePosition1+=20#增加蛇的长度snakeSegments.insert(0,list(snakePosition)#判断是否吃掉了树莓if snakePosition0=raspberryPosition0 and snakePosition1=raspberryPosition1:raspberrySpawne
7、d=0else:snakeSegments.pop()#如果吃掉树莓,则重新成树莓if raspberrySpawned=0:x=random.randrange(1,32)y=random.randrange(1,24)raspberryPosition=int(x*20),int(y*20)raspberrySpawned=1#刷新pygame显层playSurface.fill(blackColour)for position in snakeSegments:pygame.draw.rect(playSurface,whiteColour,Rect(position0,position
8、1,20,20)pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition0,raspberryPosition1,20,20)pygame.display.flip()#判断是否死亡,后和原有改动if snakePosition0 620 or snakePosition0 460 or snakePosition1 0:gameOver(playSurface)for snakeBody in snakeSegments1:if snakePosition0=snakeBody0 and snakePosition1=snakeBody1:gameOver(playSurface)fpsClock.tick(5)if _name_=_main_:main()以上就是本的全部内容,希望对家的学习有所帮助,也希望家多多持聚学院。