ALMorrow
ALMorrow

Reputation: 85

(PHP) Adding a 'guess counter' to a random number game

I need to modify a block of code and add a counter regarding how many times it took the user to guess the right number.

I was wondering how it would be properly implemented into my code.

This is what I have so far.

<?php

if (!isset($_POST["guess"])) {
     $message = "Welcome to the guessing machine!";
     $count++; //Declare the variable $count to increment by 1.
     $_POST["numtobeguessed"] = rand(0,1000);
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
    $message = $_POST["guess"]." is too big! Try a smaller number.";

} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
    $message = $_POST["guess"]." is too small! Try a larger number.";

} else { // must be equivalent
    $message = "Well done! You guessed the right number in ".$count." attempt(s)!"; 
        //Include the $count variable to the $message to show the user how many tries to took him.
}
?>
<html>
    <head>
        <title>A PHP number guessing script</title>
    </head>
    <body>
    <h1><?php echo $message; ?></h1>
        <form action="" method="POST">
        <p><strong>Type your guess here:</strong>
            <input type="text" name="guess"></p>
            <input type="hidden" name="numtobeguessed" 
                   value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
    <p><input type="submit" value="Submit your guess"/></p>
        </form>
    </body>
</html>

Upvotes: 2

Views: 8429

Answers (3)

on 22.6.2021 i wrote a Guess Number in Range [0 .. aMaxIntValue] sample Web Application using PHP. i think the following code may help you. the code is kept in a Single PHP file. it generates #4 HTML pages ...

  • the 1st initial page is used to collect application parameters (e.g. the Max Int Number to Guess)

  • the 2nd page is the Main Play Game Page where the user is asked to Guess the Secret Number or to Reset Game. this page shows the previous user guesses and some tips for the user about the guess

  • the 3rd page is used to notify the user looses game (that is he has no more tries left)

  • the 4th page is used to notify the user wins the game (that is the Guess was OK)

the Number of Tries left to the User is computed using the values range [0 .. max]

the Secret Number to Guess is a random generated integer number

this is the PHP + HTML code ...

<?php

    session_start();

    error_reporting (E_PARSE | E_COMPILE_ERROR);

    function ResetGame()
    {
        unset ( $_SESSION['theMaxNumber'] );
    }

    function InitGame()
    {
        $_SESSION['theNumberToGuess'] = mt_rand (0, $_SESSION['theMaxNumber']);

        $_SESSION['theMaxNumberOfTries'] = floor ( log ($_SESSION['theMaxNumber'], 2) ) + 1;

        $_SESSION['theUserTriesCount'] = 0;

        $_SESSION['thePrevGuessesString'] = '';

        $_SESSION['theUserGuess'] = 0;
    }

    function ComputeNumberOfTriesLeft()
    {
        return $_SESSION['theMaxNumberOfTries'] - $_SESSION['theUserTriesCount'];
    }

    function IsNoMoreTriesLeft()
    {
        return ComputeNumberOfTriesLeft() <= 0;
    }

    $aCanPlayGame = false;

    $aUserSubmittedGuess = false;

    $aIsNoMoreTriesLeft = false;

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

        if ( isset ($_REQUEST['playgame']) ) {

            $_SESSION['theMaxNumber'] = intval($_REQUEST['theMaxNumber']);

            // init game ...
            InitGame();

            $aCanPlayGame = true;

        }
        elseif ( isset ($_REQUEST['submituserguess']) ) {

            $aCanPlayGame = true;

            $aUserSubmittedGuess = true;

            $_SESSION['theUserGuess'] = intval($_REQUEST['theUserGuess']);

        }
        elseif ( isset ($_REQUEST['resetgame']) ) {

            ResetGame();

        }
        else {
            ResetGame();
        }

    }
    else {
        ResetGame();
    }

    // check a play

    $aUserShouldTryLower = false;
    $aUserShouldTryHigher = false;

    $aUserWins = false;

    $aUserLooses = false;

    if ($aCanPlayGame) {

        $aIsNoMoreTriesLeft = IsNoMoreTriesLeft();

        if ( ! $aIsNoMoreTriesLeft ) {

            // user have tries left

            if ($aUserSubmittedGuess) {

                // check user guess ...
                $aUserGuess = intval($_SESSION['theUserGuess']);

                if ( $aUserGuess > $_SESSION['theNumberToGuess'] ) {

                    $aUserShouldTryLower = true;

                }
                elseif ( $aUserGuess < $_SESSION['theNumberToGuess'] ) {

                    $aUserShouldTryHigher = true;

                }
                else {

                    $aUserWins = true;

                    // also reset game
                    ResetGame();

                }

                // add the current guess to the prev guesses string
                $_SESSION['thePrevGuessesString'] .= $_SESSION['theUserGuess'] . ' ';

                // increase the user tries count
                ++ $_SESSION['theUserTriesCount'];

                // check tries count
                if ( ! $aUserWins ) {

                    $aIsNoMoreTriesLeft = IsNoMoreTriesLeft();

                    if ($aIsNoMoreTriesLeft) {
                        // this was the last try

                        // no more tries left
                        $aUserLooses = true;

                        // also reset game
                        ResetGame();
                    }

                }
            }

        }
        else {
            // no more tries left
            $aUserLooses = true;

            // also reset game
            ResetGame();
        }

    }

