python3.6我的循环继续应用于列表,即使列表被删除

2024-05-18 17:42:57 发布

您现在位置: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.

正如你所看到的,伤害是对所有僵尸造成的,而不仅仅是被攻击的僵尸。你知道吗

对于任何格式错误,我深表歉意,这是我第一次来这里,谢谢你的帮助。你知道吗


Tags: youtargetwhichwithinthp僵尸damage
1条回答
网友
1楼 · 发布于 2024-05-18 17:42:57

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

问题如下:每个zombie的多重列表实际上是一个相同的列表,这意味着如果您尝试修改其中一个副本中的一个元素,那么所有副本中都会发生更改(因为它们是相同的对象)。因此,要让你的几个僵尸都有自己的列表,你必须独立复制原始列表(.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

相关问题 更多 >

    热门问题