Python 3.6我的循环即使在删除列表时仍继续应用于列表

时间:2017-12-07 08:25:29

标签: python

我正在尝试建立一个基于回合制的战斗游戏,但我遇到了受到伤害的问题。

roomMonsters是一个列表,如:[['A Zombie' , 2 , 2 , 3],['A Zombie , 2 , 2, 3]]

def heroAttack(roomMonsters , heroes):
    target = int(input('Which monster shall you attack? ')) #Which monster to attack
    attacker = int(input('Which hero shall you attack with? ')) #Which hero to attack with
    damage = int(random.randint(int(heroes[attacker][2]) , heroes[attacker][2])*2)    #Calculates damage
    for number in range(0,damage):
        while roomMonsters[target][1] > 0:
            roomMonsters[target][1] = roomMonsters[target][1]-1
            #print('Debug, inflicting pain')

    print('Your' , heroes[attacker][0] , 'attacked' , roomMonsters[target][0] , 'for' , damage , 'damage.') #Prints the result
    checkForMonsterDeath(heroes,roomMonsters,attacker,target)
    return roomMonsters

我预计结果会对一个列表条目造成伤害然后停止,因此会对受到攻击的僵尸造成伤害。

然而,它会对所有僵尸造成伤害。我想这可能是因为checkForMonsterDeath从列表中删除了一个怪物,但是我看不出它是如何导致对同一类型的所有怪物造成伤害的。

游戏玩法看起来像这样:

You enter the room and monsters lie ahead of you...  
You can see:  
0 A Zombie with 2 HP.
1 A Spider with 5 HP.
2 A Zombie with 2 HP.
Which monster shall you attack? 0
Which hero shall you attack with? 1
Your Wielder of Zzzzap attacked A Zombie for 14 damage.
A Zombie exploded in a fiery ball of gloop.
You enter the room and monsters lie ahead of you...  
You can see:  
0 A Spider with 5 HP.
1 A Zombie with 0 HP.

正如你所看到的那样,所有僵尸都受到了伤害,而不仅仅是受到攻击的僵尸。

对于任何不良格式的抱歉,这是我第一次来这里,感谢您的帮助。

1 个答案:

答案 0 :(得分:-1)

这个问题看起来像是列表重复中常见的警告之一。 (类似问题:List of lists changes reflected across sublists unexpectedly

问题如下:你为每个僵尸所拥有的多个列表实际上是同一个,这意味着如果你试图修改其中一个副本中的一个元素,那么所有副本都会发生变化(因为它们是同一个对象)。因此,为了让你的几个僵尸每个都有自己的列表,你必须制作原始列表的独立副本(.copy()就足够了)。看那个例子:

zombieList = ['A Zombie' , 2 , 2 , 3]
badCopyRoomMonsters = [zombieList,zombieList]
#trying to deal damage to only the first zombie
badCopyRoomMonsters[0][1] = 0
print(badCopyRoomMonsters)
print(zombieList) #even the original list got modified because they are all references to the same object

zombieList = ['A Zombie' , 2 , 2 , 3]
goodCopyRoomMonsters =[zombieList.copy(),zombieList.copy()]
#trying to deal damage to only the first zombie
goodCopyRoomMonsters[0][1] = 0
print(goodCopyRoomMonsters)
print(zombieList) #now it's all behaving as expected