Pygame Zero之贪吃蛇(三)

本文继续来研究如何移动小蛇,这一次是让小蛇左转和右转。上一篇讲到小蛇只能前进,今天就让小蛇学会转弯。

如果小蛇本来是向右移动的,那么右转以后,小蛇就会向下移动,只需要把新蛇头的位置设置在旧蛇头Snake[0]的下方

1
2
3
4
5
6
7
8
9
10
# 前置代码见9-2.py

def update():
newSnakeHead = Actor('snake1') # 创建新蛇头
# 设定新蛇头的坐标,小蛇向下移动,新蛇头在旧蛇头下方
newSnakeHead.x = Snake[0].x
newSnakeHead.y = Snake[0].y + TILE_SIZE
Snake.insert(0, newSnakeHead) # 把新蛇头加入列表的最前面
del Snake[len(Snake) - 1] # 删除旧蛇尾
time.sleep(0.2)

类似的,我们就可以完成小蛇的所有方向移动了。定义一个变量来表示小蛇的移动方向。在update函数中,判断这个变量的值,就可以控制小蛇向不同的方向移动。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 前置代码见9-2.py

direction = 'right' # 控制小蛇运动方向,默认向右


def update():
newSnakeHead = Actor('snake1') # 创建新蛇头
# 判断变量direction的值,执行相应操作
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 == 'left':
newSnakeHead.x = Snake[0].x - TILE_SIZE
newSnakeHead.y = Snake[0].y
if direction == 'right':
newSnakeHead.x = Snake[0].x + TILE_SIZE
newSnakeHead.y = Snake[0].y
Snake.insert(0, newSnakeHead)
del Snake[len(Snake) - 1]
time.sleep(0.2)

现在小蛇已经可以向四个方向移动了,我们需要加上一个控制的功能。通过按下方向键来修改direction的值就可以了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
direction = 'right'  # 控制小蛇运动方向,默认向右


def update():
global direction # 将direction设为全局变量
if keyboard.left:
direction = 'left'
if keyboard.right:
direction = 'right'
if keyboard.up:
direction = 'up'
if keyboard.down:
direction = 'down'
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 == 'left':
newSnakeHead.x = Snake[0].x - TILE_SIZE
newSnakeHead.y = Snake[0].y
if direction == 'right':
newSnakeHead.x = Snake[0].x + TILE_SIZE
newSnakeHead.y = Snake[0].y
Snake.insert(0, newSnakeHead)
del Snake[len(Snake) - 1]
time.sleep(0.2)

看一看效果图吧: