Producing probability of wins in Python craps game - python

I have the logic down for this game of craps. My only problem right now is that I can't seem to get any output for finding the probability of wins for the game. Here is the code:
from random import seed, randint
def simulate():
die1 = randint(1, 6)
die2 = randint(1, 6)
roll = die1 + die2
first_roll = roll
if first_roll == 7 or first_roll == 11:
return True
elif first_roll == 2 or first_roll == 3 or first_roll == 12:
return False
else:
second_roll = randint(1, 6) + randint(1, 6)
while second_roll != first_roll and second_roll != 7:
if second_roll == first_roll:
return True
elif second_roll == 7:
return False
## Main
def probability(n):
simulate()
wins = 0
for i in range(n):
if simulate() == 1:
wins += 1
return
print(probability(10000))
I want to find the probability of wins for 10000 trials. However, I don't get any output when running this code. Nothing shows up. Where am I going wrong on this? I have tried for a couple hours but nothing seems to be working for me. Please include code and what I was doing wrong. I know for a fact that it should be 49% but I can't seem to arrive at that answer.

I am sorry for my latest answer, I didn't read that its craps game.
from random import seed, randint
def simulate():
die1 = randint(1, 6)
die2 = randint(1, 6)
roll = die1 + die2
first_roll = roll
if first_roll == 7 or first_roll == 11:
return True
elif first_roll == 2 or first_roll == 3 or first_roll == 12:
return False
else:
while True:
second_roll = randint(1, 6) + randint(1, 6)
if second_roll == first_roll:
return True
elif second_roll == 7:
return False
# Main
def probability(n):
wins = 0
for i in range(n):
if simulate() == 1:
wins += 1
return wins
print(probability(100000))
I think its the answer, I changed the second part of simulate()
where its returning True, when second_roll == first_roll, returning False when second_roll==7, and repeats that while loop by continue, if second_roll is equal to other number.

Related

Python problem: Craps game using Monte Carlo estimation in a dice game

Here is the game: the player throws a pair of standard, six-sided dice.
If the player rolls a total of 7 or 11, the player wins.
If the player rolls a total of 2, 3, or 12, the player loses.
For all other roll values, the player will repeatedly roll the pair of dice until either she rolls the initial value again (in which case they win) or 7 (bet is lost.)
Here is my code:
from random import seed, randint
def simulate():
win_count = 0
die1 = randint(1, 6)
die2 = randint(1, 6)
roll = die1 + die2
if roll == 7 or roll == 11:
return True
win_count += 1
elif roll == 2 or roll == 3 or roll == 12:
return False
else:
die1 = randint(1, 6)
die2 = randint(1, 6)
new_roll = die1 + die2
while roll != new_roll and roll != 7:
if new_roll == roll:
return True
win_count += 1
elif new_roll == 7:
return False
return win_count
## Main
for trials in range(1000):
simulate()
print(win_count / 1000)
I also need to find the probability of winning the "pass bet", which is what the rules are described above. The number of trials is 1000. However, nothing returns from this code. Where am I going wrong?

Python craps game: Wrong output

