Questions about anything at all?

Where we are :

- booleans assignment due Tuesday
- midterm due the week after that (... please be working on that)

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.

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) :

- Understand the problem and specific specifically what the code should do.
- Break the problem into smaller pieces - functions.
- Write and document good APIs for those pieces.
- "top-down design" - think about the big picture , even if the details aren't clear yet.
- "bottom-up implementation" - work on the details , even if how the small tasks dovetail together isn't clear yet.
- "prototyping and spiral development" - interative improvement - start simple and add features and complexity
- "unit tests" and doctests - making sure that the pieces are well defined and work as expected

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$
```