How Can I Get New Results From Randint While In A Loop?
My code thus far: from random import randint Dice1 = randint(1,6) Dice2 = randint(1,6) Dice3 = randint(1,6) DiceRoll2 = Dice1 + Dice2 DiceRoll3 = Dice1 + Dice2 + Dice3 class Ite
Solution 1:
You need to make the call to randint everytime. Below is one way to do it
def Dice1(): return randint(1,6)
def Dice2(): return randint(1,6)
def Dice3(): return randint(1,6)
This isn't great though because of all the repeated code. Here is a better way
class Dice(object):
def roll_dice(self):
return randint(1,6)
Dice1 = Dice()
Dice2 = Dice()
Dice3 = Dice()
Now in your code where ever you call Dice1, Dice2 or Dice3; instead call Dice1.roll_dice(), Dice2.roll_dice(), Dice3.roll_dice(). This abstract away the dice implementation and you are free to change it later without having to change your code.
If you need have dice with different number of faces, you only need to change your dice class
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
Solution 2:
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
Post a Comment for "How Can I Get New Results From Randint While In A Loop?"