I am creating a game along the lines of Yahtzee the dice rolling game. I have to give the user 5 dice rolled, and ask them a 5 digit number of which dice they'd like to re-roll. For example:
Your roll is: 5 1 5 5 1
Which dice should I roll again?: 234
Your new roll is: 5 7 2 4 1
The three middle numbers change because those are the dice rolled. I have no idea how to do this efficiently. I could create 240 if statements, but that does not seem like the proper way of going about this.
This is my code thus far:
import random
def yahtzee():
dice1 = random.randrange(1,6)
dice2 = random.randrange(1,6)
dice3 = random.randrange(1,6)
dice4 = random.randrange(1,6)
dice5 = random.randrange(1,6)
print('Your roll is: ' + ' ' + str(dice1) + ' ' + str(dice2) + ' ' + str(dice3) + ' ' + str(dice4) + ' ' + str(dice5))
reroll = input('Which dice should I roll again?: ')
Which gives me the result:
yahtzee()
Your roll is: 4 3 2 1 5
Which dice should I roll again?:
Not sure how to go about re-rolling the dice. Any help would be appreciated! Thank you!
In general, it's much easier to manage results stored in a list:
def yahtzee():
dice = [random.randrange(1, 6) for _ in range(5)]
print('Your roll is: ', *dice)
reroll = input('Which dice should I roll again?: ')
for i in reroll:
dice[int(i) - 1] = random.randrange(1, 6)
print('Your roll is: ', *dice)
Example output:
Your roll is: 5 3 2 5 3
Which dice should I roll again?: 12
Your roll is: 1 2 2 5 3