python - 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 的克隆覆盖。感谢您提供的任何帮助。
解决方案
字典是可变对象,所以当你追加时enemy
,你实际上是在追加对 的引用enemy
,而不是enemy
. 幸运的是,这是一个相当简单的修复 - 只需添加.copy()
:
playerData[id]['fightingNow'].append(enemy.copy())
推荐阅读
- javascript - 如何在 jQuery 日期选择器中启用从数据库中获取的特定日期
- node.js - 如何在 Cookie 上指定 SameSite 和 Secure(使用 axios/React/Node Express)
- python - 无论当前目录如何,Mac 上的 ~/Library 的 Chdir 都返回错误
- javascript - 当我运行此代码时,出现错误“未定义窗口”
- arrays - 当通过函数作为参数传递数组时,数组是否索引为零?C 编程
- javascript - 为什么允许“让”作为变量名?
- firebase - react-native ios项目中的Firebase身份验证问题
- python - Google App Engine 应用程序 - klein micro web 框架出现 502 bad gateway 错误
- reactjs - 如何将对象插入到反应中的对象列表中?
- javascript - 从索引 2:3 获取数组中的项目