top of page

[Beginner Project]: Number Guessing Game

Updated: Apr 24

Imagine a guessing game where the user must find a randomly selected number between a specified lower and upper bound. The game provides the user with feedback after each guess, guiding them to narrow down the possible range of numbers until they correctly guess the hidden number.




How to Play:

  • The game starts by asking the user to input a lower and upper bound for the range of numbers.

  • The game then generates a random number within this range for the user to guess.

  • The user is informed about the number of chances they have to guess the integer based on the range size.

  • The user starts guessing numbers within the range provided.

  • After each guess, the user receives feedback:

  • If the guess is too high, they are prompted to guess lower.

  • If the guess is too low, they are prompted to guess higher.

  • If the guess is correct, the game ends with a congratulatory message.

  • The game continues until the user either guesses the correct number or runs out of chances.

Strategy:

The game is designed to encourage a strategic approach to guessing by halving the range with each guess. This methodical strategy helps the user efficiently narrow down the possible numbers and increase their chances of guessing the correct number within the given attempts.

Example Gameplay:

  • User guesses a number within the range.

  • Based on the feedback, the user adjusts their guess to narrow down the range.

  • By iteratively halving the range, the user strategically approaches the correct number.

  • The game ends when the user correctly guesses the hidden number or exhausts their chances.



Benefits:

  • Encourages logical thinking and strategic guessing.

  • Teaches the importance of narrowing down possibilities efficiently.

  • Enhances problem-solving skills through iterative guessing and feedback analysis.


Python:

Install Dependencies :

Import Random module :

pip install random2 

Import Math module :

pip install python-math      	

Complete Code:

import random2
import math

# Taking Inputs
lower = int(input("Enter Lower bound:- "))

# Taking Inputs
upper = int(input("Enter Upper bound:- "))

# generating random number between
# the lower and upper
x = random.randint(lower, upper)
print("\n\tYou've only ", 
    round(math.log(upper - lower + 1, 2)),
    " chances to guess the integer!\n")

# Initializing the number of guesses.
count = 0

# for calculation of minimum number of
# guesses depends upon range
while count < math.log(upper - lower + 1, 2):
    count += 1

    # taking guessing number as input
    guess = int(input("Guess a number:- "))

    # Condition testing
    if x == guess:
        print("Congratulations you did it in ",
            count, " try")
        # Once guessed, loop will break
        break
    elif x > guess:
        print("You guessed too small!")
    elif x < guess:
        print("You Guessed too high!")

# If Guessing is more than required guesses,
# shows this output.
if count >= math.log(upper - lower + 1, 2):
    print("\nThe number is %d" % x)
    print("\tBetter Luck Next time!")

Java:

import java.util.Random;
import java.lang.Math;
import java.util.Scanner;

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

        // Taking Inputs
        System.out.print("Enter Lower bound: ");
        int lower = scanner.nextInt();

        // Taking Inputs
        System.out.print("Enter Upper bound: ");
        int upper = scanner.nextInt();

        // generating random number between the lower and upper
        Random random = new Random();
        int x = random.nextInt(upper - lower + 1) + lower;
        System.out.println("\n\tYou've only " + Math.round(Math.log(upper - lower + 1) / Math.log(2)) + " chances to guess the integer!\n");

        // Initializing the number of guesses.
        int count = 0;

        // for calculation of minimum number of guesses depends upon range
        while (count < Math.log(upper - lower + 1) / Math.log(2)) {
            count++;

            // taking guessing number as input
            System.out.print("Guess a number: ");
            int guess = scanner.nextInt();

            // Condition testing
            if (x == guess) {
                System.out.println("Congratulations you did it in " + count + " try");
                // Once guessed, loop will break
                break;
            } else if (x > guess) {
                System.out.println("You guessed too small!");
            } else {
                System.out.println("You Guessed too high!");
            }
        }

        // If Guessing is more than required guesses, shows this output.
        if (count >= Math.log(upper - lower + 1) / Math.log(2)) {
            System.out.println("\nThe number is " + x);
            System.out.println("\tBetter Luck Next time!");
        }

        scanner.close();
    }
}

C++:

 #include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>

int main() {
    int lower, upper, x, guess, count = 0;

    std::cout << "Enter Lower bound: ";
    std::cin >> lower;

    std::cout << "Enter Upper bound: ";
    std::cin >> upper;

    std::srand(std::time(NULL));
    x = lower + std::rand() % (upper - lower + 1);

    std::cout << "\n\tYou've only " << static_cast<int>(std::log2(upper - lower + 1)) << " chances to guess the integer!\n";

    while (count < std::log2(upper - lower + 1)) {
        count++;

        std::cout << "Guess a number: ";
        std::cin >> guess;

        if (x == guess) {
            std::cout << "Congratulations you did it in " << count << " try" << std::endl;
            break;
        } else if (x > guess) {
            std::cout << "You guessed too small!" << std::endl;
        } else {
            std::cout << "You Guessed too high!" << std::endl;
        }
    }

    if (count >= std::log2(upper - lower + 1)) {
        std::cout << "\nThe number is " << x << std::endl;
        std::cout << "\tBetter Luck Next time!" << std::endl;
    }

    return 0;
}l̥L


Enjoy the Game:

Have fun playing the guessing game and enjoy the challenge of strategically narrowing down the range to find the hidden number!

Kommentare


bottom of page