首页 > 解决方案 > For 循环创建 2 个相同的字典而不是 2 个唯一的字典

问题描述

我正在使用 discord.py 创建一个 Discord 机器人。我希望它成为 Discord 中的一种 RPG,你可以在 Discord 中与怪物战斗、升级和继续任务。问题在于生成用户必须战斗的敌人列表的代码。就像现在一样,它应该创建 2 个具有不同统计数据的相同类型的敌人。

代码如下所示:

#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()

它应该像这样工作:敌人 1 和敌人 2 都是骷髅。敌人 1 的 MaxHP 统计为 10,而敌人 2 的 MaxHP 为 12。所以这两个都应该添加到用户的“fightingNow”列表中。相反,该列表包含两个 MaxHP 为 12 的骷髅。生成了敌人 1,但被敌人 2 的克隆覆盖。感谢您提供的任何帮助。

标签: pythonpython-3.xdiscord.py

解决方案


字典是可变对象,所以当你追加时enemy,你实际上是在追加对 的引用enemy,而不是enemy. 幸运的是,这是一个相当简单的修复 - 只需添加.copy()

playerData[id]['fightingNow'].append(enemy.copy())

推荐阅读