# 循环 while True:
fpsClock.tick(5) for event in pygame.event.get(): if event.type == QUIT:
gameOver() elif event.type == KEYDOWN: if event.key == K_RIGHT:
changeDirection = "right" if event.key == K_LEFT:
changeDirection = "left" if event.key == K_UP:
changeDirection = "up" if event.key == K_DOWN:
changeDirection = "down"
# 对应该键盘上的Esc键 if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
# 3.6确定方向 if changeDirection == "left" and not direction == "right":
direction = changeDirection if changeDirection == "right" and not direction == "left":
direction = changeDirection if changeDirection == "up" and not direction == "down":
direction = changeDirection if changeDirection == "down" and not direction == "up":
direction = changeDirection
# if (changeDirection == "left" and not direction == "right") or \
# (changeDirection == "right" and not direction == "left") or \
# (changeDirection == "up" and not direction == "down") or \
# (changeDirection == "down" and not direction == "up"):
# direction = changeDirection
# 3.7 根据方向移动蛇头的坐标 if direction == "right":
snakePosition[0] += 20 if direction == "left":
snakePosition[0] -= 20 if direction == "up":
snakePosition[1] -= 20 if direction == "down":
snakePosition[1] += 20
# 3.8增加蛇的长度
snakeBody.insert(0, list(snakePosition))
# 如果贪食蛇和目标方块的位置重合了,则增加蛇的长度,目标方块为0 if snakePosition[0] == targetPosition[0] and snakePosition[1] == targetPosition[1]:
targetflag = 0 else:
snakeBody.pop()
if targetflag == 0:
# 随机生成一个目标方块
x = random.randrange(1, 32)
y = random.randrange(1, 24)
# 整个界面的范围是640 480
targetPosition = [int(x*20), int(y*20)]
targetflag = 1
playSurface.fill(blackColor)
# 画蛇 画方块 for position in snakeBody:
# surface:指定绘制的编辑区 color:颜色Rect(x,y)(width,height) width:线条的粗细,若为0则填充,1为透明
pygame.draw.rect(playSurface, whiteColor, Rect(position[0], position[1], 20, 20)) # 画蛇
pygame.draw.rect(playSurface, redColor, Rect(targetPosition[0], targetPosition[1], 20, 20)) # 画矩形
# 4.更新显示到屏幕上
pygame.display.update()
# 判断游戏结束 if snakePosition[0] > 620 or snakePosition[0] < 0:
gameOver() elif snakePosition[1] > 480 or snakePosition[1] < 0:
gameOver()