如何在循环中从 randint 获得新结果? [英] How can I get new results from randint while in a loop?
问题描述
到目前为止我的代码:
from random import randint
Dice1 = randint(1,6)
Dice2 = randint(1,6)
Dice3 = randint(1,6)
DiceRoll2 = Dice1 + Dice2
DiceRoll3 = Dice1 + Dice2 + Dice3
class Item(object):
def __init__(self, name, value, desc):
self.name = name
self.value = value
self.desc = desc
sword = Item("Sword", 2, "A regular sword.")
class Monster(object):
def __init__(self, name, health, attack):
self.name = name
self.health = health
self.attack = attack
monster = Monster("Monster", 50, DiceRoll2)
Damage = DiceRoll3 + sword.value
NewHealth = monster.health - Damage
print("You see a monster!")
while True:
action = input("? ").lower().split()
if action[0] == "attack":
print("You swing your", sword.name, "for", Damage, "damage!")
print("The", monster.name, "is now at", NewHealth, "HP!")
elif action[0] == "exit":
break
意思是每次输入attack"都会得到DiceRoll3的随机结果(1到6的三个随机数,即3次),加上剑的值,然后从怪物的起始生命值中减去该值.这一切顺利,直到我第二次输入攻击",这会导致相同的伤害和相同的健康降低,而不是使用新值.我该如何正确执行此操作?
The intension is that with every time you enter "attack" you get a random result of DiceRoll3 (three random numbers from 1 to 6, that three times), add the value of the sword and substract that from the monster's starting health. This goes well until I enter "attack" a second time, which results in the same damage and the same reduced health being printed instead of using a new value. How can I properly do this?
推荐答案
把你的掷骰子放到一个单独的函数中,并在你的循环中计算 Damage
和 NewHealth
.(另外,更新你怪物的健康.:))
Put your dice-rolling into a separate function and calculate Damage
and NewHealth
inside your loop. (Also, update your Monster's health. :))
from random import randint
def dice_roll(times):
sum = 0
for i in range(times):
sum += randint(1, 6)
return sum
class Item(object):
def __init__(self, name, value, desc):
self.name = name
self.value = value
self.desc = desc
sword = Item("Sword", 2, "A regular sword.")
class Monster(object):
def __init__(self, name, health, attack):
self.name = name
self.health = health
self.attack = attack
monster = Monster("Monster", 50, dice_roll(2))
print("You see a monster!")
while True:
action = input("? ").lower().split()
if action[0] == "attack":
Damage = dice_roll(3) + sword.value
NewHealth = max(0, monster.health - Damage) #prevent a negative health value
monster.health = NewHealth #save the new health value
print("You swing your", sword.name, "for", Damage, "damage!")
print("The", monster.name, "is now at", NewHealth, "HP!")
elif action[0] == "exit":
break
if monster.health < 1:
print("You win!")
break
这篇关于如何在循环中从 randint 获得新结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!