๐ฏ Project 01: Number Guessing Game
Difficulty: ๐ข Beginner
Description
Build a command-line number guessing game where the computer picks a random number and the player tries to guess it. The game should provide hints like "Too high!" or "Too low!" after each guess.
Requirements
- Generate a random number between 1 and 100
- Ask the user for guesses until they get the correct number
- After each guess, tell the user if their guess is too high, too low, or correct
- Track the number of attempts and display it at the end
- Handle invalid input gracefully (non-numeric input)
- Ask the player if they want to play again after winning
Concepts You'll Practice
whileloopsif/elif/elseconditionalsrandommoduletry/excepterror handlinginput()function- f-strings
Example Output
๐ฏ Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100...
Enter your guess: 50
๐ Too low! Try again.
Enter your guess: 75
๐ Too high! Try again.
Enter your guess: 63
๐ Congratulations! You guessed it in 3 attempts!
Play again? (yes/no): no
Thanks for playing! Goodbye! ๐How to Run
cd projects/01_number_guessing_game
python solution.pyBonus Challenges
- Add difficulty levels (Easy: 1-50, Medium: 1-100, Hard: 1-500)
- Add a scoreboard that tracks best scores across games
- Set a maximum number of attempts based on difficulty
Solution
"""
================================================================================
Project 01: Number Guessing Game
Difficulty: ๐ข Beginner
================================================================================
A command-line number guessing game where the computer picks a random number
and the player tries to guess it with hints provided after each attempt.
Concepts Used:
- while loops
- if/elif/else conditionals
- random module
- try/except error handling
- input() function
- f-strings
================================================================================
"""
import random
# -----------------------------------------------------------------------------
# Game Configuration
# -----------------------------------------------------------------------------
DIFFICULTIES = {
"easy": {"min": 1, "max": 50, "attempts": 10},
"medium": {"min": 1, "max": 100, "attempts": 7},
"hard": {"min": 1, "max": 500, "attempts": 10},
}
# -----------------------------------------------------------------------------
# Helper Functions
# -----------------------------------------------------------------------------
def display_welcome():
"""Display the welcome banner."""
print("""
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๐ฏ NUMBER GUESSING GAME ๐ฏ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
""")
def choose_difficulty() -> dict:
"""Let the player choose a difficulty level."""
print("Choose your difficulty:")
print(" [1] ๐ข Easy (1-50, 10 attempts)")
print(" [2] ๐ก Medium (1-100, 7 attempts)")
print(" [3] ๐ด Hard (1-500, 10 attempts)")
while True:
choice = input("\nYour choice (1/2/3): ").strip()
if choice == "1":
return DIFFICULTIES["easy"]
elif choice == "2":
return DIFFICULTIES["medium"]
elif choice == "3":
return DIFFICULTIES["hard"]
else:
print("โ Invalid choice. Please enter 1, 2, or 3.")
def get_guess(min_val: int, max_val: int) -> int:
"""Get a valid integer guess from the player."""
while True:
try:
guess = int(input(f"\nEnter your guess ({min_val}-{max_val}): "))
if min_val <= guess <= max_val:
return guess
else:
print(f"โ ๏ธ Please enter a number between {min_val} and {max_val}.")
except ValueError:
print("โ ๏ธ That's not a valid number. Try again!")
def play_round():
"""Play a single round of the guessing game."""
# Setup
config = choose_difficulty()
min_val = config["min"]
max_val = config["max"]
max_attempts = config["attempts"]
secret = random.randint(min_val, max_val)
attempts = 0
print(f"\n๐ค I'm thinking of a number between {min_val} and {max_val}...")
print(f" You have {max_attempts} attempts. Good luck!\n")
# Game loop
while attempts < max_attempts:
guess = get_guess(min_val, max_val)
attempts += 1
remaining = max_attempts - attempts
if guess < secret:
print(f"๐ Too low! ({remaining} attempts remaining)")
elif guess > secret:
print(f"๐ Too high! ({remaining} attempts remaining)")
else:
print(f"\n๐ Congratulations! You guessed it in {attempts} attempt(s)!")
if attempts <= 3:
print("๐ Amazing! You're a natural!")
elif attempts <= 5:
print("๐ Well done!")
else:
print("๐
That was close!")
return True
# Out of attempts
print(f"\n๐ Game over! The number was {secret}.")
return False
def play_again() -> bool:
"""Ask the player if they want to play again."""
while True:
answer = input("\n๐ Play again? (yes/no): ").strip().lower()
if answer in ("yes", "y"):
print()
return True
elif answer in ("no", "n"):
return False
else:
print("Please enter 'yes' or 'no'.")
# -----------------------------------------------------------------------------
# Main Game Loop
# -----------------------------------------------------------------------------
def main():
"""Main entry point for the game."""
display_welcome()
wins = 0
total = 0
while True:
total += 1
if play_round():
wins += 1
print(f"\n๐ Score: {wins} wins out of {total} games")
if not play_again():
break
print(f"\n{'='*40}")
print(f" Final Score: {wins}/{total} games won")
print(f" Thanks for playing! Goodbye! ๐")
print(f"{'='*40}\n")
if __name__ == "__main__":
main()