I have been trying to create a program that will simulate a dice roll, with the option to choose between a 4, 6, or 12 sided die. At the moment the problem I am having is that the program skips the rolling entirely no matter what option I choose and immediately asks me if I want to roll again. Im using Portable Python 3.2.1.1 to create the code. This is what I have so far:
#!/usr/bin/env python
import random
def fourdie():
min = 1
max = 4
print (random.randint(min, max));
return;
def sixdie():
min = 1
max = 6
print (random.randint(min, max));
return;
def twelvedie():
min = 1
max = 12
print (random.randint(min, max));
return;
roll = "yes"
y = 1
while roll == "yes" or roll == "y":
x = raw_input("What die do you want to roll? 4, 6 or 12?");
if x == 4:
print (fourdie());
elif x == 6:
print (sixdie());
elif x == 12:
print (twelvedie());
else:
print = "Sorry, I dont appear to have that dice type";
roll = raw_input("Do you want to roll again?");
Any help would be appreciated.
Thank you for your time!
input function returns a string.
You can convert this string to int and then compare it to 4, 6, or 12:
x = int(input("What die do you want to roll? 4, 6 or 12?"))
if x == 4:
// whatever
elif x == 6:
// whatever
Or you can compare x directly to a string:
x = input("... whatever ...")
if x == "4":
// whatever
elif x == "6":
// whatever
And one other thing: there is no need to end lines with the semicolon in python. Makes Guido van Rossum happy.
Your basic problem is typing, as solved by Nigel Tufnel
I just, because it strikes my fancy, thought I'd mention you could make your code far more generic:
while roll in ["yes", "y"]:
x = int(raw_input("Number of sides on the die you want to roll?"))
print random.randint(1,x)
roll = raw_input("Do you want to roll again?")
Related
This question already has answers here:
Why does random.shuffle return None?
(5 answers)
Closed 5 years ago.
Right now I am trying to do a piece of code for the Monty Hall problem
I have some code that I am trying to fix and then enhance
This is one thing that I am stuck on:
I am trying to change the way the door at which the prize is chosen by using random.shuffle(), I have to use random.shuffle(), not anything else.
How would I do this?
What I have now does not work for that.
if I put print(random.shuffle(door)), I don't get a new output.
how do I make it return the chosen output
import random
door = ["goat","goat","car"]
choice = int(input("Door 1, 2 or 3? "))
otherDoor = 0
goatDoor = 0
if choice == 1:
if door[1] == "goat":
otherDoor = 3
goatDoor = 2
elif door[2] == "goat":
otherDoor = 2
goatDoor = 3
elif choice == 2:
if door[0] == "goat":
otherDoor = 3
goatDoor = 1
elif door[2] == "goat":
otherDoor = 1
goatDoor = 3
elif choice == 3:
if door[0] == "goat":
otherDoor = 2
goatDoor = 1
elif door[1] == "goat":
otherDoor = 1
goatDoor = 2
switch = input("There is a goat behind door " + str(goatDoor) +\
" switch to door " + str(otherDoor) + "? (y/n) ")
if switch == "y":
choice = otherDoor
if random.shuffle(door) == "car":
print("You won a car!")
else:
print("You won a goat!")
input("Press enter to exit.")
random.shuffle shuffles in place, meaning it will return None if you try and assign a variable to it's non-existent output.
Since you say you have to use shuffle, you can shuffle the list in place with random.shuffle(door), then take an element from this shuffled list eg: door[0]
From the python3 documentation of the random module:
random.shuffle(x[, random])
Shuffle the sequence x in place.
The 'in place' means that the function is replacing the variable x (in your case, 'door') with a different variable that has the same values as before but with their order shuffled. It does not have a return, it simply modifies the variable you gave it, which is why your print statement shows 'None'.
If you must use, random.shuffle, you can simply select an element of the door after you've shuffled it (i.e. random.shuffle(door) then print(door[0])).
However, if other functions were to be an option, then random.sample(door,1) may be simpler instead (documentation for random.sample here).
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}")
import random
total = [0]
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
dice=True
while dice:
a = random.randrange(1,7)
if a == 1:
one = one + 1
elif a == 2:
two = two + 1
elif a == 3:
three = three + 1
elif a == 4:
four = four + 1
elif a == 5:
five = five + 1
elif a == 6:
six = six + 1
b = len(total)
print ("Roll:", b,)
print ("The dice has rolled:",a,)
total.append (a)
dice =input("Roll again? (y,n):")
if dice == "n":
print ("Thank-You!")
print ("One rolled",one,"times")
print ("Two rolled",two,"times")
print ("Three rolled",three,"times")
print ("Four rolled",four,"times")
print ("Five rolled",five,"times")
print ("Six rolled",six,"times")
break
How can I make it so that if "one" has only been rolled "once" it says "one has been rolled time" instead of "one has been rolled 1 times"?
Thanks. An explanation would also be good so that I can learn
Make a function called printTimesRolled or something similar. Then pass a string, and an int. Like this:
def printTimesRolled(numberWord, timesRolled):
if (timesRolled == 1):
print(numberWord, "rolled 1 time.")
else:
print(numberWord, "rolled", timesRolled, "times.")
Then, to print them all, just do this:
printTimesRolled("One", one)
printTimesRolled("Two", two)
...
You can use str.format and a check whether the number has been rolled exactly one time. Demo:
>>> one = 1
>>> 'One rolled {} time{}'.format(one, 's' if one!=1 else '')
'One rolled 1 time'
>>> one = 0
>>> 'One rolled {} time{}'.format(one, 's' if one!=1 else '')
'One rolled 0 times'
>>> one = 3
>>> 'One rolled {} time{}'.format(one, 's' if one!=1 else '')
'One rolled 3 times'
This would be a good way to handle the dice rolling. I am not sure if you have started exploring classes yet, but by making the DiceRoller class you make it slightly more organized. Besides, you avoid tons of global variables.
Using a dictionary for comparisons will allow you to run a for loop to compare it, rahter than having 6 elif statements, making the code more efficient.
Finally, when the user types "n" to quit and check on his rolls, we compare to again.lower() to failsafe it in case the user types "N" instead.
Then it loops through the dictionary and prints 'time / roll' or 'times / rolls' based on a simple if statement.
I hope this makes sense to you, if not just ask!
import random
# DEFINING THE CLASS
class DiceRoller(object):
def __init__(self):
self.sides = {1:0,
2:0,
3:0,
4:0,
5:0,
6:0}
# WILL ROLL THE DICE AND ADD 1 TO THE SIDE COUNTER WHEN A SIDE IS ROLLED
def rollTheDice(self):
roll = random.randint(1,6)
for side in (self.sides):
if roll == side:
self.sides[side] += 1
print('Rolled a %s' % (roll))
# WILL PRINT TOTAL ROLLS WHEN CALLED
def getTotals(self):
for i, side in enumerate(self.sides):
if self.sides[side] == 1:
print('Side %s: %s roll' % (i + 1, self.sides[side]))
else:
print('Side %s: %s rolls' % (i + 1, self.sides[side]))
# THIS CODE IS EXECUTED
Dice = DiceRoller()
while True:
Dice.rollTheDice()
again = input('Roll again [y/n]: ')
if again.lower() == 'n':
break
Dice.getTotals()
This code outputs the following when run a couple of times:
Rolled a 2
Roll again [y/n]: y
Rolled a 4
Roll again [y/n]: y
Rolled a 3
Roll again [y/n]: y
Rolled a 1
Roll again [y/n]: y
Rolled a 4
Roll again [y/n]: y
Rolled a 2
Roll again [y/n]: n
Side 1: 1 roll
Side 2: 2 rolls
Side 3: 1 roll
Side 4: 2 rolls
Side 5: 0 rolls
Side 6: 0 rolls
Process finished with exit code 0
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
first time writing here.. I am writing a "dice rolling" program in python but I am stuck because can't make it to generate each time a random number
this is what i have so far
import random
computer= 0 #Computer Score
player= 0 #Player Score
print("COP 1000 ")
print("Let's play a game of Chicken!")
print("Your score so far is", player)
r= random.randint(1,8)
print("Roll or Quit(r or q)")
now each time that I enter r it will generate the same number over and over again. I just want to change it each time.
I would like it to change the number each time please help
I asked my professor but this is what he told me.. "I guess you have to figure out" I mean i wish i could and i have gone through my notes over and over again but i don't have anything on how to do it :-/
by the way this is how it show me the program
COP 1000
Let's play a game of Chicken!
Your score so far is 0
Roll or Quit(r or q)r
1
r
1
r
1
r
1
I would like to post an image but it won't let me
I just want to say THANK YOU to everyone that respond to my question! every single one of your answer was helpful! **thanks to you guys I will have my project done on time! THANK YOU
Simply use:
import random
dice = [1,2,3,4,5,6] #any sequence so it can be [1,2,3,4,5,6,7,8] etc
print random.choice(dice)
import random
computer= 0 #Computer Score
player= 0 #Player Score
print("COP 1000 ")
print("Let's play a game of Chicken!")
print("Your score so far is", player)
r= random.randint(1,8) # this only gets called once, so r is always one value
print("Roll or Quit(r or q)")
Your code has quite a few errors in it. This will only work once, as it is not in a loop.
The improved code:
from random import randint
computer, player, q, r = 0, 0, 'q', 'r' # multiple assignment
print('COP 1000') # q and r are initialized to avoid user error, see the bottom description
print("Let's play a game of Chicken!")
player_input = '' # this has to be initialized for the loop
while player_input != 'q':
player_input = raw_input("Roll or quit ('r' or 'q')")
if player_input == 'r':
roll = randint(1, 8)
print('Your roll is ' + str(roll))
# Whatever other code you want
# I'm not sure how you are calculating computer/player score, so you can add that in here
The while loop does everything under it (that is indented) until the statement becomes false. So, if the player inputted q, it would stop the loop, and go to the next part of the program. See: Python Loops --- Tutorials Point
The picky part about Python 3 (assuming that's what you are using) is the lack of raw_input. With input, whatever the user inputs gets evaluated as Python code. Therefore, the user HAS to input 'q' or 'r'. However, a way to avoid an user error (if the player inputs simply q or r, without the quotes) is to initialize those variables with such values.
Not sure what type of dice has 8 numbers, I used 6.
One way to do it is to use shuffle.
import random
dice = [1,2,3,4,5,6]
random.shuffle(dice)
print(dice[0])
Each time and it would randomly shuffle the list and take the first one.
This is a python dice roller
It asks for a d(int) and returns a random number between 1 and (d(int)).
It returns the dice without the d, and then prints the random number. It can do 2d6 etc. It breaks if you type q or quit.
import random
import string
import re
from random import randint
def code_gate_3(str1):
if str1.startswith("d") and three == int:
return True
else:
return False
def code_gate_1(str1):
if str1.startswith(one):
return True
else:
return False
def code_gate_2(str2):
pattern = ("[0-9]*[d][0-9]+")
vvhile_loop = re.compile(pattern)
result = vvhile_loop.match(str1)
if result:
print ("correct_formatting")
else:
print ("incorrect_formattiing")
while True:
str1 = input("What dice would you like to roll? (Enter a d)")
one, partition_two, three = str1.partition("d")
pattern = ("[0-9]*[d][0-9]+")
if str1 == "quit" or str1 == "q":
break
elif str1.startswith("d") and three.isdigit():
print (random.randint(1, int(three)))
print (code_gate_2(str1))
elif code_gate_1(str1) and str1.partition("d") and one.isdigit():
for _ in range(int(one)):
print (random.randint(1, int(three)
print (code_gate_2(str1))
elif (str1.isdigit()) != False:
break
else:
print (code_gate_2(str1))
print ("Would you like to roll another dice?")
print ("If not, type 'q' or 'quit'.")
print ("EXITING>>>___")
This is one of the easiest answer.
import random
def rolling_dice():
min_value = 1
max_value = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "Yes" or roll_again == "Y" or roll_again == "y" or roll_again == "YES":
print("Rolling dices...")
print("The values are...")
print(random.randint(min_value, max_value))
print(random.randint(min_value, max_value))
roll_again = input("Roll the dices again? ")
rolling_dice()