pygame 中的一个单位蛇,尽管它更长[重复]

问题描述 投票:0回答:1

好吧,我一直在玩 pygame 和 python,我已经构建了蛇,但这是一个非常奇怪的系统,我想为它构建一个探路者,可以绕过障碍物(蛇体)找到苹果的路径,但是身体的运动很不稳定,我知道这听起来很愚蠢,因为我什至无法制作蛇,我该如何制作探路者,但我以前做过,所以这里是:

蛇看起来像这样:snake =

[[1,0],[0,0]]

方向仅存储在元组中:

direction = (xmov = 1,ymov = 0)

time += 1
if time > 30:
    time = 0
    snakeindex = len(snake)-1
    snakeindex will be one
    while snakeindex > 0:
        this activates once and as far as it know it works
        snake[snakeindex] = snake[snakeindex-1]
        snakeindex -= 1
        the snake will end up like  this: [[1,0],[1,0]]
    but then here:
    snake[0][0] += direction[0]
    snake[0][1] += direction[1]
    the snake will then look like this: [[2,0],[2,0]]
python pygame
1个回答
-1
投票

Python 优化有时对于列表、字典等可变对象来说很混乱。你的蛇部分只是一部分,以及对此部分的引用。 你不应该做这样的事情:

a = [1,2]
b = a
# Now you might think there's to arrays
# But it's one array, and b is just a reference to a.
# If you change b or a both changes.
a[0] = 9
print(a, b)
# This will print out [9,2] and [9,2]

使用 .copy() 实际复制列表:

snake[snakeindex] = snake[snakeindex-1].copy()
© www.soinside.com 2019 - 2024. All rights reserved.