patternpythonMinor
Simple Craps game
Viewed 0 times
crapssimplegame
Problem
I'm trying to make my code smaller and less verbose.
The
The code is running a game of craps where on the first roll if I get a 7 or 11 I win, or if I get a 2,3,12 I lose. Any other number I keep rolling till I either get what I rolled the first time or I roll a 7. A return value of 1 means I won and 0 means I lost.
The
pass in the if statement are there because I need to check specifics on the dice roll. The code is running a game of craps where on the first roll if I get a 7 or 11 I win, or if I get a 2,3,12 I lose. Any other number I keep rolling till I either get what I rolled the first time or I roll a 7. A return value of 1 means I won and 0 means I lost.
def craps():
from random import randint
dice = 0
loop = 0
while loop < 1:
d1 = randint(1,6)
d2 = randint(1,6)
roll = d1 + d2
dice += 1
print(d1, d2)
if dice == 1:
first=roll
if roll in {2,3,12}:
loop += 1
return 0
elif roll in {7,11}:
loop += 1
return 1
else:
pass
elif dice != 1:
if first==roll:
loop += 1
return 1
elif roll==7:
loop += 1
return 0
else:
pass
else:
passSolution
-
-
Don't test for special cases inside the loop. A first roll is special, so roll it before the loop begins (this also eliminates a
-
Factor dice rolling into a function.
That said,
loop is totally useless. The loop doesn't have a chance to test it: as soon as it becomes 1, the function returns.-
Don't test for special cases inside the loop. A first roll is special, so roll it before the loop begins (this also eliminates a
dice variable).-
Factor dice rolling into a function.
That said,
from random import randint
def do_roll():
return randint(1, 6) + randint(1, 6)
def craps():
first = do_roll()
if first in {2,3,12}:
return 0
elif first in {7,11}:
return 1
while True:
roll = do_roll()
if roll == first:
return 1
elif roll == 7:
return 0Code Snippets
from random import randint
def do_roll():
return randint(1, 6) + randint(1, 6)
def craps():
first = do_roll()
if first in {2,3,12}:
return 0
elif first in {7,11}:
return 1
while True:
roll = do_roll()
if roll == first:
return 1
elif roll == 7:
return 0Context
StackExchange Code Review Q#145875, answer score: 5
Revisions (0)
No revisions yet.