# program to play rock, paper scissors # ECS 10, May 8, 2009 import random # function to translate number into rock, paper, scissors, ??? def what(pick): if pick == 0: return "rock" elif pick == 1: return "paper" elif pick == 2: return "scissors" # should never get here, so warn if you do return "??? (%d)" % pick # function to read and vet user selection # returns: 0 if rock # 1 if paper # 2 if scissors # 3 to end game # NOTE: caller depends on these values def getuser(): # loop until we get good input while True: try: # get the input and check the type here v = input("Enter 0 (rock), 1 (paper), 2 (scissors), 3 (quit): ") v += 0; except EOFError: # user wants to quit, so help her v = 3 # oops! let error check below do the work # so set v to something illegal (not 0-3) except (SyntaxError, NameError, TypeError): v = -1 # now check the value we read/were given if 0 <= v and v <= 3: break # this is bad, so say so print "You have to enter a 0, 1, 2, or 3 only" # tell the user what she chose and return it if v != 3: print "You pick", what(v) return v # function to generate computer selection pseudo-randomly # returns: 0 if rock # 1 if paper # 2 if scissors # NOTE: caller depends on these values def getcomp(): pick = random.randrange(0, 3) print "Computer picks", what(pick) return pick # function to determine who wins # parameters: user: user's selection # computer's selection # NOTE: 0 = rock, 1 = paper, 2 = scissors # returns: 0 if user won # 1 if computer won # 2 if tie # NOTE: caller depends on these values def whowins(user, comp): if user == comp: win = 2 elif (user, comp) == (1, 0) or (user, comp) == (2, 1) or (user, comp) == (0, 2): win = 0 else: win = 1 return win # pulling it all together # calls: getuser(), getcomp(), whowins() def main(): # initialize scores score = [ 0, 0, 0 ] # now we play while True: # get the user's choice userchoice = getuser(); if (userchoice == 3): break # get the computer's choice compchoice = getcomp(); # figure out who won winner = whowins(userchoice, compchoice) # announce it to the world! if winner == 0: print "You win" elif winner == 1: print "Computer wins" elif winner == 2: print "Tie" else: print "*** INTERNAL ERROR *** winner is", winner break # track the new score score[winner] += 1; print "You won", score[0], "games, the computer won", score[1], print "games, and", score[2], "games were tied" main()