Python Dice Rolling game - How to check separate rolls and add total - python

Hi guys I am in the midst of creating a dice in game in python. Below is my working code. So far if a player were to roll the dice one time, I can easily check if the rolled number is 1, however how can I make it so that if I want to roll lets say 10 times, I want to be able to check if any of those 10 rolls, any of them equaled 1, and then stop it, if none equaled 1, I would add them all up.
Basically How do I check the result of each seperate roll, and adding them up if a 1 is not rolled.
import random
import sys
def rollingdice(roll): #define function
total = 0 #starting count
for i in range(roll):
total+= random.randint(1, 6)
if total == 1:
print("You rolled a 1: You have zero points for the round")
else:
print(total)
main()
def main():
roll=int(input("Player 1: How many times will you roll "))
rollingdice(roll)
main()

Just add a variable to hold the rolled number and check if it is 1, then break out of the loop if it is
def rollingdice(roll): #define function
total = 0 #starting count
for i in range(roll):
rolled = random.randint(1, 6)
if rolled == 1:
print("You rolled a 1: You have zero points for the round")
break
total += rolled
if rolled != 1: print(total)
main()

Another approach:
from itertools import takewhile
import random
def rollingdice(roll):
rolls = (random.randint(1, 6) for i in range(roll))
rolls = list(takewhile(lambda n: n != 1, rolls))
if len(rolls) == roll:
print(total)
else:
print("You rolled a 1: You have zero points for the round")

Related

How can I get repeating functions of a script and variable changes

I need to make a game based on the 'drinking' game Ship, Captain, Crew. The game consists of rolling 5 dies, and if the numbers are equal to 6,5,4 (in that order), you win. 6 is the Ship, 5 is the Captain and 4 is the crew. I wrote basic script but I'm still having issues. I have an issue where when I execute the script, the rolls never stop as I'm having issues telling the "roll = random.randint(1,6)" to only run 5 times then stop. Also, 'Dice' Is trying to define the number of rolls. So for example: after the dice has been rolled 5 times, Dice would = 5. I need help making it so that the script recognises that the dice must be rolled 5 times, and when it is, if the numbers rolled were not 6,5 and 4, end the game. Can anyone help?
Code:
import random
Dice = 0
SHIP_CAPTAIN_CREW = 6, 5, 4
SHIP = 6
CAPTAIN = 5
CREW = 4
WINNING_SCORE = 6, 5, 4
while Dice != WINNING_SCORE:
roll = random.randint(1,6)
print ("You Rolled A", roll)
if roll == SHIP:
print("You found the ship!")
if roll == CAPTAIN:
print("You found the Captain")
if roll == CREW:
print("You found the Crew!")
if roll == SHIP:
score = +1
roll
else:
Dice = roll
if roll == CAPTAIN :
score = +1
roll
else:
Dice += roll
if Dice == 5:
break
print ("Dice:", roll)
Since you want to run it a set number of times, a for loop with a range would be better.
Additionally, the code you have now doesn't check to make sure the numbers are rolled in the correct order.
import random
needed_value = 6; #the next roll you need
for x in range(5) :
roll = random.randint(1,6)
print ("You Rolled A", roll)
if roll == 6:
print("You found the ship!")
if(needed_value == 6):
needed_value = 5 #update the next needed number
if roll == 5:
print("You found the Captain")
if(needed_value == 5):
needed_value = 4 #update the next needed number
if roll == 4:
print("You found the Crew!")
if(needed_value == 4):
print ("Win!") #all three were found in order
break #the game has been won so no need to continue with loop
If I understood your game and your expectation well, this might be the answer.
import random
def drinking():
names = ['crew', 'captain', 'ship']
winning_order = '654'
score = ''
for _ in range(5):
dice = random.randint(1, 6)
print(f"You Rolled A {dice}")
if 4 <= dice <= 6:
print(f'You found the {names[dice - 4]}')
score += str(dice)
elif score == winning_order:
return f'Dice:, {dice}' # You won the game would be ideal
return 'You lose the game'
print(drinking())
You Rolled A 6
You found the ship
You Rolled A 6
You found the ship
You Rolled A 5
You found the captain
You Rolled A 1
You Rolled A 3
You lose the game
I made some heavy modifications to your code. I was hoping to keep it easy to understand, while still doing everything you're expecting, and also making it easy to modify.
import random
# I put the logic inside a function so you can call it
# DiceRound() will return 0 on wins, and -1 on losses
def DiceRound():
SHIP = 6
CAPTAIN = 5
CREW = 4
Counter = 0 # keeps track of how many rolls we've made
WINNING_SCORE = 0 # modified to keep track of win-condition
dierolls = "" # used for output
while WINNING_SCORE != 3 and Counter < 5:
v = 0 # verbate
roll = random.randint(1,6)
Counter = Counter +1
dierolls = dierolls + "[%d] "%roll
# Any time we roll 6, we're 1-roll towards victory
if roll == SHIP:
WINNING_SCORE = 1
# If we roll a 5 when we've already rolled a 6
if roll == CAPTAIN and WINNING_SCORE == 1:
WINNING_SCORE = 2
# Elsewise if we just rolled a 5
elif roll == CAPTAIN and WINNING_SCORE != 1:
WINNING_SCORE = 0
# If we roll a 4 when we've already rolled a 6 and a 5
if roll == CREW and WINNING_SCORE == 2:
WINNING_SCORE = 3
print(dierolls)
print("... Round won!", end="")
return(0) # return; exits loop and returns 0 for Win-condition
# Elsewise if we just rolled a 4
elif roll == CREW and WINNING_SCORE != 2:
WINNING_SCORE = 0
# If we rolled below a 4, anytime
if roll < 4:
WINNING_SCORE = 0
# If we rolled all five times without winning
print(dierolls)
print("... Round lost.", end="")
return(-1) # return; exits loop and returns -1 for Lose-condition
Output from this script will look somewhat like this if you call DiceRound() until the return == 0:
[1] [6] [1] [5] [5] ... Round lost.
[3] [6] [4] [5] [3] ... Round lost.
[4] [2] [5] [4] [4] ... Round lost.
[2] [2] [6] [5] [4] ... Round won!

dice roll simulation in python

I am writing a program that is to repeatedly roll two dice until the user input target value is reached. I can not figure out how to make the dice roll happen repeatedly. Please, help...
from random import randrange
print ("This program rolls two 6-sided dice until their sum is a given target value.")
input = int (input("Enter the target sum to roll for:"))
#def main():
dice1 = randrange (1,7)
dice2 = randrange (1,7)
sumofRoll = dice1 + dice2
output = "Roll: {} and {}, sum is {}".format (dice1,dice2,sumofRoll)
print (output)
if sumofRoll == input:
print ("All done!!")
if sumofRoll != input:
#how do I make this repeatedly run until input number is reached?!
Here is a complete working code which takes care of invalid sum entered as input as well. The sum of two dice rolls cannot be either less than 2 or more than 13. So a check for this condition makes your code slightly more robust. You need to initialize sumofRoll = 0 before entering the while loop as this would be needed to first enter the while loop. The value of 0 is a safe value because we excluded the value of 0 entered by user to be a valid sum.
from random import randrange
print ("This program rolls two 6-sided dice until their sum is a given target value.")
input_sum = int(input("Enter the target sum to roll for:"))
def main():
sumofRoll = 0
if input_sum < 2 or input_sum > 13:
print ("Enter a valid sum of dices")
return
while sumofRoll != input_sum:
dice1 = randrange (1,7)
dice2 = randrange (1,7)
sumofRoll = dice1 + dice2
output = "Roll: {} and {}, sum is {}".format (dice1,dice2,sumofRoll)
print (output)
if sumofRoll == input_sum:
print ("All done!!")
main()
This program rolls two 6-sided dice until their sum is a given target value.
Enter the target sum to roll for:10
Roll: 3 and 5, sum is 8
Roll: 6 and 6, sum is 12
Roll: 5 and 1, sum is 6
Roll: 2 and 5, sum is 7
Roll: 6 and 6, sum is 12
Roll: 3 and 5, sum is 8
Roll: 1 and 2, sum is 3
Roll: 6 and 4, sum is 10
All done!!
I took your game and added some elements for you to peek through. One is you could use random.choice and select from a die list instead of generating new random ints repeatedly. Second you can use a try/except block to only accept an int and one that is within the range of (2, 13). Next we can add a roll_count to track the amount of rolls to hit our target. Our while loop will continue until target == roll_sum and then we can print our results.
from random import choice
die = [1, 2, 3, 4, 5, 6]
print('This program rolls two 6-sided dice until their sum is a given target.')
target = 0
while target not in range(2, 13):
try:
target = int(input('Enter the target sum to roll (2- 12): '))
except ValueError:
print('Please enter a target between 2 and 12')
roll_sum = 0
roll_count = 0
while target != roll_sum:
die_1 = choice(die)
die_2 = choice(die)
roll_sum = die_1 + die_2
roll_count += 1
print('You rolled a total of {}'.format(roll_sum))
print('You hit your target {} in {} rolls'.format(target, roll_count))
...
You rolled a total of 4
You rolled a total of 12
You hit your target 12 in 29 rolls
This is a simple while loop:
sumofRoll = -1; #a starting value!
while sumofRoll != input:
#Put the code that updates the sumofRoll variable here
count = 0
while(sumOfRoll != input):
dice1 = randrange(1,7)
dice2 = rangrange(1,7)
count = count + 1
sumOfRoll = dice1 + dice2
print("sum = %s, took %s tries" % (sumOfRoll, count))
Use a do while statement
do:
dice1=randrange(1,7)
...
while(sumofroll != input)
print("all done")

