Day 25: Number Guessing Game

Objective

Create an interactive Number Guessing Game where the computer generates a random number, and the user tries to guess it. The program will provide feedback on whether the user’s guess is too high, too low, or correct.

For example:

  • Computer: Generates the number 42.
  • User Input: 50 → Output: “Too high!”
  • User Input: 30 → Output: “Too low!”
  • User Input: 42 → Output: “Correct! You guessed it!”

Why This Challenge Is Important

This challenge reinforces concepts such as:

  • Random number generation.
  • Using loops for repeated interactions.
  • Handling conditional logic to provide feedback.
  • Enhancing the user experience by adding features like attempt tracking.

Building this game is also a great introduction to interactive programming and can easily be extended with additional features to make it more dynamic.


Steps to Solve

1. Understand the Problem

  • The program generates a random number within a specified range (e.g., 1 to 100).
  • The user repeatedly guesses the number until they get it right.
  • After each guess, the program provides feedback:
    • If the guess is too high, display: “Too high!”
    • If the guess is too low, display: “Too low!”
    • If the guess is correct, display: “You guessed it!”

2. Plan Your Solution

  1. Generate a random number using a built-in library.
  2. Prompt the user to guess the number.
  3. Use a loop to check if the guess is correct.
  4. Provide feedback after each guess.
  5. Count the number of attempts and display it when the game ends.

3. Enhancements to Consider

  • Let the user choose the difficulty level (e.g., range 1–50 for easy, 1–500 for hard).
  • Allow the user to quit the game by entering a special command (e.g., “exit”).
  • Add a feature to track the user’s best score (i.e., least attempts).

Code Examples

Python Example

import random

print("Welcome to the Number Guessing Game!")
print("I have selected a number between 1 and 100. Can you guess what it is?")

# Generate a random number
target_number = random.randint(1, 100)
attempts = 0

while True:
    try:
        # Get the user's guess
        guess = input("Enter your guess (or type 'exit' to quit): ")

        if guess.lower() == "exit":
            print("Thanks for playing! Goodbye!")
            break

        guess = int(guess)
        attempts += 1

        # Check the guess
        if guess < target_number:
            print("Too low!")
        elif guess > target_number:
            print("Too high!")
        else:
            print(f"Correct! You guessed the number in {attempts} attempts!")
            break
    except ValueError:
        print("Please enter a valid number.")

Java Example

import java.util.Scanner;
import java.util.Random;

public class NumberGuessingGame {
    public static void main(String[] args) {
        Random random = new Random();
        Scanner scanner = new Scanner(System.in);

        System.out.println("Welcome to the Number Guessing Game!");
        System.out.println("I have selected a number between 1 and 100. Can you guess what it is?");

        // Generate a random number
        int targetNumber = random.nextInt(100) + 1;
        int attempts = 0;

        while (true) {
            System.out.print("Enter your guess (or type -1 to quit): ");
            int guess = scanner.nextInt();

            if (guess == -1) {
                System.out.println("Thanks for playing! Goodbye!");
                break;
            }

            attempts++;

            // Check the guess
            if (guess < targetNumber) {
                System.out.println("Too low!");
            } else if (guess > targetNumber) {
                System.out.println("Too high!");
            } else {
                System.out.println("Correct! You guessed the number in " + attempts + " attempts!");
                break;
            }
        }
    }
}

JavaScript Example

console.log("Welcome to the Number Guessing Game!");
console.log("I have selected a number between 1 and 100. Can you guess what it is?");

// Generate a random number
const targetNumber = Math.floor(Math.random() * 100) + 1;
let attempts = 0;

while (true) {
    const input = prompt("Enter your guess (or type 'exit' to quit):");

    if (input.toLowerCase() === "exit") {
        console.log("Thanks for playing! Goodbye!");
        break;
    }

    const guess = parseInt(input);
    if (isNaN(guess)) {
        console.log("Please enter a valid number.");
        continue;
    }

    attempts++;

    // Check the guess
    if (guess < targetNumber) {
        console.log("Too low!");
    } else if (guess > targetNumber) {
        console.log("Too high!");
    } else {
        console.log(`Correct! You guessed the number in ${attempts} attempts!`);
        break;
    }
}

Edge Cases to Consider

  1. Non-Numeric Input: Handle invalid input gracefully (e.g., letters or special characters).
  2. Negative Numbers: Ensure guesses are within the valid range.
  3. Large Range: Adjust feedback for larger ranges (e.g., “Far too high!” or “Very close!”).
  4. Repeated Guesses: Track and notify if the user repeatedly guesses the same number.

Extensions to Explore

  1. Add Levels: Allow the user to choose difficulty (e.g., easy: 1–50, hard: 1–1000).
  2. Hints: Add hints like “The number is even/odd” after a certain number of attempts.
  3. Timer: Track how long it takes the user to guess the correct number.
  4. Multiplayer Mode: Let two players take turns guessing, and declare a winner.

What You’ve Learned

  • How to use random number generation.
  • Implementing loops for repeated interactions.
  • Providing user feedback with conditional statements.
  • Tracking attempts for improved gameplay.

Next Steps

In Day 26: Password Generator, you’ll create a program that generates random, secure passwords based on user-defined criteria.