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
defDice1(): return randint(1,6)
defDice2(): return randint(1,6)
defDice3(): 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
classDice(object):def__init__(self, num_faces=6):
self.faces = num_faces
defroll_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
defdice_roll(times):
sum = 0for i inrange(times):
sum += randint(1, 6)
returnsumclassItem(object):
def__init__(self, name, value, desc):
self.name = name
self.value = value
self.desc = desc
sword = Item("Sword", 2, "A regular sword.")
classMonster(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!")
whileTrue:
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 valueprint("You swing your", sword.name, "for", Damage, "damage!")
print("The", monster.name, "is now at", NewHealth, "HP!")
elif action[0] == "exit":
breakif monster.health < 1:
print("You win!")
break
Post a Comment for "How Can I Get New Results From Randint While In A Loop?"