Determine average number of roll to get 1-1 on a pair of dice

Roll a pair of 6-sided dice (a.k.a. D6) until they both come up '1'. Count the number of rolls this took.
Run 100 trials of this. Print out the result of each roll and report the average number of rolls required.
Use nested loops. The outer loop runs 100 trials; the inner loop continues rolling until 1-1 appears. Then update the running counts and go to the next trial.
import random
dice1, dice2 = " ", " "
roll = " "
for roll in range(1, 101):
roll = 0
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
print(dice1, ",", dice2)
while dice1 == 1 and dice2 == 1:
break
this doesn't stop when 2 1's a rolled and i need help accumulating the roll number and trial number
The problem is that your inner loop really doesn't do anything.
You have to give it the work you described: keep rolling two dice until they both come up 1. I'll outline the logic you described, but have trouble implementing. I'll leave the detailed work to you. :-)
roll_count = 1
while not (dice1 == 1 and dice2 == 1):
roll both dice
increment roll_count
running_total += roll_count
You also need to initialize running_total somewhere.
Does this get you unstuck?
import random
from itertools import count
for roll in range(1, 101):
for c in count(1):
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
print(c, ':', dice1, ",", dice2)
if dice1 == 1 and dice2 == 1:
break

Python - rolling a dice fairly and counting how many 4's I get

So I had to make code that roll a die fairly and counted how many 4's I got. With the help of you all 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. It
should calculate BOTH numbers in ONE run – you are counting two
distinct things."
And this is my code freshly fixed.
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
print ("In", n,"rolls of a pair of dice, there were",twoCount,"twos.")
rollManyCountTwo(6000)
Your code is bad, and hence, not as random as it should be.
randrange(low,up) includes both boundaries.
Look at what you do in the roll function:
you roll a dice. If it is 1, you return "1".
If it is not 1, you roll the dice again! That's simply wrong, and in a game would be considered cheating.
Your roll function is absolutely unnecessary, and can be replaced by
str(randrange(1,6)).
Also, why would you need the numbers as strings? You don't actually use these strings, so just stick with the result of randrange as it is -- a number.
EDIT:
You say
Yeah I'm assuming some of it is unnecessary but it's for a class and this is the way he wants it so I'm trying to keep it how he wants. I thought that's what I was doing but I could find a way around it!
All of it is unnecessary. There is a function that does what you want, so no need to encapsulate this in a class.
Well, you can just
class ash_class(object):
def roll():
return str(randrange(1,6))
For your counting problem: Python comes with all the tools.
counts = [0] * 6 # this is [0,0,0,0,0,0]
for i in range(n):
counts[randrange(1,6)] += 1
print counts
As you notice, it's really handy if the randrange numbers are numbers and not strings, as you can then use them like numbers to index an array.
As a personal advice: There should always be the freedom to discuss bad design choice. One such bad design choice is forcing you to convert numbers to strings, when you clearly need to work with them as numbers.
You shouldn't be calling randrange() inside the roll() in every if condition, instead you should call it once and save it in a variable and check.
The code would look like -
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 rollManyCountFour(n):
fourCount = 0
for i in range (n):
if roll() == "6":
fourCount += 1
print ("In", n,"rolls of a due, there were",fourCount,"fours.")
rollManyCountFour(6000)
I have used np.random.randint(1, 7, N), with N being the number of rolls and have used the following system to store it (if this helps):
R1s = 0
R2s = 0
R3s = 0
R4s = 0
R5s = 0
R6s = 0
for i in range(0, N):
if x[i] == 1:
R1s += 1
elif x[i] == 2:
R2s += 1
elif x[i] == 3:
R3s += 1
elif x[i] == 4:
R4s += 1
elif x[i] == 5:
R5s += 1
else:
R6s += 1
print(R1s)
# Ans ≈ N/6

While loop won't stop in python

