首页 > 解决方案 > 蛇与 Python 和 Pygame

问题描述

我目前正在为我的编码课程做一个蛇项目。我能够让蛇移动,每个身体部位都跟随它前面的那个。但是,我很难改变蛇的方向。这是当前的示例代码。

snakeHeadX = 400
snakeHeadY = 400

a = [[snakeHeadX,snakeHeadY],[snakeHeadX - 20,snakeHeadY], [snakeHeadX-20-20,snakeHeadY]]

for i in range(len(a) -1, -1, -1):
    if i == 0:
        continue

    [a[i][0], a[i][1]] = [a[i-1][0], a[i-1][1]]
    if i == 0:
        continue
a[0][0] = a[0][0] + 20

a[0][0] = a[0][0] + 20就是将蛇头位置在 X 上移动 20 的原因。关于如何改变方向的任何想法,例如说a[0][1] = a[0][1] + 20,这会将蛇的头在 Y 上向上移动 20?

标签: python

解决方案


您可以创建变量“方向”,它可以存储您的头部前进方向(即“上”、“下”、“左”或“右”)的值,并基于此您可以移动您的蛇但是每个“块” “你的蛇会同时改变方向。

这是您需要做的:

    snake_start_x = 400
    snake_start_y = 400
    snake_block_size = 20

    snake = [] #please, use names that make sense, not a
    for i in range(3): #a bit more elegant than what you did to create snake
        snake.append([snake_start_x-i*snake_block_size, snake_start_y])

    def move_head(direction):
        global snake #if you would pass snake as an argument it would create another instance. Here where're working directly on snake

        if direction == "up": #change y by -20
            snake[0][1] -= snake_block_size

        elif direction == "down": #change y by 20
            snake[0][1] += snake_block_size

        elif direction == "left": #change x by -20
            snake[0][0] -= snake_block_size

        elif direction == "right": #change x by 20
            snake[0][0] += snake_block_size

    def move_tail(): #
        global snake
        for i in range(len(snake)-1, 0, -1): #looping backwards without including head
            snake[i][0] = snake[i-1][0]
            snake[i][1] = snake[i-1][1]

然后你需要在你的循环中调用它

    d = "up" # you can change it on key-press for example
    while True: #your main loop
        move_tail() #first snake moves tail up to it's head
        move_head(d) #then head "bounces" in the right direction

        #draw it then or whatever...

我认为有一些方法可以做到这一点(也许让蛇成为一个对象?)但我想出了这个相对简单的方法。

编辑:您可以在 move_head 函数中添加碰撞检测,或者在移动完成后调用另一个检查它的函数。这是一个例子:

    def is_in_wall(WIDTH, HEIGHT):
        global snake
        if snake[0][0] < 0: # too far left
            return True
        elif snake[0][0]+snake_block_size > WIDTH: # too far right
            return True
        elif snake[0][1] < 0: # too far up
            return True
        elif snake[0][1]+snake_block_size > HEIGHT: # too far down
            return True
        else:
            return False

在你的循环中:

    if is_in_wall(WIDTH, HEIGHT): #WIDTH and HEIGHT are dimensions of your window 
        #die or stop the game bacause snake has crossed the border

推荐阅读