I am working on dice rolling game which prints out the number of attempts (n) before both dice shows the same value.
I would like to also print out the past rolling results. However, my code only shows the last rolling results (n-1 attempts).
I have tried to google and check the past history of stackoverflow dice rolling queries and I still can't figure out how to solve the code. Please help, I think it has got to do with nested list or dictionaries, but I just can't figure it out.
Below is my code:
from random import randint
stop = 0
count = 0
record = []
while stop == 0:
roll = [(dice1, dice2) for i in range(count)]
dice1 = randint(1,6)
dice2 = randint(1,6)
if dice1 != dice2:
count += 1
else:
stop += 1
record.append(roll)
if count == 0 and stop == 1:
print("You roll same number for both dice at first try!")
else:
print(f"You roll same number for both dice after {count+1} attempts.")
print("The past record of dice rolling as below: ")
print(record)
You have a few mistakes in your code. The first, is that I'm not entirely sure what the
roll = [(dice1, dice2) for i in range(count)]
line is doing for you.
You can make a few simple changes though.
First - your record.append(...) line is outside of your loop. That is why you only see the previous run. It's only recording one run.
Second, your while statement can be a simple while True: with a break in it when you meet your matching condition. You don't need the stop variable.
from random import randint
count = 0
record = []
while True:
dice1 = randint(1,6)
dice2 = randint(1,6)
record.append([dice1,dice2])
if dice1 != dice2:
count += 1
else:
break
if count == 0:
print("You roll same number for both dice at first try!")
else:
print(f"You roll same number for both dice after {count+1} attempts.")
print("The past record of dice rolling as below: ")
print(record)
With output similar to this:
You roll same number for both dice after 8 attempts.
The past record of dice rolling as below:
[[1, 6], [2, 1], [1, 6], [5, 6], [5, 3], [6, 3], [6, 5], [4, 4]]
Notice that I've brought the .append(...) into your while loop. I've also made the changes around the stop variable as I described.
I would do something similar to #TeleNoob. Just use while True: and break when the condition is met.
Here's my reworking:
from random import randint
roll = 0
die1_record = []
die2_record = []
while True:
die1 = randint(1,6)
die2 = randint(1,6)
die1_record.append(die1)
die2_record.append(die2)
roll += 1
if die1 == die2:
break
print(f"You rolled same number for both dice after {roll} attempt(s).")
print("The past record of dice rolling is: ")
print(f"die1: {die1_record}")
print(f"die2: {die2_record}")
Related
Im trying to make a loop where I start with 5 random dice rolls. the values 1,3,4, and 6 are added up for your score, while 2s and 5s are not counted and subtract the combined amount of dice rolled with 2s and 5s from the amount of dice rolled the next turn. I can't quite figure out how to get the sum of only the dice that rolled 1,3,4,6 and roll a lesser amount of dice the next turn based off ho many dice were 2 or 5
#Stuck in the Mud Dice Game
Exit = 0
Rolls = int(5)
score = 0
def RollDice():
totalsum = 0
for die in range(0, Rolls):
number = random.randint(1,6)
print("die", die + 1, ":", number)
totalsum += number
print("score: ", totalsum)
def Menu():
print("1. Roll Dice")
print("2. Exit Program")
print()
choice = int(input("Enter option here: "))
if(choice == 1):
RollDice()
if(choice == 2):
Exit()
Menu()
In the for-loop, use an if statement:
if number==2 or number==5:
Rolls -= 1
else:
totalsum += number
I suppose that you also need to start your function RollDice like this:
def RollDice():
global Rolls
...
otherwise, it might only locally (i.e., within the function) assign a new value to the variable.
Or do you mean the number of Rolls should be different when you re-start the program? This can only be done by writing the value to a file.
I need help condensing my Yahtzee code. I'm familiar with loops, but I can't seem to figure out how to do it without wiping my roll each turn. It's set up to roll 5 random dice and then you choose which you want to keep. It will then roll what's left for three total rolls. I thought of making a placeholder list, but I can't make it work that way either.
Dice = [‘⚀ ’,‘⚁ ‘,’ ⚂ ‘,’ ⚃ ‘,’ ⚄ ‘,’ ⚅ ‘]
turns = 3
#first roll
first_roll = []
for _ in range(5):
roll = random.choice(dice)
first_roll.append(roll)
print(first_roll)
turns -= 1
print(f'You have {turns} turns left.')
keep = input("Which dice would you like to keep? 1 - 5: ").split()
clear()
#second roll
second_roll = []
for i in keep:
x = int(i)
j = first_roll[x-1]
second_roll.append(j)
remainder = 5 - len(second_roll)
for _ in range(remainder):
roll = random.choice(dice)
second_roll.append(roll)
print(second_roll)
turns -= 1
print(f'This is your last turn.')
keep = input("Which dice would you like to keep? 1 - 5: ").split()
clear()
#third roll
third_roll = []
for i in keep:
x = int(i)
j = second_roll[x-1]
third_roll.append(j)
remainder = 5 - len(third_roll)
for _ in range(remainder):
roll = random.choice(dice)
third_roll.append(roll)
print(third_roll)
So I'm not sure if this is exactly what you're looking for, but I created a function that lets you continuously roll for X turns and the dice pool gets progressively smaller like your code shows. I thoroughly commented the code to hopefully give you a good explanation to what I'm doing.
import random
#Dice characters
dice = ['1','2','3','4','5','6']
#Number of turns player has
turns = 3
#This is the group of dice kept by the player
kept_dice = []
def roll():
#This is the group of dice randomly chosen
rolled_dice = []
#Generate up to 5 random dice based on how many have been kept so far
for _ in range(5 - len(kept_dice)):
#Append random dice value to rolled_dice array
rolled_dice.append(random.choice(dice))
#Print roll group
print(rolled_dice)
dice_to_keep = int(input("Which dice would you like to keep? 1 - 5: "))
kept_dice.append(rolled_dice[dice_to_keep-1])
while turns != 0:
#Let the user know how many turns they have left
print(f'You have {turns} turns left.')
#Roll dice
roll()
#Subtract 1 turn
turns -= 1
#After all turns, show the kept dice:
print("Kept dice:")
print(kept_dice)
I am working on some code for my mock exams and I am stuck on the part where I have to add all the scores together and then print the total. The aim of the code is for 2 players to roll 2 dice, if the numbers are the same, they roll a third die. the code then adds the die together and prints the total depending on if the total can be divided by 2.
after repeating this 5 times, the code should then add all the totals together and display the overall total.
yet it only ever prints the last total, and does not add all 5 totals together. if anyone could help me, that would be appreciated, i am also sorry for the noob question. i am new to this.
import random
score = 0
for i in range(5):
print ("\n")
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
dice3 = random.randint(1,6)
print ("player 1: roll 1 = ",dice1)
print ("player 1: roll 2 = ",dice2)
if dice1 == dice2:
print ("player 1: roll 3 = ",dice3)
score = dice1+dice2
if dice1 == dice2:
score = dice1+dice2+dice3
if score % 2 == 0:
score = score+10
if score % 2 == 1:
score = score-5
print ("player 1: score = ", score)
print ("\n")
overalltotal = score
print ("total for player 1:", overalltotal)
i expect the output to be the total of all 5 scores. yet the actual output is only ever the last score
I think you need to include overalltotal += score at the end of the for-loop rather than setting overalltotal = score after the for-loop. So your code would be:
import random
score = 0
overalltotal = 0 # <-- initialize here
for i in range(5):
print ("\n")
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
dice3 = random.randint(1,6)
print ("player 1: roll 1 = ",dice1)
print ("player 1: roll 2 = ",dice2)
if dice1 == dice2:
print ("player 1: roll 3 = ",dice3)
score = dice1+dice2
if dice1 == dice2:
score = dice1+dice2+dice3
if score % 2 == 0:
score = score+10
if score % 2 == 1:
score = score-5
print ("player 1: score = ", score)
overalltotal += score # <-- add value of each round here
print ("\n")
print ("total for player 1:", overalltotal)
You problem is not Python but is program logic. Use a paper and a pencil to first describe what should be done, step by step with tests, loops and blocks. Then follow the process on the paper with different use cases. When you think it should work, translate it it Python code, add trace prints to control what happens and run. You should be able to fix everything by yourself.
As hints of what should be fixed or improved:
2 different if dice1 == dice2: tests one after the other. Better to group outside what is common (score = dice1 + dice2) and than use one single test for what is specific (score += dice3)
the print ("player 1: score = ", score) is inside an if block. Nothing will be printed if score % 2 != 1. Is this really desirable?
initialize overalltotal before the main loop, and increment it with score inside the loop
your code always compute dice3 even when it is not used. Why not only compute it inside the if dice1 == dice2: block?
If you want to change score as you have mentioned then you have to change your statements
score = dice1+dice2 --> score += dice1+dice2 (do this for dice things)
score = score+10 --> score += 10 (for score things)
score = score-5 --> score -= 5 (for score things)
I made a simple Yahtzee game in as few of lines as I could think. Currently, the user must press Enter (with any value) to continue. I would like to use a loop statement so that the dice continue to roll until Yahtzee (all rolled numbers are the same). I would also like a 10 second timer. What is the best way to add a loop statement to this code? P.S. This is not homework, I wanted to make this game for my Yahtzee nights. My daughter wakes easil...haha
import random
while True:
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
dice3 = random.randint(1,6)
dice4 = random.randint(1,6)
dice5 = random.randint(1,6)
numbers = (dice1, dice2, dice3, dice4, dice5)
sum1 = sum(numbers)
if sum1 == ("5" or "10" or "15" or "20" or "25"):
print("Winner, winner, chicken dinner!", dice1, dice2, dice3, dice4, dice5)
else:
print("Your rolls are: ", dice1, dice2, dice3, dice4, dice5)
input("Press return key to roll again.")
EDIT: This is my final product. Thank you for all the help guys!!
import random
import time
input("Press return key to roll.")
for x in range(0,10000):
numbers = [random.randint(1,6) for _ in range(5)]
if all(x == numbers[0] for x in numbers):
print("Winner, winner, chicken dinner!", numbers)
input("Press return key to play again.")
else:
print("Your rolls are: ", numbers)
print("Next roll in one second.")
time.sleep(1)
If you would like to check if all the dice numbers are the same it is as simple as.
allDice = [dice1, dice2, dice3, dice4, dice5] #List of dice variables
if all(x == allDice[0] for x in allDice): # If all dice are the same
print("Yahtzee")
break # Break out of while loop
The most simple way of having a "timer" could be adding a time.sleep(). You have to import time otherwise it won't work.
So replace
input("Press return key to roll again.")
with
time.sleep(10)
This means every 10 seconds the dice will roll until all dice are the same number, if they are then it prints Yahtzee and stops the loop.
Replace the while True:... with a while boolean_variable: ... and set the value of that boolean_variable to True before the while loop and to False when you achieved Yahtzee => in the if condition.
What do you mean by 10 second timer, however? A sleep time of ten seconds can be implemented by a time.sleep(10) at the end of the inner while loop.
EDIT boolean_variable EXAMPLE
import time
...
not_yahtzee = True
while not_yathzee:
....
if sum == 5 or sum == 10 or ... :
...
not_yahtzee = False
else:
...
time.sleep(10)
The ... represent the code you already have. As commented on your question, the if condition should look more like this one. There are other ways on how to check all the elements in a list are the same.
So I had to make code that roll a die fairly and counted how many 4's I got. With the help of people on here I got it to work. Well now I have to created another die and roll them and then add they products together. This is the instructions I've been given.
"Then write another function that simulates rolling two fair dice. The easy way is to call the function you just wrote, twice, and add the numbers you get.
This should return a number between 2 and 12."
I've added rolling the dice a second time but how do I add the sums of the two rolls together is my question?
And this is my code.
from random import randrange
def roll():
rolled = randrange(1,7)
if rolled == 1:
return "1"
if rolled == 2:
return "2"
if rolled == 3:
return "3"
if rolled == 4:
return "4"
if rolled == 5:
return "5"
if rolled == 6:
return "6"
def rollManyCountTwo(n):
twoCount = 0
for i in range (n):
if roll() == "2":
twoCount += 1
if roll() == "2":
twoCount +=1
print ("In", n,"rolls of a pair of dice, there were",twoCount,"twos.")
rollManyCountTwo(6000)
You shouldn't have to deal with strings at all, this could be done entirely using int values
from random import randint
def roll():
return randint(1,6)
def roll_twice():
total = 0
for turn in range(2):
total += roll()
return total
For example
>>> roll_twice()
10
>>> roll_twice()
7
>>> roll_twice()
8
And for your function that is supposed to count the number of 2s that were rolled, again you can do integer comparison
def rollManyCountTwo(n):
twos = 0
for turn in range(n):
if roll() == 2:
twos += 1
print('In {} rolls of a pair of dice there were {} twos'.format(n, twos))
return twos
>>> rollManyCountTwo(600)
In 600 rolls of a pair of dice there were 85 twos
85
from random import randint
def roll():
return randint(1,6)
def rollManyCountTwo(n):
twoCount = 0
for _n in xrange(n*2):
if roll() == 2:
twoCount += 1
print "In {n} rolls of a pair of dice, there were {cnt} twos.".format(n=n, cnt=twoCount)
Since you roll two dices for n times and count every single two rolled, just loop for n*2 and check if the dice result is two.