import turtle import random # Number to be guessed: 1 to UPPER_RANGE UPPER_RANGE = 12 PLAYER_1_COLOR = 'red' PLAYER_2_COLOR = 'green' WINNING_SCORE = 2 def get_guess(player): """ Returns a valid user input guess number from 1 to WINNING_SCORE Args: player: the player number to show in the prompt to get output. Returns: int: a int from 1 to WINNING_SCORE """ while True: try: guess_str = input(f"Player #{player}: please make a guess from 1 to {UPPER_RANGE}: ") guess = int(guess_str) if 1 <= guess <= UPPER_RANGE: return guess else: print(f" Invalid Guess.Please enter a number between 1 and {UPPER_RANGE}.") except (ValueError, TypeError): print(" Invalid Input. Please enter a valid number.") # Set up the turtle screen screen = turtle.Screen() screen.setup(width=400, height=200) screen.title(f"Guess Game: Player 1 ({PLAYER_1_COLOR}), Player 2 ({PLAYER_2_COLOR})") # t1: turtle for player #1 t1 = turtle.Turtle() t1.shape("turtle") t1.color(PLAYER_1_COLOR) t1.penup() t1.goto(-150, 30) t1.pendown() # t2: turtle for player #2 t2 = turtle.Turtle() t2.shape("turtle") t2.color(PLAYER_2_COLOR) t2.penup() t2.goto(-150, -30) t2.pendown() # initial scores for the two players. player_1_score = 0 player_2_score = 0 # get the first random number from 1 to UPPER_RANGE correct_answer = random.randint(1, UPPER_RANGE) # play the game. while True: # every iteration includes a guess from player #1 and a guess # guess from player #2, until one player wins. # get a guess from player 1 and process it. guess = get_guess(1) # process the guess. if guess == correct_answer: # update player #1 score. player_1_score += 1 # move player #1 turtle. t1.forward(300 // WINNING_SCORE) if player_1_score >= WINNING_SCORE: # player #1 wins. print(f"Correct. Player 1 wins. Score: {player_1_score}") print(f" Player 2 loses; score: {player_2_score}") break else: # no winner yet. Continue to play the game. print(f" Correct. Player 1 score: {player_1_score}") correct_answer = random.randint(1, UPPER_RANGE) else: # Provide feedback. print(f" Incorrect. Your guess is {'smaller' if guess < correct_answer else 'larger'} then the answer.") # get a guess from player 2 and process it. guess = get_guess(2) # process the guess. if guess == correct_answer: # update player #2 score. player_2_score += 1 # move player #2 turtle. t2.forward(300 // WINNING_SCORE) if player_2_score >= WINNING_SCORE: # player #2 wins. print(f"Correct. Player 2 wins. Score: {player_2_score}") print(f" Player 1 lose; score: {player_1_score}") break else: # no winner yet. Continue to play the game. print(f" Correct. Player 2 score: {player_2_score}") correct_answer = random.randint(1, UPPER_RANGE) else: # Provide feedback. print(f" Incorrect. Your guess is {'smaller' if guess < correct_answer else 'larger'} then the answer.") # Keep the window open until closed manually screen.mainloop()