代码仅供参考
import pgzrun
import time
import random
TILE_SIZE =20#小蛇方块的大小
WIDTH = 40*TILE_SIZE#设置屏幕的大小
HEIGHT = 30*TILE_SIZE
snakeHead1=Actor('snake1')#导入蛇头图片
snakeHead1.x=WIDTH/2 #设置蛇头位置
snakeHead1.y=HEIGHT/2
cookie=Actor('cookie')#导入食物
cookie.x = random.randint(10, 30)*TILE_SIZE#随机出现食物位置
cookie.y = random.randint(10, 30)*TILE_SIZE
Snake=[]#创建贪吃蛇列表
Snake.append(snakeHead1)
direction='up'
isLoose=False
score=0
for i in range(4): # 再为蛇添加4段蛇身
snakebody = Actor('snake1') # 导入蛇身方块图片
snakebody.x = Snake[i].x - TILE_SIZE # 蛇身方块图片的x坐标
snakebody.y = Snake[i].y # 蛇身方块图片的y坐标
Snake.append(snakebody) # 把蛇身加入到列表中
def draw():#绘制模块
screen.clear()#每帧清除屏幕
screen.fill('white')
for snakebody in Snake:#绘制蛇
snakebody.draw()
cookie.draw()
screen.draw.text("得分:"+str(score),(360,20),fontsize=25,fontname='s',color='blue')
if isLoose:
screen.draw.text("游戏失败!", (180, HEIGHT/2-100),
fontsize=100, fontname='s', color='blue')
def update():#每帧更新操作
global direction
if keyboard.left:
direction= 'left'#左移动
if keyboard.right:
direction = 'right'# 右移动
if keyboard.up:
direction = 'up' # 上移动
if keyboard.down:
direction = 'down' # 下移动
def moveSnake():#和蛇移动相关的一些操作
global direction,isLoose,score
newSnakeHead=Actor('snake1')
if direction=='up':
newSnakeHead.x = Snake[0].x
newSnakeHead.y = Snake[0].y-TILE_SIZE
if direction == 'down':
newSnakeHead.x = Snake[0].x
newSnakeHead.y = Snake[0].y+TILE_SIZE
if direction =='right':
newSnakeHead.x = Snake[0].x+TILE_SIZE
newSnakeHead.y = Snake[0].y
if direction == 'left':
newSnakeHead.x = Snake[0].x-TILE_SIZE
newSnakeHead.y = Snake[0].y
#判定游戏失败
if newSnakeHead.y < 0 or newSnakeHead.y > HEIGHT \
or newSnakeHead.x < 0 or newSnakeHead.x>WIDTH:
isLoose=True
for snakebody in Snake:
if newSnakeHead.x==snakebody.x and newSnakeHead.y==snakebody.y:
isLoose=True
break
#当小蛇食物时,不删去最后一个,也就是长度加1;
if newSnakeHead.x==cookie.x and newSnakeHead.y==cookie.y:
cookie.x = random.randint(8,30)*TILE_SIZE
cookie.y = random.randint(8,30)*TILE_SIZE
score =score+ 1
else:
del Snake[len(Snake)-1]
Snake.insert(0,newSnakeHead)
clock.schedule_unique(moveSnake,0.2)#下一次隔0.2s调用
moveSnake()
pgzrun.go()