# program to play rock, paper scissors # # Matt Bishop, MHI 289I, Fall 2022 # # final version # import random # list of objects things = ( "rock", "paper", "scissors" ) # list of legal commands cmdlist = ( "rock", "paper", "scissors", "quit" ) # list of winning pairs (first dominates second) winlist = ( ("rock", "scissors"), ("paper", "rock"), ("scissors", "paper") ) # scores score = { "user" : 0, "computer" : 0, "tie" : 0 } # get user input def getuser(): while True: # get string input, and look for problems try: n = input("Human: enter rock, paper, scissors, quit: ") except (EOFError, KeyboardInterrupt): n = "quit" except Exception as msg: print("Unknown exception:", msg, "-- quitting") n = "quit" break # it's a good string; compain if not a command, or return it if n not in cmdlist: print("Bad input; try again") else: break return n # function to generate computer selection pseudo-randomly # returns: "rock", "paper", "scissors" def getcomp(): pick = random.choice(things) print("Computer picks", pick) return pick # function to determine who wins # parameters: user: user's selection # computer's selection # returns: "user" if user won # "computer" if computer won # "tie" if tie def whowins(user, comp): if user == comp: win = "tie" elif (user, comp) in winlist: win = "user" else: win = "computer" return win # pulling it all together # calls: getuser(), getcomp(), whowins() def main(): # initialize the pseudorandom number generator random.seed() # now we play while True: # get the user's choice userchoice = getuser(); if userchoice == "quit": break # get the computer's choice compchoice = getcomp(); # figure out who won winner = whowins(userchoice, compchoice) # announce it to the world! if winner == "user": print("You win") elif winner == "computer": print("Computer wins") elif winner == "tie": print("Tie") else: print("*** INTERNAL ERROR *** winner is", winner) break # track the new score score[winner] += 1; # # announce the final score, with good grammar # print("You won", end='') if score["user"] == 1: print("1 game, the computer won",end=' ') else: print(score["user"], "games, the computer won", end=' ') if score["computer"] == 1: print("1 game, and you two tied", end=' ') else: print(score["computer"], "games, and you two tied", end=' ') if score["tie"] == 1: print("1 game.") else: print(score["tie"], "games.") main()