[Tutor] Crazy craps problem
Andreas Perstinger
andreas.perstinger at gmx.net
Sun Oct 9 08:55:39 CEST 2011
On 2011-10-09 08:25, col speed wrote:
> Thanks for your prompt reply! Here's the whole thing:
>
> import random
>
> message = """Welcome to craps!!!! Place your bet
> and roll the dice.
> 7 or 11 wins.
> 2, 3 or 12 loses.
> Others are "point"."""
> player = "Your"
> dice = range(1, 7)
> stake = 100
> bet = 5
> winmsg = "You have won!You have ${0} left.".format(stake)
> losemsg = "You have lost! You have ${0} left.".format(stake)
> players = ["Your", "My"]
>
> def win(num):
> if num in [7,11]:
> return "win"
> elif num in [2,3,12]:
> return "lose"
> else:
> return "point"
>
> def changePlayer(player):
> if player == "Your":
> return "My"
> else:
> return "Your"
>
> def point(num):
> while True:
> raw_input("Roll")
> uno, dos = random.choice(dice), random.choice(dice)
> three = uno+dos
> print "{0} + {1} = {2}".format(uno, dos, three)
> print "Point is {0}. You scored {1}.".format(num, three)
> if three == num:
> return "win"
> if three == 7:
> return "lose"
> else:
> print "Try again."
>
> print message
> while stake:
> print "{0} throw! You have ${1}. How much do you bet?".format(player,
> stake)
> bet = int(raw_input("$"))
> stake -= bet
> one, two = random.choice(dice), random.choice(dice)
> print "{0} + {1} = {2}".format(one, two, one+two)
> if win(one+two) == "win":
> stake += bet*2
> print winmsg
> elif win(one+two) == "lose":
>
> print losemsg
> else:
> if point(one+two) == "win":
Here you go into the function "point" the first time. Inside the
function you are in an infinite while-loop where you only exit if the
sum is either 7 ("lose") or equal the given parameter ("win"). Then you
compare the return value. In the case of "lose" you continue to the next
elif-statement:
> stake += bet*2
> print winmsg
> elif point(one+two) == "lose":
Now you go into the function "point" a *second* time, in other words you
have to throw another 7 to leave the function with the return value
"lose". But just now you will print out the message for loosing the game:
> print losemsg
> player = changePlayer(player)
What you probably want is to go into "point" only once, save the result
value and check if it's "win" or "lose".
HTH,
Andreas
More information about the Tutor
mailing list