Created
June 6, 2018 07:08
-
-
Save SlyCodePanda/ed3b4a5d79631e0ac01b5615c31b1a0c to your computer and use it in GitHub Desktop.
Simulates 5000 games of Craps and works out the probability of winning a game, and the average number of times the dice is rolled per game.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import division | |
import random | |
numRolls = 0 # Number of times the dice is rolled. | |
# generates a random number between 1 and 6, like rolling a 6 sided die. | |
def rollDice() : | |
return random.randint(1, 6) | |
# Simulate this 5000 times, then to get the prob of winning, do (numb of times won/numb of times simumalted). | |
def sim() : | |
global numRolls | |
# Rolls two 6-sided die. | |
dice1 = rollDice() | |
dice2 = rollDice() | |
numRolls += 1 | |
print( 'Dice1 = ' + str(dice1) ) | |
print( 'Dice2 = ' + str(dice2) ) | |
total = dice1 + dice2 | |
ref = 0 | |
# Immediate loss or immediate win. | |
if total == 7 or total == 11 : | |
return 'YOU WIN!' | |
elif total == 2 or total == 3 or total == 12 : | |
return 'YOU LOSE!' | |
# Reference point | |
elif total == 4 or total == 5 or total == 6 or total == 8 or total == 9 or total == 10 : | |
ref = total | |
print( 'ref point = ' + str( total ) ) | |
# Keep rolling two dice till you get same value as ref, then you win. | |
# If you roll again and get 7, you lose. | |
newRoll1 = rollDice() | |
newRoll2 = rollDice() | |
numRolls += 1 | |
newTotal = newRoll1 + newRoll2 | |
while newTotal != ref : | |
newRoll1 = rollDice() | |
newRoll2 = rollDice() | |
numRolls += 1 | |
newTotal = newRoll1 + newRoll2 | |
print( 'newTotal = ' + str(newTotal) ) | |
if newTotal == 7 : | |
return 'YOU LOSE!' | |
if newTotal == ref : | |
return 'YOU WIN!' | |
else : | |
return None | |
def main() : | |
# Simulate 5000 times. Expect prob. of winning to be approx 0.49. | |
numOfSims = 5000 | |
numOfWins = 0 | |
numOfLoss = 0 | |
for i in range(numOfSims) : | |
game = sim() | |
if game == 'YOU WIN!' : | |
print('YOU WIN!') | |
numOfWins = numOfWins + 1 | |
if game == 'YOU LOSE!' : | |
print('YOU LOSE!') | |
numOfLoss = numOfLoss + 1 | |
print('The number of wins = ' + str(numOfWins) ) | |
print('The number of losses = ' + str(numOfLoss)) | |
print('The number of sims = ' + str(numOfSims)) | |
prob = float(numOfWins / numOfSims) | |
print('The probability of winning = ' + str(prob) ) | |
print('The dice was rolled ' + str(numRolls)) | |
print('On average, the dice is rolled ' + str(numRolls / numOfSims)) | |
if __name__ == "__main__": | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment