import random # Check that users have entered a valid # option based on a list def string_checker(question, valid_ans=("yes", "no")): while True: error = f"Enter a valid option from {valid_ans}" user_response = input(question).lower() for item in valid_ans: # check if the user response is a valid answer if item == user_response: return item elif user_response == item[0]: return item print(error) print() def instructions(): print(''' **** Instructions **** To begin, choose the number of rounds (or press for infinite mode). Then play against the computer, You enter R (rock), P (paper) or S (scissors), The rules are: Paper beats rock Rock beats scissors Scissors beats paper Press xxx to end the game at any time ''' ) # compare the comp selection v the user input # result - win, lose or tie def rps_compare(user, comp): if user == comp: result = "tie" elif user == "paper" and comp == "rock": result = "win" elif user == "rock" and comp == "scissors": result = "win" elif user == "scissors" and comp == "paper": result = "win" else: result = "lose" return result # checks the input is an integer def int_check(question): while True: error = "Enter an integer more than 1" to_check = input(question) if to_check == "": return "infinite" try: response = int(to_check) # check the number is more than 1 if response >= 1: return response else: print(error) except ValueError: print(error) # Main routine # game variables mode = "regular" rounds_played = 0 rps_list = ["rock", "paper", "scissors", "xxx"] print() print(" *** Rock / Paper / Scissors Game *** ") print() # instructions want_instructions = string_checker("Do you want to see the instructions? ") if want_instructions == "yes": instructions() num_rounds = int_check("Enter the number of rounds or press enter for unlimited ") # game loop starts here while rounds_played < num_rounds: # infinite mode if mode == "infinite": rounds_heading = f"\n*** Round {rounds_played + 1} (Infinite Mode) ***" else: rounds_heading = f"\n*** Round {rounds_played + 1} of {num_rounds} ***" print(rounds_heading) user_choice = string_checker("Choose: ", rps_list) print("You selected: ", user_choice) if user_choice == "xxx": break # Random computer choice comp_choice = random.choice(rps_list[:-1]) print(comp_choice) result = rps_compare(user_choice, comp_choice) print(f"{user_choice} vs {comp_choice}, {result}") rounds_played += 1 # infinite mode - increase number of rounds if num_rounds == "infinite": num_rounds += 1 print("The program has ended")