如何在循环中从randint获取新结果?

时间:2016-06-01 13:09:57

标签: python python-3.x while-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

每次进入"攻击"你得到一个DiceRoll3的随机结果(从1到6的三个随机数,那三次),加上剑的值并从怪物的起始生命值中减去它。这很顺利,直到我进入"攻击"第二次,导致相同的伤害和相同的健康状况被打印而不是使用新值。我该怎么做呢?

2 个答案:

答案 0 :(得分:1)

将你的骰子滚动到一个单独的函数中,并在循环中计算DamageNewHealth。 (另外,更新你的怪物的健康状况。:))

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

答案 1 :(得分:1)

你需要每次都调用randint。以下是一种方法

def Dice1(): return  randint(1,6)
def Dice2(): return  randint(1,6)
def Dice3(): return  randint(1,6)

由于所有重复的代码,这并不是很好。这是一个更好的方法

class Dice(object):
    def roll_dice(self):
        return randint(1,6)

Dice1 = Dice()
Dice2 = Dice()
Dice3 = Dice()

现在,您可以在代码中调用Dice1Dice2Dice3;而是致电Dice1.roll_dice()Dice2.roll_dice()Dice3.roll_dice()。这抽象了骰子实现,您可以在以后更改它而无需更改代码。

如果你需要骰子有不同数量的面孔,你只需要改变你的骰子类

class Dice(object):
    def __init__ (self, num_faces=6):
        self.faces = num_faces

    def roll_dice(self):
        return randint(1,self.faces)

Dice1 = Dice() # 6 faced die
Dice2 = Dice(20) # 20 faced die