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
Related
I am creating a Yahzee game, and I want it to save a 'dice' roll, temporarily.
import random
roll = random.randint(0, 6)
print("Dice 1: " + roll)
print("Dice 2: " + roll)
input = "Save die?"
if input == "Dice 2":
print("Dice 1: " + roll)
# Print Dice 2's number above, below
It should output:
Dice 1: 3
Dice 2: 6
Save Die? Die 2
Dice 1: 2
Dice 2: 6
How do I make it save the number, so I can use it, but then after 6 moves, 5 Rolls and choosing the play, it will erase.
I do not know what is a Yahzee game, but I think you need a simple data structure like list to save your results and empty the list when it is necessary.
import random
results = []
move_num = 6
while True:
for i in range(move_num):
dices = [random.randint(0, 6), random.randint(0, 6)]
print('Dice 1: {}'.format(dices[0]))
print('Dice 2: {}'.format(dices[1]))
decision = int(input('Save die?'))
if decision in [1, 2]:
results.append(dices[decision-1])
else:
print('wrong dice number')
print('results are {}'.format(results))
results.clear()
I do not understand the game rules, hope this could help you.
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'm making a two player dice game and this is some of the code for it. I want it to loop five times but it will not do so. Once it has executed all this code, it stops there and doesn't repeat 5 times. I've tried doing for x in range (0, 5) but that doesn't seem to work either. What is the problem with the code and can anyone help fix this?
Btw please ignore the comments, it is for the purpose for an assignment.
for x in range(5): #loops the following code 5 times
import random #imports a random module
print ("Player1, it's your turn to play") #prints message
while True:
roll = input("Type roll to roll the dice: ") #asks user for input to assign value to variable
if roll == "roll" or roll == "Roll" : #takes place if the condition is true
die = random.randint(1, 6) #assigns a random integer value to the variable
dieOne = random.randint(1, 6) #assigns a random integer value to the variable
print ("You rolled : ", die, "and", dieOne) #prints a message telling the player what numbers they rolled on the dice
scoreOne = scoreOne + die + dieOne #assigns the value
if die == dieOne : #loops only if the condition here is true
print ("You rolled a double!") #a message that tells the player they rolled a double
print ("Roll again!") #prints a message
die = random.randint(1, 6) #assigns a random integer value to the variable
print ("You rolled : ", die) #prints a message telling the player what number they rolled
scoreOne = scoreOne + die #adds the value of two variables together
print ("Player2, it's your turn to play") #prints message
roll2 = input("Type roll to roll the dice: ") #asks user for input to assign value to variable
if roll == "roll" or roll == "Roll" : #takes place if the condition is true
dieTwo = random.randint(1, 6) #assgins a random integer value to this variable
playerTwoDie = random.randint(1, 6) #assgins a random integer value to this variable
scoreTwo = scoreTwo + dieTwo + playerTwoDie #assigns the value of the previous variable to this variable
print ("You rolled : ", dieTwo, "and", playerTwoDie) #prints a message telling the player what numbers they rolled on the dice
break
if dieTwo == playerTwoDie : #loops only if the condition here is true
print ("You rolled a double!") #a message that tells the player they rolled a double
print ("Roll again!") #outputs a message
dieTwo = random.randint(1, 6) #assigns a random integer value to the variable
print ("You rolled : ", dieTwo) #prints a message telling the player what number they rolled
scoreTwo = scoreTwo + dieTwo #adds the value of two variables together
break
if die % 2 == 0 : #loops if the value of the variable has a remainder of 0 when divided by 2
scoreOne = scoreOne + 10 #adds 10 to the value of this variable
elif dieOne % 2 == 0 : #loops if the value of the variable has a remainder of 0 when divided by 2
scoreOne = scoreOne + 10 #adds 10 to the value of this variable
else : #when the above conditions are not true the following code is executed
scoreOne = scoreOne - 5 #takes away 5 from the value of this variable
if scoreOne < 0 : #checks if this condition is true so it can execute the code
scoreOne = 0 #assigns the value 0 to the variable
if dieTwo % 2 == 0 : #loops if the value of the variable has a remainder of 0 when divided by 2
scoreTwo = scoreTwo + 10 #adds 10 to the value of this variable
elif playerTwoDie % 2 == 0 : #loops if the value of the variable has a remainder of 0 when divided by 2
scoreTwo = scoreTwo + 10 #adds 10 to the value of this variable
else : #when the above conditions are not true the following code is executed
scoreTwo = scoreTwo - 5 #takes away 5 from the value of this variable
if scoreTwo < 0 : #checks if this condition is true so it can execute the code
scoreTwo = 0 #assigns the value 0 to the variable
print ("Player 1, your score so far is: ", scoreOne) #prints a message teller player 1 their score
print ("Pleyer 2, your score so far is: ", scoreTwo) #prints a message telling player 2 their score
break #ends the while loop
print ("Player 1, your total score is: ", scoreOne) #prints message with player one's scores
print ("Player 2, your total score is: ", scoreTwo) #prints message with player two's scores
while scoreOne == scoreTwo : #loop continues when the condition here is true
print("You have the same score as each other. Lets play again until one person wins!") #prints a message
import random #inports a random module
print("Player 1, it's your turn to play!")
roll = input("Type roll to roll the dice: ") #asks user for input to assign value to variable
while roll != "roll" or roll != "Roll" : #loops while the condition is true
print ("Error, please try again!") #prints message
roll = input("Type roll to roll the dice: ") #asks user for input to assign value to variable
if roll == "roll" or roll == "Roll" : #takes place if the condition is true
die = random.randint(1,6) #generates a random integer value for variable
print ("Your rolled: ", die) #prints message telling the player the value of the variable
scoreOne = scoreOne + die
break #ends loop
print("Player 2, it's your turn to play!")
roll = input("Type roll to roll the dice: ") #asks user for input to assign value to variable
while roll != "roll" or roll != "Roll" : #loops while the condition is true
print ("Error, please try again!") #prints message
roll = input("Type roll to roll the dice: ") #asks user for input to assign value to variable
if roll == "roll" or roll == "Roll" : #takes place if the condition is true
dieTwo = random.randint(1, 6) #generates a random integer value for variable
print ("Your rolled: ", dieTwo) #prints message telling the player the value of the variable
scoreTwo = scoreTwo + dieTwo
break #ends loop
if die % 2 == 0 : #loops if the value of the variable has a remainder of 0 when divided by 2
scoreOne = scoreOne + 10 #adds 10 to the value of this variable
elif dieOne % 2 == 0 : #loops if the value of the variable has a remainder of 0 when divided by 2
scoreOne = scoreOne + 10 #adds 10 to the value of this variable
else : #when the above condition is not true the following code is executed
scoreOne = scoreOne - 5 #takes away 5 from the value of this variable
if scoreOne < 0 : #checks if this condition is true so it can execute the code
scoreOne = 0 #assigns the value 0 to the variable
if die2 % 2 == 0 : #loops if the value of the variable has a remainder of 0 when divided by 2
scoreTwo = scoreTwo + 10 #adds 10 to the value of this variable
elif playerTwoDie % 2 == 0 : #loops if the value of the variable has a remainder of 0 when divided by 2
scoreTwo = scoreTwo + 10 #adds 10 to the value of this variable
else : #when the above condition is not true the following code is executed
scoreTwo = scoreTwo - 5 #takes away 5 from the value of this variable
if scoreTwo < 0 : #checks if this condition is true so it can execute the code
scoreTwo = 0 #assigns the value 0 to the variable
print ("Player 1, your score so far is: ", scoreOne) #prints a message teller player 1 their score
print ("Player 2, your score so far is: ", scoreTwo) #prints a message telling player 2 their score
Instead of using while True, you can use the following:
gamecount = 0
while (gamecount < 5):
print (f'play game {gamecount}')
#insert your other game code here
gamecount += 1
Also remember to remove the break in your code as per what #Eliad Cohen said in his answer.
From a first look, this code block won't run unless you move the import to be the first line and indent everything below the "for" loop.What your code is doing now is just importing the random module for five times.
Also, scoreOne needs to be instantiated before it is used in line 11.
I agree with #ycx comment, I think using the while loop will work better.
I think that your use of break in line 57 makes the loop end before you want it to. You can read more about loop control in: http://www.tutorialspoint.com/python/python_loop_control.htm
Hope this helps so far.
As pointed out in other answers, the indentation and ordering of your code is off. This may be a programming error or a result of copying the code to stack overflow.
Indentation aside, the script has a lot of repeated code. To reduce duplication of code and make the script easier to read and understand, you may want to split the program into different functions.
Though I do not intend to nulify your previous work, here's my implementation of the game(as I've understood it), so you can get an idea of how one might go about strucuring a simple script. I do realize that there are more elegant ways to implement the game, but for the sake of clarity, I decided to stick to common code constructs.
#! /usr/bin/env python3
# imports
from random import randint
# functions
def roll_dice(n_dice):
"""Rolls specified number of dice and returns their values"""
# wait until the player types 'roll'
while True:
answer = input("Type 'roll' to roll the dice: ")
if answer.lower() == "roll":
break
# generate results using list comprehension
results = [randint(1, 6) for die in range(n_dice)]
print("you rolled: ", results)
return results
def play_turn(player_name):
"""Lets specified player play a turn and returns the resulting score"""
print(player_name, " it's your turn to play!")
# roll two dice
roll_one, roll_two = roll_dice(2)
print(type(roll_one))
score = roll_one + roll_two
# if it was a double, roll die no 1 again
if roll_one == roll_two:
print("You rolled a double!", "Roll again", sep="\n")
roll_one = roll_dice(1)[0]
score += roll_one
if roll_one % 2 == 0 or roll_two % 2 == 0: # if at least one die has an even value:
score += 10
else:
score -= 5
print("you scored", score, "points", "\n")
return score
def play_game(player_names):
"""runs the game, given a collection of player names"""
# set up a score board.
# # This can be implemented more elegantly, but this solution is most clear, I think.
# the alternative would be a dictionary comprehension: score_board = {player: 0 for player in player_names}
score_board = dict()
for player in player_names:
score_board[player] = 0
# do 5 rounds of regular playing, adding extra rounds if the game ties
round_no = 0
while True:
for player in player_names:
score = play_turn(player)
score_board[player] = max(0, score_board[player] + score) # make sure the score doesn't drop below 0
print("current scores are", score_board)
round_no += 1
# after 5 normal rounds have been played:
if round_no >= 5:
if len(set(score_board.values())) == 1: # if the game tied:
print("game tied. Let's play until someone wins!")
continue
else:
# determine who won
max_score = max(score_board.values())
for player in score_board:
if score_board[player] == max_score:
print(player, "won with a score of", max_score)
return # a return will exit the function and thus break the loop
def main():
"""The main function controls the entire program on a high level"""
player_names = ("player 1", "player 2")
play_game(player_names)
return
# These lines make sure the game won't start when this file is imported using 'import'
if __name__ == '__main__':
main()
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.
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?")