Intro to
Programming
(with Python)

Fall 2018
course
site

Thu Oct 17

Questions about anything at all?

Where we are :

Today : practice.

Chapter 9 is called "simulation and design" ... which discusses some ideas behind the practice of writing software. Please read that chapter. We'll be discussing in class some of those ideas over the next week or so.

craps

Our goal today is to write together as a group a program that simulates the game of craps, and in particular estimates the odds of winning at craps.

Writing software ideas (some from chapter 9) :

So let's do this together.


Here's what we came up with :

"""
 craps.py

 rules:
   roll two dice
     if 2, 3, 12 => lose
     if 7, 11 => win
     otherwise result is "point"
   then continue to roll
     if get point you win
     if 7 => lose
     otherwise keep rolling

"""
from random import randint

DEBUG = False

def print_debug(message):
    if DEBUG:
        print("debug: ", message)

def roll(n_dice=2, sides=6):
    """ return sum of two dice """
    total = 0
    for i in range(n_dice):
        total = total + randint(1, sides)
    return total

def win_at_craps():
    """ simulate craps; return True win """
    print_debug("-- win_at_craps() --")
    first_roll = roll()
    print_debug("Your first roll is {}".format(first_roll))
    if first_roll in (7, 11):
        print_debug("You win!")
        return True
    elif first_roll in (2, 3, 12):
        print_debug("You lose! (sucker...)")
        return False
    else:
        while True:
            next_roll = roll()
            print_debug("next roll is {}".format(next_roll))
            if next_roll == first_roll:
                print_debug("You win (finally)")
                return True
            elif next_roll == 7:
                print_debug("You lose (finally)")
                return False

def main():
    print("-- craps odds --")
    wins = 0
    n_games = 100000
    for i in range(n_games):
        if win_at_craps():
            wins = wins + 1
    print("You won ", wins, " games out of ", n_games, \
          " so your odds are winning are ", wins/n_games)

if __name__ == '__main__':
    import doctest
    doctest.testmod()
    main()

Running it looks like this

softmaple:Desktop mahoney$ python craps.py 
-- craps odds --
You won  49493  games out of  100000  so your odds are winning are  0.49493
softmaple:Desktop mahoney$ python craps.py 
-- craps odds --
You won  49008  games out of  100000  so your odds are winning are  0.49008
softmaple:Desktop mahoney$ python craps.py 
-- craps odds --
You won  49244  games out of  100000  so your odds are winning are  0.49244
softmaple:Desktop mahoney$ 


https://cs.marlboro.college /cours /fall2018 /python /notes /chap9
last modified Thu November 21 2024 3:41 pm