How to implement a Loop statement - python

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.

Related

random dice rolling game. adding up the sum of values 1,3,4,and 6 excluding 2 and 5 in python

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.

Problem with simple dice game using python

I'm new to python so I decided to make a simple dice game using a while loop just to do a simple test of myself. In the game, I use the module random and the method random.randint(1, 6) to print a random integer of any value from "1 to 6", which is evidently how a dice works in real life. But to make this a game, if the integer that is printed is even (random.randint(1, 6) % 2 ==0) then 'you win' is printed. If the integer is odd, then 'you lose' is printed. After this, the console asks if you want to roll the dice again, and if you say yes (not case sensitive hence .lower()) then it rolls again and the loop continues, but if you say anything else the loop breaks.
I thought this is was how it would work, but every now and then, when an even number is rolled, 'you lose' is printed, and the opposite for odd numbers, which is not what I thought I had coded my loop to do. Obviously I'm doing something wrong. Can anyone help?
This is my code:
import random
min = 1
max = 6
roll_again = True
while roll_again:
print(random.randint(min, max))
if random.randint(min, max) % 2 == 0:
print('you win')
else:
print('you lose')
again = input('roll the dice? ').lower()
if again == ('yes'):
continue
else:
print('ok')
break
print(random.randint(min, max))
if random.randint(min, max) % 2 == 0:
print('you win')
Those are two separate calls to randint(), likely producing two different numbers.
Instead, call randint() once and save the result, then use that one result in both places:
roll = random.randint(min, max)
print(roll)
if roll % 2 == 0:
print('you win')
You are generating a random number twice, the number printed isn't the same the number as the one you are checking in the if condition.
You can save the number generated in a variable like this to check if your code is working fine :
import random
min = 1
max = 6
roll_again = True
while roll_again:
number = random.randint(min, max)
print(number)
if number % 2 == 0:
print('you win')
else:
print('you lose')
again = input('roll the dice? ').lower()
if again == ('yes'):
continue
else:
print('ok')
break
You need to assign random number to a variable, right now printed and the other one are different numbers.
import random
min = 1
max = 6
dice = 0
while True:
dice = random.randint(min, max)
print(dice)
if dice % 2 == 0:
print('you win')
else:
print('you lose')
again = input('roll the dice? ').lower()
if again == ('yes'):
continue
else:
print('ok')
break
random.randint(min,max) returns different value every time it is executed. So, the best thing you can do is store the value at the very first execution and check on that stored value for Win or Loss.
You can try this version of code:
import random
while(True):
value = random.randint(1,6)
print(value)
if(value % 2 == 0):
print("You Win!")
else:
print("You Lose!")
again = input("Want to roll Again? Type 'Yes' or 'No'")
if(again.lower() != 'yes'):
break

Python occasional list index error when two integer dice held

When I choose to hold two dice it will not always follow the script. It occurs at approximately line 50. Sometimes it doesn't even print the list.
(As a side note- if anyone can simplify the code it would be much appreciated.)
Can anybody help offer a solution and reason for the problem.
(Script is below)
import random
points = 0
final = []
print("Welcome to Yahtzee")
print("Where there are closed questions answer lower case with 'y' or n'")
print("Please be aware that this a variation of the traditional game.\nShould you hold a number- you cannot 'unhold' it.\nIt has been added to your final roll for the round.")
print("Do not be tempted to hold onto a number you haven't rolled\n- this will not work and won't be added to your final score")
def roll_dice():
global collection
collection = []
input("Press Enter to roll the first die")
die_1 = random.randint(1,6)
collection.append(die_1)
print(die_1)
input("Press Enter to roll the second die")
die_2 = random.randint(1,6)
collection.append(die_2)
print(die_2)
input("Press Enter to roll the third die")
die_3 = random.randint(1,6)
collection.append(die_3)
print(die_3)
input("Press Enter to roll the fourth die")
die_4 = random.randint(1,6)
collection.append(die_4)
print(die_4)
input("Press Enter to roll the fifth die")
die_5 = random.randint(1,6)
collection.append(die_5)
print(die_5)
roll_dice()
print(collection)
yeno = input("Would you like to hold any dice? ")
if yeno == "n":
input("This will mean re-rolling all the dice: proceeding...")
del(collection)
roll_dice()
print(collection)
elif yeno == "y":
no = input("How many dice would you like to hold: " )
if no == "1":
num1 = input("Enter the number you would like to keep: ")
num1 = int(num1)
for x in range(len(collection)-1):
if collection[x] == num1:
final.append(num1)
del(collection[x])
print(collection)
print(final)
if no == "2":
num2 = input("Enter the first number you would like to keep: ")
num2 = int(num2)
num3 = input("Enter the second number you would like to keep: ")
num3 = int(num3)
for x in range(len(collection)-1):
if collection[x] == num2:
final.append(num2)
del(collection[x])
for x in range(len(collection)-1):
if collection[x] == num3:
final.append(num3)
del(collection[x])
print(collection)
print(final)
Seems you would do well to read up on what list and the random module has to offer.
Below a suggested simple solution to generate one round of Yatzy.
NOTE: the solution uses formatted string literals so Python 3.6 or greater is needed.
#! /usr/bin/env python3
import sys
import random
greeting = """Welcome to Yatzy
Where there are closed questions answer lower case with 'y' or n'
When asked which dice to hold answer with a list of dice separated by
space.
At most 3 rounds per turn. Between each turn decide what numbers to
keep before rolling again.
Please be aware that this a variation of the traditional game. Should
you hold a number- you cannot 'unhold' it. It has been added to your
final roll for the round.
Do not be tempted to hold onto a number you haven't rolled - this will
not work and won't be added to your final score.
"""
# Assume we have N dice. There are 3 rounds per turn and between
# rounds the player chooses r numbers to keep. The next round will
# then have N - r dice to roll. After each turn the kept dice
# collection is displayed.
#
# The turn stops when 3 rounds have been played or when there are no
# more dice to roll or when the player decides to stop.
def play_one_turn(dice=5, turns=3):
keep = []
msg = "Dice to hold: "
while turns and dice:
turns -= 1
print(f"Kept: {keep}")
play = random.choices(range(1, 7), k=dice)
print(f"Throw --> {play}")
for h in map(int, input(msg).split()):
if h in play:
keep.append(h)
dice -= 1
play.remove(h)
ask = "Another round? (yes/no) "
if not input(ask).strip().upper().startswith('Y'):
break
return keep
if __name__ == "__main__":
print(greeting)
score = play_one_turn()
print(f"Play result {score}")

Python Roll dice with 2 parameters: Number of sides of the dice and the number of dice

This is the problem I have: Write a function roll dice that takes in 2 parameters - the number of sides of the die, and the number of dice
to roll - and generates random roll values for each die rolled. Print out each roll and then return the string
“That’s all!” An example output
>>>roll_dice(6,3)
4
1
6
That's all!
This is the code I have so far using a normal roll dice code:
import random
min = 1
max = 6
roll_dice = "yes"
while roll_dice == "yes":
print random.randint(min,max)
print random.randint(min,max)
print "That's all"
import sys
sys.exit(0)
Try this:
def roll_dice(sides, rolls):
for _ in range(rolls):
print random.randint(1, sides)
print 'That\s all'
This uses a for loop to loop rolls amount of times and prints a random number between 1 and sides each loop.
import random
def roll_dice(attempts,number_of_sides):
for i in range(attempts):
print(random.randint(1, number_of_sides))
print("thats all")
In a more advanced, you can have two parameters where you ask the users input to set the values and it will run the functions and give the numbers rolled, the sum and ask if the user wants to try again.
#Import 'random' module
import random
def main():
#Get values from user to determine slides_per_dice and number_of_die.
sides_per_die = get_value(1,50, 'How many sides should the dice to have
(1-50): ', 'That is not a correct response, enter a value between 1 and
50')
number_of_dice = get_value(1,10, 'How many dice should be rolled (1-10):
', 'That is not a correct response, enter a value between 1 and 10')
#Simulate rolling specified number of dice with specified sides on each
dice.
outcome = rolling_dice (sides_per_die, number_of_dice)
#Asking user if they would like to roll again.
roll_again = input("Would you like to play again (y/n): ") .lower()
while roll_again != 'n':
if roll_again =='y':
main()
else:
print('Error: please enter "y" or "n".')
roll_again = input("Would you like to play again (y/n): ")
#Final message if user ends the game.
print('Thanks for playing.')
#Asking user for side_per_dice and number_of_nice input.
def get_value(lower_limit, upper_limit, prompt, error_message):
number = int(input(prompt))
while number < lower_limit or number > upper_limit:
print(error_message)
number = int(input(prompt))
return number
#Determining the outcome of the rolls and summing up total for all rolls.
def rolling_dice (sides_per_die, number_of_die):
roll_sum = 0
print('Rolling dice .....')
for roll in range (number_of_die):
result = random.randint(1, sides_per_die)
roll_sum += result
print(result, end = " ")
print(f'\nThe sum of all dice rolled is {roll_sum}')
main()

Loop never seems to actually loop

print("Welcome to my dice game.")
print("First enter how many sides you would like your dice to have, 4, 6 or 12")
print("Then this program will randomly roll the dice and show a number")
#Introduction explaing what the game will do. Test 1 to see if it worked.
while True:
#starts a while loop so the user can roll the dice as many times as they find necessary
import random
#Imports the random function so the code will be able to randomly select a number
dice = int(input("Enter which dice you would to use,4, 6, or 12? "))
#set a variable for the amount of dice number
if dice == 12:
x = random.randint(1,12)
print("You picked a 12 sided dice. You rolled a " + str(x) + " well done")
#Test 2 see if it does pick a random number for a 12 sided di
elif dice == 6:
x = random.randint(1,6)
print("You picked a 6 sided dice. You rolled a " + str(x) + " well done")
#Test 3 see if it does pick a random number for a 6 sided di
elif dice == 4:
x = random.randint(1,4)
print("You picked a 4 sided dice. You rolled a " + str(x) + " well done")
#Test 4 see if it does pick a random number for a 4 sided di
else:
print("Sorry, pick either 12, 6 or 4")
#Test 5 tells the user that they can only pick 4, 6 or 12 if anything else is entered this error shows
rollAgain = input ("Roll Again? ")
if rollAgain == "no":
rollAgain = False
if rollAgain == "yes":
rollAgain = True
break
print ("Thank you for playing")
#if the user enters anything apart from yes y or Yes. The code ends here.
That is the code i have so far. However the code will never actually go to the beginning of the loop, no matter what i enter the code just displays "Thanks for playing" and ends. Can anyone please tell me where i have went wrong?
First, you should be using raw_input to get the user's selection. (assuming python 2) If you're using python 3 then input is fine and keep reading.
Anyway, it'll still quit when you type yes because you break out of the loop! You should move the break statement into the "no" case so it breaks out when you say you do not want to roll again.
rollAgain = raw_input ("Roll Again? ")
if rollAgain == "no":
break
You don't need to set rollAgain to true or false at all. With the above code, anything other than "no" is assumed to be "yes" but you can add checks for that easily.
The problem is that you break your loop when the user wants to roll the dice again. The loop should break when the player doesn't want to play again so you have to do :
http://pastebin.com/hzC1UwDM

Categories

Resources