From 659fbc140e6a201c02c36a0dbd5e096a18e2b735 Mon Sep 17 00:00:00 2001 From: siddharth A Date: Mon, 21 Oct 2024 08:43:13 +0530 Subject: [PATCH] Improvement in number_guesing_game --- number_guessing_game.py | 59 +++++++++++++++++++++++++++++++---------- 1 file changed, 45 insertions(+), 14 deletions(-) diff --git a/number_guessing_game.py b/number_guessing_game.py index 09f85b109..6086946a0 100644 --- a/number_guessing_game.py +++ b/number_guessing_game.py @@ -1,34 +1,65 @@ import random def number_guessing_game(): + #difficulty level + print("\nšŸŽÆ Welcome to the Number Guessing Game!") + print("Choose a difficulty level:") + print("1. Easy (12 attempts)\n2. Medium (8 attempts)\n3. Hard (5 attempts)") + + while True: + difficulty = input("Select difficulty (1/2/3): ").strip() + if difficulty == '1': + max_attempts = 12 + break + elif difficulty == '2': + max_attempts = 8 + break + elif difficulty == '3': + max_attempts = 5 + break + else: + print("āš ļø Invalid choice. Please select 1, 2, or 3.") + + # Initialize game variables secret_number = random.randint(1, 100) guesses = 0 + low, high = 1, 100 - print("Welcome to the Number Guessing Game!") - print("I'm thinking of a number between 1 and 100.") - - while True: + print(f"\nI'm thinking of a number between 1 and 100. You have {max_attempts} attempts to guess it!") + + while guesses < max_attempts: try: - guess = int(input("Enter your guess: ")) + guess = int(input(f"Attempt {guesses + 1}/{max_attempts}: Enter your guess: ")) except ValueError: - print("Please enter a valid number.") + print("āš ļø Invalid input! Please enter a valid number.") continue guesses += 1 if guess == secret_number: - print(f"Congratulations! You've guessed the number in {guesses} attempts.") + print(f"šŸŽ‰ Congratulations! You guessed the number in {guesses} attempts.") break elif guess < secret_number: - print("Too low!") + print("ā¬†ļø Too low!") + low = max(low, guess + 1) else: - print("Too high!") + print("ā¬‡ļø Too high!") + high = min(high, guess - 1) + + # Provide a hint every 3rd incorrect guess + if guesses % 3 == 0 and guesses < max_attempts: + print(f"šŸ’” Hint: The number is between {low} and {high}.") + + # If the player runs out of attempts + if guesses == max_attempts and guess != secret_number: + print(f"āŒ You're out of attempts! The correct number was {secret_number}.") - if guesses % 3 == 0: - if guess < secret_number: - print("Hint: The number is in the upper half of the remaining range.") - else: - print("Hint: The number is in the lower half of the remaining range.") + # Play again option + replay = input("\nDo you want to play again? (yes/no): ").strip().lower() + if replay == 'yes': + number_guessing_game() + else: + print("šŸ‘‹ Thanks for playing! Goodbye.") if __name__ == "__main__": number_guessing_game()