I'm a beginner and I can't figure out why I can't get the output I
want. It's a craps game. It's suppose to go like:
How many games do you want to play > 6 You rolled 5 + 2 = 7 You
win
What I got is something like: You rolled 1 + 6 = 7 You rolled 1 + 6 =
7 You rolled 1 + 6 = 7 You lose
import random
def rollDice():
roll_1 = random.randint(1,7)
roll_2 = random.randint(1,7)
return roll_1, roll_2
def determine_win_or_lose(dice1,dice2):
sum = dice1 + dice2
print("You rolled", dice1, "+", dice2, "=", sum )
if sum == '2' or '3' or '12':
return 0
elif sum == '7' or '11':
return 1
else:
print("Point is", sum)
determinePointValueResult(sum)
if determinePointValueResult(sum) == 1:
return 1
elif determinePointValueResult(sum) == 0:
return 0
def determinePointValueResult(sum):
point = sum
while sum != 7 and sum != point:
x, y = rollDice()
sum = x + y
if sum == point:
return 1
elif sum == '7':
return 0
print("You rolled", x, "+", y, "=", sum )
#==== MAIN =====
win = 0
lose = 0
game = int(input("How many games do you want to play > "))
for i in range(game):
x, y = rollDice()
determine_win_or_lose(x, y)
if determine_win_or_lose(x, y) == 1:
print("You win")
win = win + 1
elif determine_win_or_lose(x, y) == 0:
print("You lose")
lose = lose + 1
print("Game results: ", win, "wins and", lose, "losses")
Your issue come from the main, because you call the determine_win_or_lose function 3 times, the first one before the if (and i'm not sure why since you do nothing with it), a second time to check the condition of the if and a third time to check the condition of the elif.
Since it's this function that print the message, and you call the function 33 times each iteration of the for loop, it's normal to get the message printed 3 times.
(
Also since the determine_win_or_lose will always return 0 or 1 you don't really need an elif you can just do an if/else to achieve the same thing and simplify your code a bit.
)
So i'd suggest the following :
#==== MAIN =====
win = 0
lose = 0
game = int(input("How many games do you want to play > "))
for i in range(game):
x, y = rollDice()
result = determine_win_or_lose(x, y)
if result == 1:
print("You win")
win = win + 1
else:
print("You lose")
lose = lose + 1
print("Game results: ", win, "wins and", lose, "losses")
Obvious issues:
You call determine_win_or_lose too many times in your for loop. Change it to:
for i in range(game):
x, y = rollDice()
result = determine_win_or_lose(x, y)
if result == 1:
print("You win")
win = win + 1
elif result == 0:
print("You lose")
lose = lose + 1
Your check in determine_win_or_lose is incorrect. It should be something like:
def determine_win_or_lose(dice1,dice2):
sum = dice1 + dice2
print("You rolled", dice1, "+", dice2, "=", sum )
if sum == 2 or sum == 3 or sum == 12:
return 0
elif sum == 7 or sum == 11:
return 1
else:
print("Point is", sum)
determinePointValueResult(sum)
if determinePointValueResult(sum) == 1:
return 1
elif determinePointValueResult(sum) == 0:
return 0
In determinePointValueResult you shouldn't compare sum to a string, but an integer:
def determinePointValueResult(sum):
point = sum
while sum != 7 and sum != point:
x, y = rollDice()
sum = x + y
if sum == point:
return 1
elif sum == 7:
return 0
print("You rolled", x, "+", y, "=", sum )
It's possible that determine_win_or_lose and determinePointValueResult are returning None. You may need to change your elifs to elses or create a new else case.

Python: how to let dice not roll same value

In my Python program I want to roll a dice 8 times, but without it repeating the same value. I am trying different things but can't find a solution. My code is all follows:
if time%2 == 0 and counter_agents<max_agents:
succeeded=False
teller=0
while (not(succeeded)and teller<10):
dice = random.randint (0,7)
combis = []
if dice == 0:
pos_x=20
pos_y=75
elif dice == 1:
pos_x=21
pos_y=75
elif dice == 2:
pos_x=60
pos_y=75
elif dice == 3:
pos_x=61
pos_y=75
elif dice == 4:
pos_x=100
pos_y=75
elif dice == 5:
pos_x=101
pos_y=75
elif dice == 6:
pos_x=140
pos_y=75
elif dice == 7:
pos_x=141
pos_y=75
if counter_agents+1<=max_agents: #field[pos_y,x_pos]==0 and
succeeded=True
teller=teller+1
I believe this function does the job
import random
def roll_dice(min, max) -> int:
numbers = set()
for _ in range(max - min + 1):
while (dice_value := random.randint(min, max)) in numbers:
pass
numbers.add(dice_value)
yield dice_value
You can call it like this:
dice = roll_dice(0, 7)
dice_value = next(dice)
To get all values:
list(roll_dice(0, 7))
You can use this:
#Importing the library
import numpy as np
#create a function "def"
def roll():
numbers = list(np.random.choice(range(8), 8, replace=False))
return numbers
#calls the function
roll()

Caught in a Python infinite loop

I am trying to write a program to play 100 games of Craps and print out the overall results. I have an infinite loop at the end of my code.
Does anyone see the problem?
I assume my 2nd function could be calling diceRoll again for secondRoll. Trying that now...
Specs:
The player must roll two six-side dice and add the total of both
dice.
The player will win on the first roll if they get a total of 7 or 11
The player will lose on the first roll if they get a total of 2, 3,
or 12
If they get any other result (4, 5, 6, 8, 9, 10), they must roll
again until they either match their first roll (a win) or get a
result of 7 (a loss)
Use at least two functions in your program
from random import randrange as rd
winTuple = 7, 11
lossTuple = 2, 3, 12
wins = 0
losses = 0
x = 1
def diceRoll (number, type = 6):
result = 0
for i in range(number):
result += rd(1, type +1)
return result
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
secondRoll = diceRoll(2)
while secondRoll != 7 or secondRoll != firstRoll:
if secondRoll == 7:
wins += 1
elif secondRoll == firstRoll:
wins += 1
else:
secondRoll = diceRoll(2)
x += 1
print("wins: ", wins)
print("losses: ", losses)
Looks like you need to eliminate your inner loop. First, the loop conditions are in direct conflict with your conditional statements, so the loop never exits. Second, why would you want a loop here? Even if you fixed it, all it would do is keep rolling the second dice until a win is scored.
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
secondRoll = diceRoll(2)
if secondRoll == 7 or secondRoll == firstRoll:
wins += 1
x += 1
In response to your comment, this is how you create your second loop. You make an infinite loop with while True and break out of it when the conditions are met.
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
while True:
secondRoll = diceRoll(2)
if secondRoll == 7:
losses += 1
break
elif secondRoll == firstRoll:
wins += 1
break
x += 1
If your firstRoll != 7 (let's say firstRoll = 8) then your script cannot exit the second nested loop because either secondRoll != 7 or secondRoll = 7 and therefore firstRoll != secondRoll (7 != 8)
I am not sure how your program goes through 100 games of craps, here is an example of a program I wrote quick that goes through 100 games. Games being times you either hit or don't hit the point.
Clearly you need to understand how craps works to make something like this, so I am assuming you do. The program you were trying to write, even though you were stuck in the loop, was not actually playing a full game of craps.
You can choose the amount of games you want and the only thing it stores is if you won or lost.
You can add other statistics if you would like, for example points hit and which points they were etc.,
I added text to, also, make it user friendly if this is for a school project.
There are many different ways to do this, I used a main while loop and created two functions for whether the button is on or off.
You could obviously condense this, or write a class instead but I simply put this together quick to give you an idea and see how it goes through every loop and statement.
I am still a novice, so I apologize to anyone else reading, I know the below is not the most efficient/does not perfectly follow PEP8 especially the long if statement in the main loop.
This does perform what you wanted and feel free to change the number of games. Enjoy!
import random
wins = 0
losses = 0
gamenum = 0
#Used a list to pull the dice numbers from but not mandatory
dicenum = [2,3,4,5,6,7,8,9,10,11,12]
#Function when point is off
def roll_off():
#Random roll from list
roll = random.choice(dicenum)
if roll == 2:
print("2 craps")
elif roll == 3:
print("3 craps")
elif roll == 4:
print("Point is 4")
return(4)
elif roll == 5:
print("Point is 5")
return(5)
elif roll == 6:
print("Point is 6")
return(6)
elif roll == 7:
print("Winner 7")
elif roll == 8:
print("Point is 8")
return(8)
elif roll == 9:
print("Point is 9")
return(9)
elif roll == 10:
print("Point is 10")
return(10)
elif roll == 11:
print("Yo 11")
elif roll == 12:
print("12 craps")
#Function when point is on
def roll_on(x):
#Random roll from list
roll = random.choice(dicenum)
if roll == 2:
print("2 craps")
elif roll == 3:
print("3 craps")
elif roll == 4:
print("You rolled a 4")
elif roll == 5:
print("You rolled a 5")
elif roll == 6:
print("You rolled a 6")
elif roll == 7:
print("7 out")
elif roll == 8:
print("You rolled a 8")
elif roll == 9:
print("You rolled a 9")
elif roll == 10:
print("You rolled a 10")
elif roll == 11:
print("Yo 11")
elif roll == 12:
print("12 craps")
#Check if you hit the point
if x == 4 and roll == 4:
print("You win!")
return (True)
elif x == 5 and roll == 5:
print("You win!")
return (True)
elif x == 6 and roll == 6:
print("You win!")
return (True)
elif x == 7 and roll == 7:
print("You win!")
return (True)
elif x == 8 and roll == 8:
print("You win!")
return (True)
elif x == 9 and roll == 9:
print("You win!")
return (True)
elif x == 10 and roll == 10:
print("You win!")
return (True)
#Check if you 7'ed out
if roll == 7:
print("You lose!")
return (False)
#Main game, change the amount of games you want to play
while gamenum < 100:
diceresult = roll_off()
#If statement to check the point
if diceresult == 4 or diceresult == 5 or diceresult == 6 or diceresult == 8 or diceresult == 9 or diceresult == 10:
active = True
print("The point is on!")
while active == True:
curentstate = roll_on(diceresult)
if curentstate == False:
gamenum += 1
losses += 1
print("------------")
print("Games:", gamenum)
print("Losses:", losses)
print("Wins:", wins)
print("------------")
break
elif curentstate == True:
gamenum += 1
wins += 1
print("------------")
print("Games:", gamenum)
print("Losses:", losses)
print("Wins:", wins)
print("------------")
break

How can I simplify this code

I'm a beginner, and I wanted to know if there was a simpler way of write this out in Python. I'm assuming some type of dictionary, but I do not understand how to write it out.
I was on a cruise a couple of days ago, and I play craps. I wanted to know if the odds are somewhat correct. So, I wrote this, but I know there is a simpler way.
import random
dice2 = 0
dice3 = 0
dice4 = 0
dice5 = 0
dice6 = 0
dice7 = 0
dice8 = 0
dice9 = 0
dice10 = 0
dice11 = 0
dice12 = 0
for i in range(100000):
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
number = dice1 + dice2
#print(dice1)
if number == 2:
dice2 +=1
elif number == 3:
dice3 += 1
elif number == 4:
dice4 += 1
elif number == 5:
dice5 += 1
elif number == 6:
dice6 += 1
elif number == 7:
dice7 += 1
elif number == 8:
dice8 += 1
elif number == 9:
dice9 += 1
elif number == 10:
dice10 += 1
elif number == 11:
dice11 += 1
elif number == 12:
dice12 += 1
total = dice2+dice3+dice4+dice5+dice6+dice7+dice8+dice9+dice10+dice11+dice12
At the end of this, it just prints out the percentage of hits on numbers from 2-12.
I'd use Counter, as that's what it was made for:
from random import randint
from collections import Counter
counts = Counter(randint(1, 6) + randint(1, 6) for i in range(100000))
total = sum(counts.values())
number_of_tens = counts[10]
from random import randint
dice = [0]*11
for i in range(100000):
dice[randint(1,6)+randint(1,6)-2] += 1
total = sum(dice) #it is 100000, of course
for i, v in enumerate(dice, 2):
print('{0}: {1}%'.format(i, v*100.0/total))
import random
def roll(n=6):
return random.randint(1, n)
dice = dict.fromkeys(range(2, 13), 0)
for i in range(100000):
number = roll() + roll()
dice[number] += 1
total = float(sum(dice.values()))
for k,v in dice.items():
print "{}, {:.2%}".format(k, v/total)

Categories

Resources