所以我是Python的新手,我不明白这个问题。代码如下:
(敌人和玩家都是包含2个变量的列表,例如[1,2])
def AIenemyTurn(enemy,playerPos):
startPos = enemy
print(startPos)
potEnemyPos = enemy
if playerPos[0] > enemy[0]:
potEnemyPos[0] += 1
elif playerPos[0] < enemy[0]:
potEnemyPos[0] -= 1
elif playerPos[1] > enemy[1]:
potEnemyPos[1] += 1
elif playerPos[1] < enemy[1]:
potEnemyPos[1] -= 1
if potEnemyPos not in rocks:
print(potEnemyPos)
print(startPos)
return potEnemyPos
else:
return startPos
这就是Shell中显示的内容:
[1, 2]
[2, 2]
[2, 2]
为什么startPos在第二次打印时会有所不同?我没有在函数中修改它
这是因为列表是可变的,所以将它们赋给两个不同的值意味着这两个值引用同一个列表:
您还可以通过查看
id
进行检查:解决这个问题的一种方法是调用
startPos = list(enemy)
,因为强制转换到list
会生成一个新列表:这是您编辑的代码:
相关问题 更多 >
编程相关推荐