import pygame
import time
import sys
import random
from pygame.locals import *
bgColor=pygame.Color(0,0,0)
snakeColor=pygame.Color(255,255,255)
foodColor=pygame.Color(150,120,80)
fontColor=pygame.Color(100,150,120)
def gameOver(playSurface):
gameOverFont=pygame.font.Font('Arial.ttf',72)#设置字体样式
gameOverSurf=gameOverFont.render('GameOver',True,fontColor)
gameOverRect=gameOverSurf.get_rect()#获取实例
gameOverRect.midtop=(320,100)#文字显示的坐标
playSurface.blit(gameOverSurf,gameOverRect)
pygame.display.flip()
time.sleep(3)
pygame.quit()
sys.exit()
def main():
pygame.init()# 初始化pygame
fpsClock=pygame.time.Clock()# 定义多久时间走一次
#初始化弹框的一些变量
playSurface=pygame.display.set_mode((640,480))#窗体大小
pygame.display.set_caption('贪吃蛇')#设置标题
snakePosition=[100,100]#初始化蛇的位置
#保存蛇头以下的坐标
snakeSetments=[[100,100],[80,100],[60,100]]
foodPosition=[300,300]#初始化食物的位置
foodSpwned=1#判断食物是否被吃掉
direction='right'#初始化默认方向
changeDirection=direction#改变方向
while True:
#设置背景颜色
playSurface.fill(bgColor)
#绘制
for position in snakeSetments:
pygame.draw.rect(playSurface,snakeColor,Rect(position[0],position[1],20,20))
pygame.draw.rect(playSurface,foodColor,Rect(foodPosition[0],foodPosition[1], 20, 20))
pygame.display.flip()#刷新
for event in pygame.event.get():
#判断点击的按钮
if event.type==QUIT:
pygame.quit()
sys.exit()
elif event.type==KEYDOWN:
if event.key==K_RIGHT or event.key==ord('d'):
changeDirection='right'
if event.key==K_LEFT or event.key==ord('a'):
changeDirection='left'
if event.key==K_UP or event.key==ord('w'):
changeDirection='up'
if event.key==K_DOWN or event.key==ord('s'):
changeDirection='down'
if event.key==K_ESCAPE:
pygame.event.pos(pygame.event.Event(QUIT))
#判断如果输入的是反方向
if changeDirection=='right'and not direction=='left':
direction=changeDirection
if changeDirection == 'left' and not direction == 'right':
direction=changeDirection
if changeDirection=='up'and not direction=='down':
direction=changeDirection
if changeDirection=='down'and not direction=='up':
direction=changeDirection
#根据方向移动蛇头的坐标
if direction=='right':
snakePosition[0]+=20
if direction == 'left':
snakePosition[0]-= 20
if direction == 'up':
snakePosition[1]-= 20
if direction == 'down':
snakePosition[1]+= 20
#增加蛇的长度
snakeSetments.insert(0,list(snakePosition))
#判断是否吃掉食物
if snakePosition[0]==foodPosition[0] and snakePosition[1]==foodPosition[1]:
foodSpwned=0
else:
snakeSetments.pop()#吃掉食物删掉最后一个,使整体没有变化
#如果吃掉,则随机生成
if foodSpwned==0:
x=random.randrange(1,32)
y=random.randrange(1,24)
foodPosition=[int (x*20),int (y*20)]
foodSpwned=1
fpsClock.tick(5)#游戏的速度
#超出边界则游戏结束
if snakePosition[0]>620 or snakePosition[0]<0:
gameOver(playSurface)
if snakePosition[1]>460 or snakePosition[1]<0:
gameOver(playSurface)
if __name__ == '__main__':
main()