# Help with Python Game

This topic is 3596 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi Everyone! I am trying to create a easy game called doubles using Python. Ive got some of the code but i'm stuck and can't figure it out. Here are the rules of the game: 1. You start by throwing two dice, and your score is the sum of the two numbers. If the two dice show the same number, this is a "Double" and your score is doubled. At this point, you can stop and let the computer try to beat your score. Or, you can throw one last die. 2. If you have a Double and you throw the third die, then, if the third die is the same number again, you have thrown a Triple'' and you win --- the game ends immediately. Otherwise, you subtract the score of the third die from your total score --- this is your penalty. For example, if you threw 5 and 5 and then chose to throw the third die and it was 4, then your score is ((5 + 5) * 2) = 20 - 4 = 16 3. If you did not throw a Double and you choose to throw the third die, then your total score is the sum of the first two dice plus half the score of the third die (drop any fraction). For example, if you threw 6 and 4 and then threw a 5, your score is (6 + 4) + (5/2) == 10 + 2 == 12. 4. If you did not win by throwing a Triple, then the computer plays its turn and tries to beat your score. The computer plays under the same rules you did. 5. At the end of the game, if neither player threw a Triple, then the player with the higher score wins. If it is a tie, then you win. Alright this is what I have so far.
import random
raw_input("\nWelcome to Doubles! You play first, press Enter to roll dice")
d1 = random.randrange(1,7)
d2 = random.randrange(1,7)
d3 = random.randrange(1,7)
t = d1+d2
t2 = t*2
print "\nYou rolled", d1 ,"and", d2
if d1 == d2:
print "Your total score is", t2 ,"cause you rolled Doubles!"
else:
print "Your total score is", t

a = raw_input("\nDo you want to throw the third die (y or n)?: ")

if a == "y":
if d3==(d1,d2):
print "\nYour third die is", d3
print "You threw a Triple!"
print "\nCongratulations --- you WON!"
raw_input("Press Enter to Finish")
else:
print "\nYour third die is", d3
raw_input("\nYour turn is over now. Press Enter to allow the computer to roll his turn: ")
else:
raw_input("\nYour turn is over now. Press Enter to allow the computer to roll his turn: ")


Sample behaviors of the program, Doubles.py: >python Doubles.py Welcome to Doubles! You play first: You rolled 6 and 3 Your score is 9 Do you want to throw the third die (y or n)?: y Your third die is 5 Your total score is 11 The computer plays next: The computer rolled 2 and 2 A Double! Its score is 8 The computer will throw a third die. It is a 3 The computer's score is reduced. The computer's total score is 5 Congratulations --- you won! Press Enter to finish >python Doubles.py Welcome to Doubles! You play first: You rolled 4 and 2 Your score is 6 Do you want to throw the third die (y or n)?: y Your third die is 4 Your total score is 8 The computer plays next: The computer rolled 5 and 5 A Double! Its score is 20 The computer's total score is 20 Sorry --- the computer won. Press Enter to finish >python Doubles.py Welcome to Doubles! You play first: You rolled 1 and 1 A Double! Your score is 4 Do you want to throw the third die (y or n)?: y Your third die is 1 You threw a Triple! Congratulations --- you won! Press Enter to finish The code above the samples works like its designed to up tell "if a == "y": but im not sure how to make it right after that. Placement of if and else statements have my brain going crazy. If you guys could help me finish this I would appreciate it alot. Also consider im pretty new to the language so please dont throw hard stuff at me. Thanks Everyone Andy

##### Share on other sites
if d3==(d1,d2):

This doesn't check if d3 is equal to both d1 and d2. When you write (d1,d2) you create a tuple (an immutable sequence) of those two values (see 'Sequence types' in your manual).

To check if two seperate comparisons are both true...

if d3 == d1 and d3 == d2:

But since you're doing a three-way compare this is probably clearest...

if d1 == d2 == d3:

Finally you could use tuples, though it is not quite as clear...

if (d1,d2) == (d3,d3):

##### Share on other sites
1) Draw out the process logically, based on the algorithm you gave. I'm going to take some of the sentences of your description, and arrange them indented in a way that looks like Python code:

You start by throwing two dice, and your score is the sum of the two numbers.If the two dice show the same number,  this is a "Double"  and your score is doubled.If you have a Double and you throw the third die, then,   if the third die is the same number again,    you have thrown a Triple' and    you win --- the game ends immediately.  Otherwise,    you subtract the score of the third die from your total scoreIf you did not throw a Double and you choose to throw the third die, then  your total score is the sum of the first two dice plus half the score of the third die (drop any fraction).If you did not win by throwing a Triple, then  the computer plays its turn and tries to beat your score.  The computer plays under the same rules you did.At the end of the game, if neither player threw a Triple, then  the player with the higher score wins. If it is a tie, then  you win.

Now, let's rearrange that to simplify. Clearly, checking whether the user wants to throw the third die is important: we check that whether or not the user has a double, so it makes sense to pull that out and check it in an if statement first. Meanwhile, we can collapse the "tie" condition into the "higher score" condition, and start writing things with mathematical expressions, and taking out irrelevant details. Notice below that I am assuming the process will stop immediately if we say "you win" or "the computer wins", which allows us to simplify some of the if/else logic.

You start by throwing two dice x, y, and your score is x + y.If x == y,  your score is 2 * your score.If you throw the third die z,  If x == y,    if z == x,      you win.    your score is your score - z.  Otherwise,    your score is your score + z / 2.# since "you win" ends our process implicitly, we assume at this point that# the user did not throw a Triple.The computer throws a, b, and the computer's score is a + b.If a == b,  the computer's score is 2 * the computer's score.# Decide if the computer will throw the third die.If the computer throws the third die c,  if a == b,    if c == a,      the computer wins.    the computer's score is the computer's score - c.  Otherwise,    the computer's score is the computer's score + c / 2.# Neither player has a Triple at this point.If your score >= the computer's score:  You win.The computer wins.

So, now we have to figure out the computer's strategy. It has one decision to make: whether or not to roll the third die. This is easy to decide: if the computer has beaten the player's score, it should not try; otherwise, it has nothing to lose.

You start by throwing two dice x, y, and your score is x + y.If x == y,  your score is 2 * your score.If you throw the third die z,  If x == y,    if z == x,      you win.    your score is your score - z.  Otherwise,    your score is your score + z / 2.The computer throws a, b, and the computer's score is a + b.If a == b,  the computer's score is 2 * the computer's score.If the computer's score > the player's score:  The computer wins. # It will not throw again.Throw the third die c.  if a == b,    if c == a,      the computer wins.    You win. # The computer's score went down, which can't possibly help.  Otherwise,    the computer's score is the computer's score + c / 2.If your score >= the computer's score:  You win.The computer wins.

Next, let's try to pull out some common logic from here. We'll end up losing the value of some of our observations (such as the shortcut "you win" if the computer has to try for a triple and fails), but the code will be shorter overall.

The obvious thing that gets repeated is the evaluation of score. The two players make their decisions differently, but they play by the same rules.

We need a way to accept either two or three dice for the purpose of calculating a score. We'll make a function which takes those values in. In Python, we can deal with varying numbers of arguments in a few different ways. I'll use the "*args" approach here (look it up in your reference). Also, we need a way to indicate the "automatic win" condition. The simple approach is to simply return a score that is higher than could be rolled normally. The only thing we have to check, in that case, is that the computer should not bother playing if the player gets a Triple. :)

# The highest "normal" score is (6 + 6) * 2.AUTO_WIN = 25def score(*dice):  # We assume 'dice' will be a list of either two or three dice values.  result = dice[0] + dice[1]  # Apply double/triple logic.  if dice[0] == dice[1]:    result *= 2  if len(dice) == 3:    if dice[0] == dice[1]:      if dice[0] == dice[2]: # All three match.        result = AUTO_WIN      else:        result -= dice[2]    else:      result += dice[2] / 2    return result

Now we can fold that in, assuming we have a "score" function that we can call whenever, instead of keeping a running total.

You start by throwing two dice x, y, and your score is score(x, y).If you throw the third die z,  your score is score(x, y, z).If your score is AUTO_WIN:  You win. # Don't let the computer try; it can't win.The computer throws a, b, and the computer's score is score(a, b).If the computer's score > the player's score:  The computer wins. # It will not throw again.Throw the third die c. The computer's score is score(a, b, c).If the computer's score > the player's score:  The computer wins. # This automatically covers the case of throwing a triple.You win. # The computer still couldn't beat you.

And then we write that up as a function:

def play():  """Play the game. Return whether or not the player won.  (The code that calls play() can interpret the result and print a message)"""  x = roll_die()  y = roll_die()  your_score = score(x, y)  if user_wants_to_throw_third_die():    your_score = score(x, y, roll_die()) # We don't really need the 'z' variable,    # since past this point, we don't need to "remember" the die totals.  if your_score == AUTO_WIN:    return True  a = roll_die()  b = roll_die()  if score(a, b) > your_score: # Again, we don't really need to "remember" computer score.    return False  if score(a, b, roll_die()) > your_score:    return False  return True

So actually, you need very little nesting. :)

##### Share on other sites
Ok ive gotten a little farther in my code thanks for the replys. But there is something that I dont think you understood about the rules. Going first and second in this game has its advantages. If the first person throws a triple the game is over without the 2nd person having a chance to go. The second person has the advantage of knowing if he/she should throw the 3rd die. So in the code below how am I supposed to exit the program if the first person throws the triple. Right now if someone throws a triple it still gives the computer a chance to throw which I dont want.

import randomraw_input("\nWelcome to Doubles! You play first, press Enter to roll dice")d1 = random.randrange(1,7)d2 = random.randrange(1,7)d3 = random.randrange(1,7)t = d1+d2t2 = t*2print "\nYou rolled", d1 ,"and", d2if d1==d2:    print "Your total score is", t2 ,"cause you rolled Doubles!"else:    print "Your total score is", ta = raw_input("\nDo you want to throw the third die (y or n)?: ")if a == "y":    if d3 == d1 == d2:        print "\nYour third die is", d3        print "You threw a Triple!"        print "\nCongratulations --- you WON!"        raw_input("Press Enter to Finish")    if d1 == d2 != d3:        print "\nYour third die is", d3        print "Your total is", t2-d3    if d1 != d2:        print "\nYour third die is", d3        print "Your total is", t+(d3/2)else:    raw_input("\nYour turn is over now. Press Enter to allow the computer to roll his turn: ")

Thanks Everyone
Andy

Thanks
Andrew

##### Share on other sites
You should at least learn how to define functions. It is not a difficult concept - personally, I'm not sure why most tutorials teach flow control first before functions. Currently, all of your code is at the "top level" (or module level) of your script, so the program basically runs from top to bottom and there's not much you can do about it. If all or part of your code was within a function, you can use return statements to exit that function at any point. Example:
def my_function():    print "Hello there!"    return    print "This will NEVER be printed!"my_function()

Output:
Hello there!

Study Zahlman's post. Maybe it was too much to swallow all at once but it is good stuff.

There is one way to terminate a "top level" script. I only mention it for completeness, though - don't do it until you are advanced enough to know why I'm saying not to do it :). Raising an exception will cause a script to abort. sys.exit() does this by raising a SystemExit exception. It's considered bad practice to do without a good reason.

##### Share on other sites

This topic is 3596 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628704
• Total Posts
2984306

• 23
• 10
• 9
• 13
• 13