?>

<?php if ($aUserLooses): ?>

<!DOCTYPE html>
<html>
<head>
    <title>Guess a Number</title>
</head>
<body>
    <p>Sorry, you loose the game</p>
    <p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
    <form method="post">
        <input type="submit" name="resetgame" value="reset game">
    </form>
</body>
</html>

<?php elseif ($aUserWins): ?>

<!DOCTYPE html>
<html>
<head>
    <title>Guess a Number</title>
</head>
<body>
    <p>Congrats, you Win the Game</p>
    <p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
    <form method="post">
        <input type="submit" name="resetgame" value="reset game">
    </form>
</body>
</html>

<?php elseif ($aCanPlayGame): ?>

<!DOCTYPE html>
<html>
<head>
    <title>Guess a Number</title>
</head>
<body>

    <p>the Max Number is <?php echo $_SESSION['theMaxNumber']; ?></p>
    <p>Guess a Number in the Range [ 0 .. <?php echo ($_SESSION['theMaxNumber']); ?> ]</p>
    <p>[DEBUG] the secret number to guess is <?php echo $_SESSION['theNumberToGuess']; ?></p>
    <p>you have <?php echo ComputeNumberOfTriesLeft(); ?> tries left</p>
    <form method="post">
        <label for="theUserGuess">Enter your Guess: </label>
        <input type="text" id="theUserGuess" name="theUserGuess">
        <input type="submit" name="submituserguess" value="Guess">
        <input type="submit" name="resetgame" value="reset game">
    </form>
    <p>Prev Guesses: <?php echo $_SESSION['thePrevGuessesString']; ?> </p>
    <p>
        <?php
            if ($aUserShouldTryLower) {
                echo 'you should try a lower < guess';
            }
            elseif ($aUserShouldTryHigher) {
                echo 'you should try a higher > guess';
            }
            else {
                echo 'no guess';
            }
        ?>
    </p>

</body>
</html>

<?php else: ?>

<!DOCTYPE html>
<html>
<head>
    <title>Guess a Number</title>
</head>
<body>

    <p>Guess a Number from (0) to ... </p>
    <form method="post">
        <input id="theMaxNumber" name="theMaxNumber">
        <input type="submit" name="playgame" value="play game">
    </form>

</body>
</html>

<?php endif; ?>

that's all folks ...

Upvotes: 0

Bogdan Habic
Bogdan Habic

Reputation: 94

This should work for you.

$count = isset($_POST['count']) ? $_POST['count'] : 0; //Use post value if defined. If not set to 1.
if (!isset($_POST["guess"])) {
     $message = "Welcome to the guessing machine!";
     $_POST["numtobeguessed"] = rand(0,1000);
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
    $message = $_POST["guess"]." is too big! Try a smaller number.";

} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
    $message = $_POST["guess"]." is too small! Try a larger number.";

} else { // must be equivalent
    $message = "Well done! You guessed the right number in ".$count." attempt(s)!"; 
        //Include the $count variable to the $message to show the user how many tries to took him.
}
$count++;
?>
<html>
    <head>
        <title>A PHP number guessing script</title>
    </head>
    <body>
    <h1><?php echo $message; ?></h1>
        <form action="" method="POST">
        <p><strong>Type your guess here:</strong>
            <input type="text" name="guess"></p>
            <input type="hidden" name="numtobeguessed" 
                   value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
            <input type="hidden" name="count" 
                   value="<?php echo $count; ?>" ></p>
    <p><input type="submit" value="Submit your guess"/></p>
        </form>
    </body>
</html>

Upvotes: 1

Bijan
Bijan

Reputation: 8602

You have to use PHP Sessions to keep track of the count. All you have to do is initialize counter to 0 and have it increment when the user guesses a number

<?php
session_start();

if (!isset($_POST["guess"])) {
     $_SESSION["count"] = 0; //Initialize count
     $message = "Welcome to the guessing machine!";
     $_POST["numtobeguessed"] = rand(0,1000);
     echo $_POST["numtobeguessed"];
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
    $message = $_POST["guess"]." is too big! Try a smaller number.";
    $_SESSION["count"]++; //Declare the variable $count to increment by 1.

} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
    $message = $_POST["guess"]." is too small! Try a larger number.";
    $_SESSION["count"]++; //Declare the variable $count to increment by 1.

} else { // must be equivalent
    $_SESSION["count"]++;
    $message = "Well done! You guessed the right number in ".$_SESSION["count"]." attempt(s)!"; 
    unset($_SESSION["count"]);
        //Include the $count variable to the $message to show the user how many tries to took him.
}
?>
<html>

    <head>
        <title>A PHP number guessing script</title>
    </head>
    <body>
    <h1><?php echo $message; ?></h1>
        <form action="" method="POST">
        <p><strong>Type your guess here:</strong>
            <input type="text" name="guess"></p>
            <input type="hidden" name="numtobeguessed" 
                   value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
    <p><input type="submit" value="Submit your guess"/></p>
        </form>
    </body>
</html>

Upvotes: 4

Related Questions