0

I am creating a Discord bot with discord.py. I want it to be a sort of RPG in Discord where you can fight monsters, level up, and go on quests all in Discord. The problem is in the code that generates a list of enemies that the user must fight. As it is right now, it should create 2 enemies of the same type, with different stats.

The code is shown below:

#startBattle method. Creates an enemy and adds them to the user's 'fightingNow' list
def startBattle(id, room, area):

    #prevents player from progressing while in a battle
    playerData[id]['canProgress'] = False

    #Chooses amount of enemies to be created. Set it just 2 for testing reasons
    amount = random.randint(2,2)

    for enemyID in range(0, amount):
        #Creates a modifier to be applied to an enemy's stats
        randomMod = random.randint(-3,3)
        modifier = 1 + (room + randomMod) / 10

        #chooses an enemy from a .json file. Set to only choose one enemy for testing reasons
        enemy = random.randint(1,1)
        enemy = enemyData[str(enemy)]

        #Apply modifiers to related stats
        enemy['maxHP'] = int(modifier * enemy['maxHP'])
        enemy['baseHP'] = enemy['maxHP']
        enemy['baseEnd'] = int(modifier * enemy['baseEnd'])
        enemy['baseAttack'] = int(modifier * enemy['baseAttack'])
        enemy['baseAgi'] = int(modifier * enemy['baseAgi'])
        enemy['basePre'] = int(modifier * enemy['basePre'])
        enemy['baseLvl'] = int(modifier * enemy['baseLvl'])

        #sets the enemies id, used in the battle system to determine who the player is attacking
        enemy['id'] = enemyID

        #print() will be removed in final version.
        print(enemy)

        #Appends the created enemy to the user's list of enemies they are fighting
        playerData[id]['fightingNow'].append(enemy)

    #saves data to some .json files
    _save()

It should work like so: Enemy 1 and enemy 2 are both Skeletons. Enemy 1 has a MaxHP stat of say, 10, while enemy 2's MaxHP is 12. So both of those should be added to the user's 'fightingNow' list. Instead, the list contains two skeletons with a MaxHP of 12. Enemy 1 IS generated, but gets overwritten by a clone of enemy 2. Thank you for any help you can give.

MrFoxGamer
  • 67
  • 6

1 Answers1

1

Dictionaries are mutable objects, so when you append enemy, you are actually appending a reference to enemy, not a copy of enemy. It's a rather easy fix, fortunately - just add .copy():

playerData[id]['fightingNow'].append(enemy.copy())
iz_
  • 15,923
  • 3
  • 25
  • 40