我制作了基于文字的游戏,我希望玩家能够在整个游戏中与怪物进行战斗。我将玩家统计数据存储在字典中,而对于攻击我使用的是random.randint(a,b)。问题在于它存储在战斗的while循环之外。因此攻击始终是相同的,但我希望它在整个循环中改变。
到目前为止,我唯一能想到的是将它作为字符串存储在字典中,然后使用slice来取消引号,然后使用int()使它不再是整数。这是我尝试过的最后一件事。法术已被评论出来,直到我能弄清楚
import random
player = {"attack":"(random.randint(2,4))", "health": 50}
goblin = {"name": "goblin", "attack": "(random.randint(1,3))", "health": 30}
def battle(user, monster):
for key in player:
if key != "health":
print(key)
while goblin["health"] > 0:
user["attack"] = int(user["attack"][1:-1])
monster["attack"] = int(monster["attack"][1:-1])
print(user["attack"])
print(monster["attack"])
select = input("Would you like to attack or use a spell?")
if select == "attack":
print(user["attack"])
goblin["health"] -= user["attack"]
print("The", (monster["name"]), "is at", (monster["health"]),"health")
user["health"] -= goblin["attack"]
print("The goblin hit you for", goblin["attack"], "damage, you are at", user["health"])
if user["health"] < 0:
print("You were killed by the ")
print("You killed the goblin!")
battle(player, goblin)
我知道这是一个奇怪的问题。任何帮助将不胜感激。
答案 0 :(得分:3)
你将不能使用int()
,你必须eval()
,这通常被建议反安全问题可能不是一个游戏的大问题,但它' d,主观上,也是一种有点笨重和不雅的设计。
无视更大的设计图片,有什么东西阻止你将攻击简单地定义为词典中的匿名函数吗?
player = {"attack": lambda: random.randint(2, 4), "health": 50}
以后您可以这样做,例如,
goblin["health"] -= player["attack"]()
您还可以将损伤计算定义为独立功能:
player = {"attack_skill_factor": 2, "health": 50, "defense_skill_factor": 2}
goblin = {"attack_skill_factor": 1, "health": 30, "defense_skill_factor": 1}
def calculate_damage(aggressor, victim):
return (
random.randint(1, 3) *
aggressor['attack_skill_factor'] /
victim['defense_skill_factor'])
# Action
damage = calculate_damage(goblin, player)
player['health'] -= damage
print(
"The goblin hit you for {damage} damage, "
"you are at {health}".
format(damage=damage, health=player['health'])
下一个逻辑步骤可能是使用类以OOP方式定义玩家和NPC。
答案 1 :(得分:1)
为什么不使用:
player = {"attack":"2-4", "health": 50}
goblin = {"name": "goblin", "attack": "1-3", "health": 30}
然后使用拆分(使用' - '作为分隔符字符串)来获取攻击的上限和下限,然后您可以计算循环内的随机值:
user["attack"] = random.randint(int(player["attack"].split('-')[0], int(player["attack"].split('-')[1])