A simple Number Guessing Game in PHP

Here’s a simple Number Guessing Game in PHP along with an explanation of the code:

Project Description

The objective of this game is to allow the user to guess a randomly generated number within a certain range (e.g., between 1 and 100).

The game will give feedback whether the guess was too high, too low, or correct.

Complete Code

<?php
// Start the session to keep track of the generated number and attempts
session_start();

// Generate a random number between 1 and 100, and store it in the session if not already set
if (!isset($_SESSION['random_number'])) {
    $_SESSION['random_number'] = rand(1, 100);
    $_SESSION['attempts'] = 0; // Initialize attempts counter
}

// Initialize an empty message variable
$message = "";

// Check if the form was submitted
if (isset($_POST['guess'])) {
    $user_guess = (int)$_POST['guess']; // Get the user's guess from the form input
    $_SESSION['attempts']++; // Increment the attempt counter

    // Compare the guess to the randomly generated number
    if ($user_guess < $_SESSION['random_number']) {
        $message = "Your guess is too low!";
    } elseif ($user_guess > $_SESSION['random_number']) {
        $message = "Your guess is too high!";
    } else {
        // If the guess is correct
        $message = "Congratulations! You've guessed the number in " . $_SESSION['attempts'] . " attempts.";
        // Reset the game by regenerating a new random number and resetting attempts
        unset($_SESSION['random_number']);
        unset($_SESSION['attempts']);
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Number Guessing Game</title>
</head>
<body>
    <h1>Number Guessing Game</h1>
    
    <!-- Display the message after each guess -->
    <p><?php echo $message; ?></p>
    
    <!-- Form for the user to input their guess -->
    <form method="post" action="">
        <label for="guess">Enter your guess (between 1 and 100):</label>
        <input type="number" name="guess" min="1" max="100" required>
        <button type="submit">Guess</button>
    </form>
</body>
</html>

 

Explanation of the Code

1. Starting the Session

session_start();

 

We use PHP sessions to store data across different page requests. Here, we store the random number and the number of attempts in the session.

2. Random Number Generation and Storing

if (!isset($_SESSION['random_number'])) {
    $_SESSION['random_number'] = rand(1, 100);
    $_SESSION['attempts'] = 0;
}

 

This block checks if a random number is already stored in the session. If not, it generates a random number between 1 and 100 using rand(1, 100) and stores it in the session.
It also initializes an attempts counter to 0.

3. Handling User Input

if (isset($_POST['guess'])) {
    $user_guess = (int)$_POST['guess'];
    $_SESSION['attempts']++;
}

 

This checks if the form has been submitted (i.e., the user has made a guess). It retrieves the user’s input ($_POST[‘guess’]) and casts it to an integer to ensure it’s in the correct format.
Each time a guess is made, the number of attempts is incremented by one.

4. Guess Evaluation

if ($user_guess < $_SESSION['random_number']) {
    $message = "Your guess is too low!";
} elseif ($user_guess > $_SESSION['random_number']) {
    $message = "Your guess is too high!";
} else {
    $message = "Congratulations! You've guessed the number in " . $_SESSION['attempts'] . " attempts.";
    unset($_SESSION['random_number']);
    unset($_SESSION['attempts']);
}

 

Here, the user’s guess is compared to the stored random number:
If the guess is lower, the message “Your guess is too low!” is displayed.
If the guess is higher, the message “Your guess is too high!” is displayed.
If the guess is correct, the message congratulates the user and shows how many attempts it took.

After the correct guess, we unset() the session variables (random_number and attempts) to reset the game.

5. HTML Form for Input

<form method="post" action="">
    <label for="guess">Enter your guess (between 1 and 100):</label>
    <input type="number" name="guess" min="1" max="100" required>
    <button type="submit">Guess</button>
</form>

 

This is the simple HTML form where the user can input their guess. The form sends the data via POST when submitted.
The <input> field allows users to enter a number between 1 and 100.

6. Displaying the Message

<p><?php echo $message; ?></p>

 

After each guess, the result (too high, too low, or correct) is displayed to the user by echoing the $message variable.

How the Game Works

Start of the Game: When the game is loaded for the first time, a random number between 1 and 100 is generated and stored in the session.
User Guesses: The user enters a number through the form and submits it.
Feedback: The program compares the guess to the stored random number and displays feedback—whether the guess was too high, too low, or correct.
Winning: If the user guesses correctly, the program resets the game (by unsetting the session variables), allowing them to play again.

Future Improvements:

Limit the Number of Attempts: You could add a limit to how many times a user can guess before losing the game.
Difficulty Levels: Add different difficulty levels (e.g., easy: 1-50, hard: 1-200).
Store Past Guesses: Keep track of the user’s previous guesses and display them on the page.
Styling: Add CSS to improve the appearance of the game.

This simple PHP project demonstrates how to work with sessions, forms, and basic logic in PHP. It’s a great way to practice user input handling, conditional statements, and session management!

Related posts

A Palindrome Checker in PHP

a Multiplication Table Generator in PHP

A simple BMI Calculator in PHP