I did another exercise, this time it simulates n games of craps(dice game) and outputs the wins and win percentage!
#craps.py -- Simulates multiple games of craps
# and estimates the probability that the player wins.
import random
def output(wins, total):
winrate = wins / total
print("The player won {0} of {1} games ({2:0.2%})".format(wins, total, winrate))
def rolldies():
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll = dice1 + dice2
return roll
def simOneGame():
initial_roll = rolldies()
if initial_roll == 2 or initial_roll == 3 or initial_roll == 12:
return True # won
elif initial_roll == 7 or initial_roll == 11:
return False #lost
else:
#Roll until roll is 7 or initial roll
roll = rolldies()
while roll != 7 and roll != initial_roll:
roll = rolldies()
if roll == 7:
return True #won
else:
#roll is inital_roll
return False #lost
def simNGames(games_to_sim):
wins = 0
for i in range(games_to_sim):
if simOneGame():
wins += 1
return wins
def main():
games_to_sim = int(input("How many games to simulate? "))
wins = simNGames(games_to_sim)
output(wins, games_to_sim)
if __name__ == "__main__":
main()
Always open for suggestions on what to improve/do differently or more pythonic.