简体   繁体   中英

Comparing the Output of Functions Correctly

I've written the base of a Rock-Scissor-Paper game in Python 2.7, as follows:

  1 #!/bin/py
  2 #Python 2.7.6
  3 from random import choice
  4 
  5 moves = ["r", "p", "s"] # Possible moves  
  6 winning_combos = {("r", "s"), ("s", "p"), ("p", "r")} # Winning   outcomes 
  7 
  8 def human():
  9         print
 10         print "R: Rock    P: Paper    S: Scissor"
 11         print
 12         human_move = raw_input("Enter your choice: ").lower()
 13         return human_move
 14 ()
 15 
 16 def bot():
 17         bot_move = choice(moves)
 18         return bot_move
 19 ()
 20 
 21 while True:
 22         human(), bot()
 23         if human() == bot():
 24                 print "Grr... a tie!"
 25         elif (human(), bot()) in winning_combos:
 26                 print "Woo-hoo! You win this round, human"
 27         else:
 28                 print "Bwahahaha! The almighty bot wins!"

.

My question is how, if at all, can I compare the results of the human() and bot() functions as I am trying to do in line 25? When this program runs as is, I am prompted to enter input twice before the comparison is done.

I can write this program in a different way to produce an acceptable result, so I am not looking to rewrite the program. I'm specifically, although perhaps not effectively, asking about how to tweak this program as is (I'm fairly new to Python), as well as understand what I have done incorrectly. Thanks!

Your problem is you're calling human and bot each time you need to access the value. Store the results in variables, something like this:

while True:
        human_move, bot_move = human(), bot()
        if human_move == bot_move:
                print "Grr... a tie!"
        elif (human_move, bot_move) in winning_combos:
                print "Woo-hoo! You win this round, human"
        else:
                print "Bwahahaha! The almighty bot wins!"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM