Number Guesser

The BrainPad ecosystem is designed to excite new learners about coding and then it prepares them to transition beyond circuits; to building apps, websites, and more. This lesson will show how to build a number-guessing game using the existing experience gained from prior BrainPad lessons.

Prerequisite

Finish all BrianPad Basics with Python, C#, and JavaScript.

Intro

Step 1: Set Up the Game

  • Import the `random` module to generate a random number.
  • Generate a random number between 1 and 100 and store it in a variable as the target number. This will be the number the player needs to guess.

Python

import random

C#

// Step 1: Set Up the Game
Random random = new Random();
int targetNumber = random.Next(1, 101);

JS

// Step 1: Set Up the Game
const targetNumber = Math.floor(Math.random() * 100) + 1;

Step 2: Initialize Variables

  • Create a variable to store the player’s guess count and set it to 0.
  • Create a variable to store the maximum number of guesses allowed and set it to a reasonable number (e.g., 10).

Python

# Step 1: Set Up the Game
target_number = random.randint(1, 100)

# Step 2: Initialize Variables
guess_count = 0
max_guesses = 10

C#

// Step 1: Set Up the Game
Random random = new Random();
int targetNumber = random.Next(1, 101);

// Step 2: Initialize Variables
int guessCount = 0;
const int maxGuesses = 10;

JS

// Step 1: Set Up the Game
const targetNumber = Math.floor(Math.random() * 100) + 1;

// Step 2: Initialize Variables
let guessCount = 0;
const maxGuesses = 10;

Step 3: Start the Game Loop

  • Create a `while` loop that runs as long as the player hasn’t guessed the correct number and hasn’t used up all their guesses.

Step 4: Get Player Input

  • Inside the loop, ask the player to input their guess as an integer.
  • Increment the guess count by 1.

Python

guess = int(input("Guess the number (between 1 and 100): "))
guess_count += 1

C#

int guess = int.Parse(Console.ReadLine());
guessCount++;

JS

let guess = parseInt(readline.question("Guess the number (between 1 and 100): "));
guessCount++;

Step 5: Check the Guess

  • Compare the player’s guess with the target number.
  • If the guess is correct, print a congratulatory message and exit the loop.
  • If the guess is too high, print a message telling the player to guess lower.
  • If the guess is too low, print a message telling the player to guess higher.

Python

if guess == target_number:
        print(f"Congratulations! You guessed the number {target_number} in {guess_count} attempts!")
        break
    elif guess < target_number:
        print("Guess higher.")
    else:
        print("Guess lower.")

C#

if (guess == targetNumber)
 {
  Console.WriteLine($"Congratulations! You guessed the number {targetNumber} in {guessCount} attempts!");
  }
 else if (guess < targetNumber)
 {
        Console.WriteLine("Guess higher.");
    }
 else {
            Console.WriteLine("Guess lower.");
       }

JS

if (guess === targetNumber) {
    console.log(`Congratulations! You guessed the number ${targetNumber} in ${guessCount} attempts!`);
} else if (guess < targetNumber) {
    console.log("Guess higher.");
} else {
    console.log("Guess lower.");
}

Step 6: Handle Out-of-Guesses Condition

If the player uses up all their guesses without guessing correctly, print a message revealing the target number and inform the player that they lost.

Python

if guess_count == max_guesses:
    print(f"Sorry, you've run out of guesses. The number was {target_number}.")

C#

// Step 6: Handle Out-of-Guesses Condition
        if (guessCount == maxGuesses)
        {
            Console.WriteLine($"Sorry, you've run out of guesses. The number was {targetNumber}.");
        }

JS

// Step 6: Handle Out-of-Guesses Condition
if (guessCount === maxGuesses) {
    console.log(`Sorry, you've run out of guesses. The number was ${targetNumber}.`);
}

Step 7: Play Again (Optional)

  • Ask the player if they want to play again.
  • If they do, generate a new random number and reset the guess count. If not, exit the game.

Final Results

Python

import random
# Step 1: Set Up the Game
target_number = random.randint(1, 100)

# Step 2: Initialize Variables
guess_count = 0
max_guesses = 10

guess = int(input("Guess the number (between 1 and 100): "))
guess_count += 1

if guess == target_number:
        print(f"Congratulations! You guessed the number {target_number} in {guess_count} attempts!")
elif guess < target_number:
    print("Guess higher.")
else:
    print("Guess lower.")

if guess_count == max_guesses:
    print(f"Sorry, you've run out of guesses. The number was {target_number}.")

# Step 3: Start the Game Loop
while guess_count < max_guesses:
    # Step 4: Get Player Input
    guess = int(input("Guess the number (between 1 and 100): "))
    guess_count += 1

    # Step 5: Check the Guess
    if guess == target_number:
        print(f"Congratulations! You guessed the number {target_number} in {guess_count} attempts!")
        break
    elif guess < target_number:
        print("Guess higher.")
    else:
        print("Guess lower.")

# Step 6: Handle Out-of-Guesses Condition
if guess_count == max_guesses:
    print(f"Sorry, you've run out of guesses. The number was {target_number}.")

# Step 7: Play Again (Optional)
play_again = input("Do you want to play again? (yes/no): ").lower()
if play_again == "yes":
    target_number = random.randint(1, 100)
    guess_count = 0
    print("New game started.")
else:
    print("Thanks for playing! Goodbye.")

C#

using System;

class Program
{
    static void Main()
    {
        // Step 1: Set Up the Game
        Random random = new Random();
        int targetNumber = random.Next(1, 101);

        // Step 2: Initialize Variables
        int guessCount = 0;
        const int maxGuesses = 10;

        Console.Write("Guess the number (between 1 and 100): ");
        int guess = int.Parse(Console.ReadLine());
        guessCount++;

        if (guess == targetNumber)
        {
            Console.WriteLine($"Congratulations! You guessed the number {targetNumber} in {guessCount} attempts!");
        }
        else if (guess < targetNumber)
        {
            Console.WriteLine("Guess higher.");
        }
        else
        {
            Console.WriteLine("Guess lower.");
        }

        // Step 3: Start the Game Loop
        while (guessCount < maxGuesses)
        {
            // Step 4: Get Player Input
            Console.Write("Guess the number (between 1 and 100): ");
            guess = int.Parse(Console.ReadLine());
            guessCount++;

            // Step 5: Check the Guess
            if (guess == targetNumber)
            {
                Console.WriteLine($"Congratulations! You guessed the number {targetNumber} in {guessCount} attempts!");
                break;
            }
            else if (guess < targetNumber)
            {
                Console.WriteLine("Guess higher.");
            }
            else
            {
                Console.WriteLine("Guess lower.");
            }
        }

        // Step 6: Handle Out-of-Guesses Condition
        if (guessCount == maxGuesses)
        {
            Console.WriteLine($"Sorry, you've run out of guesses. The number was {targetNumber}.");
        }

        // Step 7: Play Again (Optional)
        Console.Write("Do you want to play again? (yes/no): ");
        string playAgain = Console.ReadLine().ToLower();
        if (playAgain == "yes")
        {
            targetNumber = random.Next(1, 101);
            guessCount = 0;
            Console.WriteLine("New game started.");
        }
        else
        {
            Console.WriteLine("Thanks for playing! Goodbye.");
        }
    }
}

JS

// Step 1: Set Up the Game
const targetNumber = Math.floor(Math.random() * 100) + 1;

// Step 2: Initialize Variables
let guessCount = 0;
const maxGuesses = 10;

let guess = parseInt(prompt("Guess the number (between 1 and 100): "));
guessCount++;

if (guess === targetNumber) {
    console.log(`Congratulations! You guessed the number ${targetNumber} in ${guessCount} attempts!`);
} else if (guess < targetNumber) {
    console.log("Guess higher.");
} else {
    console.log("Guess lower.");
}

// Step 3: Start the Game Loop
while (guessCount < maxGuesses) {
    // Step 4: Get Player Input
    guess = parseInt(readline.question("Guess the number (between 1 and 100): "));
    guessCount++;

    // Step 5: Check the Guess
    if (guess === targetNumber) {
        console.log(`Congratulations! You guessed the number ${targetNumber} in ${guessCount} attempts!`);
        break;
    } else if (guess < targetNumber) {
        console.log("Guess higher.");
    } else {
        console.log("Guess lower.");
    }
}

// Step 6: Handle Out-of-Guesses Condition
if (guessCount === maxGuesses) {
    console.log(`Sorry, you've run out of guesses. The number was ${targetNumber}.`);
}

// Step 7: Play Again (Optional)
const playAgain = readline.question("Do you want to play again? (yes/no): ").toLowerCase();
if (playAgain === "yes") {
    targetNumber = Math.floor(Math.random() * 100) + 1;
    guessCount = 0;
    console.log("New game started.");
} else {
    console.log("Thanks for playing! Goodbye.");
}

Going beyond Text! – Python

Now, that you learned about the basics of programming games in Python typing code, what about adding some extra steps to your game and designing an awesome UI for it?

To do this we are going to use a built-in Python library, that helps us to add UI to our game:

import random  # Import the random module to generate random numbers
import tkinter as tk  # Import the tkinter library for GUI
from tkinter import messagebox  # Import messagebox from tkinter for displaying pop-up messages

and then we are going to define the functions needed to run inside our GUI interfaces:

# Step 1: Import necessary modules
import random  # Import the random module to generate random numbers
import tkinter as tk  # Import the tkinter library for GUI
from tkinter import messagebox  # Import messagebox from tkinter for displaying pop-up messages


# Step 2: Define a function to check the guess
def check_guess(event=None):
    global guess_count  # Declare the global variable guess_count to keep track of the number of guesses
    try:
        # Step 2a: Get the user's guess from the input field and convert it to an integer
        guess = int(entry.get())

        # Step 2b: Increment the guess_count by 1
        guess_count += 1

        # Step 2c: Update the label displaying the guess count
        guessing_count_label.config(text=guess_count)

        # Step 2d: Check if the guess is correct
        if guess == target_number:
            # Step 2d.1: If correct, display a congratulatory message with the target number and the number of attempts
            messagebox.showinfo("Congratulations", f"You guessed the number {target_number} in {guess_count} attempts!")
            # Step 2d.2: Reset the game
            reset_game()
        elif guess < target_number:
            # Step 2e: If the guess is too low, update the result label
            result_label.config(text="Guess higher.")
        else:
            # Step 2f: If the guess is too high, update the result label
            result_label.config(text="Guess lower.")

        # Step 2g: Check if the user has reached the maximum allowed guesses
        if guess_count == max_guesses:
            # Step 2g.1: If max guesses reached, display a message with the correct number and reset the game
            messagebox.showinfo("Out of Guesses", f"Sorry, you've run out of guesses. The number was {target_number}.")
            reset_game()
    except ValueError:
        # Step 2h: Handle a ValueError if the user enters a non-numeric input and show an error message
        messagebox.showerror("Invalid Input", "Please enter a valid number.")


# Step 3: Define a function to start a new game
def reset_game():
    global target_number, guess_count  # Declare global variables for target number and guess count
    # Step 3a: Generate a new random target number between 1 and 100
    target_number = random.randint(1, 100)
    # Step 3b: Reset the guess count to 0
    guess_count = 0
    # Step 3c: Clear the result label
    result_label.config(text="")
    # Step 3d: Clear the label displaying the guess count
    guessing_count_label.config(text=guess_count)
    # Step 3e: Clear the input field
    entry.delete(0, tk.END)


# Step 4: Create the main window
window = tk.Tk()  # Create the main tkinter window
window.title("Guess the Number Game")  # Set the title of the window

# Step 5: Set up initial game variables
target_number = random.randint(1, 100)  # Generate a random target number
guess_count = 0  # Initialize the guess count to 0
max_guesses = 10  # Set the maximum number of guesses

# Step 6: Create GUI components

# Step 6a: Create labels, entry field, buttons, and configure their properties
title_label = tk.Label(window, text="Guess the Number Game", font=("Arial", 32))
instruction_label = tk.Label(window, text="Guess the number (between 1 and 100):", font=("Arial", 16))
entry = tk.Entry(window)
check_button = tk.Button(window, text="Check", command=check_guess)
result_label = tk.Label(window, text="", fg="red", font=("Arial", 12))
guessing_count_Sign = tk.Label(window, text="Guessing Count:", fg="blue", font=("Arial", 12))
guessing_count_label = tk.Label(window, text="", fg="blue", font=("Arial", 12))
play_again_button = tk.Button(window, text="Play Again", command=reset_game)

# Step 6b: Bind the Enter key to the check_guess function so that pressing Enter is equivalent to clicking the "Check" button
entry.bind("<Return>", check_guess)

# Step 6c: Place GUI components on the window using the pack() method
title_label.pack()
instruction_label.pack()
entry.pack()
check_button.pack()
result_label.pack()
guessing_count_Sign.pack()
guessing_count_label.pack()
play_again_button.pack()

# Step 7: Start the GUI main loop, which waits for user interactions
window.mainloop()

BrainStorm

Building a full game based on Python sounds cool, right? So what about exploring another GUI and drawing methods using Python, like recursion drawing?

Content Licensing
Newsletter

Twitter Feed
Hot off the press!