We are trying to make a python program to simulate games of craps and display the probability of winning. I have narrowed down the answer to the while loop and as the title suggests, when it hits the loop it won't exit. As far as I can tell the loop should exit but instead just returns and endless train of "false". Here is the code for the whole program with comments, I'll type out the rules for craps (as far as what we're using for our program) at the bottom.
import random
def craps()
roll = random.randint(1,6) + random.randint(1,6)
if (roll == 7 or roll == 11): #Tests if the player should win. If so it adds a 1 to the win counter
return 1
elif (roll == 2 or roll == 3 or roll == 12): #Tests if player should lose. If so adds 0
return 0
else:
roll2 = 0 #initializes roll2 for the while
while (roll2 != roll or roll2 != 7): #The player keeps rolling until they get a 7 or the initial roll
roll2 == random.randint(1,6) + random.randint(1,6) #Rolls the dice
if (roll2 == roll): #Tests if the player should win
return 1
elif (roll2 == 7): #Tests if the player should lose
return 0
win = 0 #Start the win counter at 0
games = int(input("Enter the amount of games you want played: ")) #Accept how many games will be played
for i in range (games):
win = win + craps() #adds a 1 or a 0 depending on if a game was won
print ("The probability of winning is:", win, "/", games, " =", float(win)/games) #print the probability of winning
The basic rules we are using are: the player rolls 2 six sided dice, if the initial roll is a 7 or 11 the player wins (line 4). If the player rolls a 2, 3 or a 12 the player loses (line 6) If the player doesn't get either they keep rolling until they match the initial roll or roll a 7. If they match the initial roll they win, if they get a 7 they lose (lines 10-15). Our program is supposed to simulate and display the probability of the player winning.
This is my first time using this site so let me know if I screwed up on anything for the future. And thanks for helping!
A common, but very frustrating and time-wasting typo, which can get even the best Python developers. Replace roll2 == random.randint(1,6) + random.randint(1,6) with roll2 = random.randint(1,6) + random.randint(1,6).
Also, I think you need roll2 != roll and roll2 != 7. From a stylistic point of view, it's better to omit the parenthesis around the statement evaluated in an if or while line.
Your loop has a slight amount of redundancy in it though. You check for roll2 being roll or 7 at the top of each loop and at the end of each loop. You could also consider trying this:
while True:
# do everything in the same way as before
or
while roll2 != roll and roll2 != 7:
# do stuff with the roll
roll = random.randint(1,6) + random.randint(1,6)
return 1 if roll2 == roll else return 0 # a "ternary operator" in Python
A double equals sign tests for equality. Change it to single for your code to work. Here is your edited code:
import random
def craps()
roll = random.randint(1,6) + random.randint(1,6)
if (roll == 7 or roll == 11): #Tests if the player should win. If so it adds a 1 to the win counter
return 1
elif (roll == 2 or roll == 3 or roll == 12): #Tests if player should lose. If so adds 0
return 0
else:
roll2 = 0 #initializes roll2 for the while
while (roll2 != roll or roll2 != 7): #The player keeps rolling until they get a 7 or the initial roll
roll2 = random.randint(1,6) + random.randint(1,6) #Rolls the dice
if (roll2 == roll): #Tests if the player should win
return 1
elif (roll2 == 7): #Tests if the player should lose
return 0
win = 0 #Start the win counter at 0
games = int(input("Enter the amount of games you want played: ")) #Accept how many games will be played
for i in range (games):
win = win + craps() #adds a 1 or a 0 depending on if a game was won
print ("The probability of winning is:", win, "/", games, " =", float(win)/games) #print the probability of winning
Here is an example:
>>> import time
>>> x = 7
>>> x == 7
True
>>> while x != 6:
... x == 6
... time.sleep(1)
...
False
False
False
^CTraceback (most recent call last):
File "<stdin>", line 3, in <module>
KeyboardInterrupt
>>> while x != 6:
... x = 6
... time.sleep(1)
...
>>>
Your first issue is with this line:
while (roll2 != roll or roll2 != 7): #The player keeps rolling until they get a 7 or the initial roll
This will be an infinite loop if roll is not equal to 7. You should have an and here instead, because you want to change if one of these is false, not if both are. Make sense?
You want:
while (roll2 != roll and roll2 != 7): #as long as both are not `True` then keep rolling.
Your other issue is with this line:
roll2 == random.randint(1,6) + random.randint(1,6)
The double equals checks to see if roll2 is equal to the expression on the left. What you want to do is set it equal to the expression on the left, like so:
roll2 = random.randint(1,6) + random.randint(1,6)

Categories