I am coding a text adventure in python. I have a sheriff NPC that counts all item
objects in player.inventory
, and if item.name == "dead goblin"
then the item is removed from the list, and goblins_taken += 1
:
if "sheriff" in player.action and "talk" in player.action and player.location == sheriff:
goblins_taken = 0
for item in player.inventory:
if item.name == "dead goblin":
goblins_taken += 1
player.inventory.remove(item)
write("The sheriff says, 'Good job. You have killed " + str(goblins_taken) + " goblins!")
The problem with this code was the fact that if the player killed 2 goblins, the sheriff would say that the player killed 1 goblin, not 2.
I tried to simplify the problem in IDLE and realized that it was an indexing problem:
>>> foo = ['a', 'b', 'c', 'd', 'e']
>>> foo[2]
'c' # With b
>>> foo.remove('b')
>>> foo[2]
'd' # Without b, index is shifted down
Is there some better method of removing items from a list than list.remove()
? Or is there some way to fix this problem?