Python PyGame制作蛇游戏

时间:2019-12-31 06:34:23

标签: python pygame

我目前正在做蛇游戏,但是遇到一些我不理解的东西。

def moveHead():
global snakeList
lenlist = list(range(1,len(snakeList)))
lenlist.reverse()
for i in lenlist:
    snakeList[i] = snakeList[i-1]
snakeList[0][1] += 30
print("AF")
print(snakeList)

基本上,snakeList是另一个列表中的坐标列表。例如[[25,25],[0,0]] 应该发生的是,列表中的项目应该复制列表中的前一个项目,但列表中的前一个项目除外。在上述示例中,[0,0]将变成[25,25],而for循环下面的行会将整个内容更改为[[25,55],[25,25]],不是吗?由于某种原因,第二个项目也会复制前面的更改项目,从而将snakeList变成[[25,55],[25,55]]。抱歉,如果解释不清楚:(非常感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

使用snakeList[i] = snakeList[i-1],实际上没有两个子列表。分配只是将引用复制到子列表,而不是实际的子列表,因此snakeList[i]snakeList[i-1]都在分配后引用了相同的子列表,因此,当一个元素更改为另一个元素时分别改变。

为了获得理想的结果,您应该使用内置的list.copy()方法:

snakeList[i] = snakeList[i-1].copy()

运行了上面的更正代码后,结果是:

AF
[[25, 55], [25, 25]]

答案 1 :(得分:0)

嘿,看来您要花很长的路来做python内置的功能

因此,您似乎希望列表中除第一项之外的所有项?

您可以通过对数组中的“:”进行一些操作来实现此目的

# first we can get the last index of the array, e.g. snakeList
last_i = len(snakeList)
# then we can use the part of the array we'd like, in this case everything else except the first
snake_list_copy = snakeList[1:last_i]
# you can then make use of python's simple array manipulation to add any new items to the array
snakeList = snake_list_copy + [ new_items ] # this will create a new array with new items at the end

作为一个简单的示例,请考虑以下内容

a = [2, 4, 6, 8]
last_i = len(a)
b = a[1:last_i] # b is now [4, 6, 8]
b = [0,2] + b + [10,12] # b is now [0, 2, 4, 6, 8, 10, 12]

答案 2 :(得分:0)

以下代码将解决您的问题:

def moveHead():
    global snakeList
    snakeList.insert(0, snakeList[0].copy())
    del snakeList[-1]
    snakeList[0][1] += 30

  

应该发生的是,除索引0中的元素外,该项目向右移动。在上述示例中,[0,0]将变成[25,25],并且for下方的行循环会将整个内容更改为[[25,55],[25,25]]

不。请注意,索引通过以下方式反转:

  
lenlist = list(range(1,len(snakeList)))
lenlist.reverse()

如果len(snakeList)为4,则在这两行之后lenlist的内容为[3, 2, 1]

因此for循环以相反的顺序运行。如果snakeList的内容为[[0,0],[25,0],[50,0],[75,0]],则在处理循环之后

  
for i in lenlist:
   snakeList[i] = snakeList[i-1]

列表的内容为[[0, 0], [25, 0], [50, 0], [75, 0]]

现在发生的是,列表的第1个和第2个元素引用了同一对象。

所以在这行之后

  
snakeList[0][1] += 30

列表的内容为[[0, 30], [0, 30], [25, 0], [50, 0]]

如果重复此过程,列表的内容将更改为[[0, 60], [0, 60], [0, 60], [25, 0]],然后更改为[[0, 90], [0, 90], [0, 90], [0, 90]]。现在,列表中的所有元素都引用同一个列表对象。

您可以通过对list元素(列表的每个元素也是一个列表)进行浅表复制(list.copy())来摆脱这种情况:

snakeList[i] = snakeList[i-1].copy()

如果您想将列表的元素向右移动,那么在列表的顶部添加一个新元素并删除列表的尾部元素也可以完成此工作:

snakeList.insert(0, snakeList[0].copy())
del snakeList[-1]