Craps In Python
I'm trying to simulate n games of craps. The code seems to make sense to me but I never get the right result. For example, if I put in n = 5 i.e. fives games the wins and losses
Solution 1:
The problem is with
ifgame():
wins = wins + 1ifnotgame():
losses = losses + 1
Instead, it should be
ifgame():
wins = wins + 1else:
losses = losses + 1
In your code, you are simulating two games instead of one (by calling game()
twice). This gives four possible outcomes instead of two (win/loss), giving inconsistent overall results.
Solution 2:
In this code
for i in range(n):
if game():
wins = wins + 1ifnotgame():
losses = losses + 1
you call game()
twice, so you play two games right there. What you want is a else block:
for i in range(n):
if game():
wins = wins + 1else:
losses = losses + 1
Btw, you can simplify the logic with in
:
defgame():
dice = roll()
if dice in (2,3,12):
returnFalseif dice in (7,11):
returnTrue# keep rollingwhileTrue:
new_roll = roll()
# re-rolled the initial value => winif new_roll==dice:
returnTrue# rolled a 7 => lossif new_roll == 7:
returnFalse# neither won or lost, the while loop continues ..
The code is quite literally the description you gave.
Solution 3:
Don't do this
for i in range(n):
if game():
wins = wins + 1ifnotgame():
losses = losses + 1
It doesn't work out well at all.
Solution 4:
There are numerous problems with this code. Most importantly, you're calling game() twice per loop. You need to call it once and store the result, and switch based on that.
Solution 5:
An OO rewrite:
import random
try:
rng = xrange # Python 2.x
inp = raw_input
except NameError:
rng = range# Python 3.x
inp = inputdefmakeNSidedDie(n):
_ri = random.randint
returnlambda: _ri(1,n)
classCraps(object):
def__init__(self):
super(Craps,self).__init__()
self.die = makeNSidedDie(6)
self.firstRes = (0, 0, self.lose, self.lose, 0, 0, 0, self.win, 0, 0, 0, self.win, self.lose)
self.reset()
defreset(self):
self.wins = 0
self.losses = 0defwin(self):
self.wins += 1returnTruedeflose(self):
self.losses += 1returnFalsedefroll(self):
return self.die() + self.die()
defplay(self):
first = self.roll()
res = self.firstRes[first]
if res:
return res()
else:
whileTrue:
second = self.roll()
if second==7:
return self.lose()
elif second==first:
return self.win()
deftimes(self, n):
wins = sum(self.play() for i in rng(n))
return wins, n-wins
defmain():
c = Craps()
whileTrue:
n = int(inp("How many rounds of craps would you like to play? (0 to quit) "))
if n:
print("Won {0}, lost {1}".format(*(c.times(n))))
else:
breakprint("Total: {0} wins, {1} losses".format(c.wins, c.losses))
if __name__=="__main__":
main()
Post a Comment for "Craps In Python"