220k views
2 votes
Using a random number generator, pick a number between 1-100 (don’t worry about writing code for this - it has been provided later in this document). The player is then asked to try and guess this number. They are given a limited number of attempts to try and guess the number correctly. We allow the player to decide how many attempts they want at the start of the game.

Once the player starts guessing, for each incorrect guess, the player is informed whether they must "Guess higher" or "Guess lower" the next time. You must also display the number of remaining attempts after each incorrect guess. The game ends either when the player guesses the correct number, or when they run out of attempts.

a picture showing a sample run of how we expect the game to work here.

User Khalito
by
8.2k points

1 Answer

5 votes

import random

def play_game():

# Generate a random number between 1 and 100

secret_number = random.randint(1, 100)

# Get the maximum number of attempts from the player

max_attempts = int(input("Enter the maximum number of attempts: "))

# Start the game

attempts = 0

while attempts < max_attempts:

attempts += 1

guess = int(input("Enter your guess (1-100): "))

# Check if the guess is correct

if guess == secret_number:

print("Congratulations! You guessed the correct number.")

return

# Provide hints for the next guess

if guess < secret_number:

print("Guess higher.")

else:

print("Guess lower.")

# Display the number of remaining attempts

remaining_attempts = max_attempts - attempts

print(f"You have {remaining_attempts} attempt(s) remaining.")

# The player ran out of attempts

print("Game over. You did not guess the correct number.")

print(f"The secret number was: {secret_number}")

# Start the game

play_game()

User Ripa Saha
by
7.9k points

No related questions found