# 通过键盘控制蛇的运动
while True:
# 从队列中获取事件
for event in pygame.event.get():
# 判断是否为退出事件
if event.type == QUIT:
pygame.quit()
sys.exit()
# 按键事件
elif event.type == KEYDOWN:
# 如果是右键头或者是d,蛇向右移动
if event.key == K_RIGHT or event.key == K_d:
changeDirection = 'right'
# 如果是左键头或者是a,蛇向左移动
if event.key == K_LEFT or event.key == K_a:
changeDirection = 'left'
if event.key == K_UP or event.key == K_w:
changeDirection = 'up'
if event.key == K_DOWN or event.key == K_s:
changeDirection = 'down'
# 对应键盘上的Esc键,表示退出
if event.key == K_ESCAPE:
pygame.event.post(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
# 增加蛇的长度
snakeSegments.insert(0, list(snakePosition))
# 判断是否吃到食物
if snakePosition[0] == foodPostion[0] and snakePosition[1] == foodPostion[1]:
foodTotal = 0
else:
snakeSegments.pop() # 每次将最后一单位蛇身剔除列表
# 如果食物为0 重新生成食物
if foodTotal == 0:
x = random.randrange(1, 50)
y = random.randrange(1, 30)
foodPostion = [int(x * 20), int(y * 20)]
foodTotal = 1
# 绘制pygame显示层
screen.fill(blackColor)
网友评论
我要评论