PHP - Write program to create a simple number-guessing game

Requirements

Write program to create a simple number-guessing game

The script should generate a random number between 1 and 100.

Give the user five chances to guess the number.

For each guess, the script should report whether the guessed number was too low, too high, or correct.

Hint

Use hidden fields to store both the random number generated by computer, and the number of guesses left.

Use rand(1, 100) to generate a random number between 1 and 100.

 <html>
   <head>
     <title>Guess the Number</title>
   </head>
   <body>
     Guess the Number
 <?php

 if (isset($_POST[" submitButton" ]) and isset($_POST[" guess" ])) {
   processForm();
 } else {
   displayForm(rand(1, 100));
 }

 function processForm() {
   $number = (int)$_POST[" number" ];
   $guessesLeft = (int)$_POST[" guessesLeft" ]-1;
   $guess = (int)$_POST[" guess" ];

   if ($guess == $number) {
     displaySuccess($number);
   } elseif ($guessesLeft == 0) {
     displayFailure($number);
   } elseif ($guess <$number) {
     displayForm($number, $guessesLeft," Too low-try again!" );
   } else {
     displayForm($number, $guessesLeft," Too high-try again!" );
   }
 }

 function displayForm($number, $guessesLeft=5, $message="" ) {
 ?>
     <form action="" method="post">
       <div>
        <input type="hidden" name="number" value="<?php echo $number?>" />
        <input type="hidden" name="guessesLeft" value="<?php echo $guessesLeft?>" />
        <?php if ($message) echo " <p>$message</p>" ?>
        <p>I'm thinking of a number. You have <?php echo $guessesLeft?> <?php echo ($guessesLeft == 1) ?" try" :" tries" ?> left to guess it!</p>
        <p>What's your guess? <input type="text" name="guess" value=""/> 
        <input type="submit" name="submitButton" value="Guess"/></p>
      </div>
    </form>
<?php
}

function displaySuccess($number) {
?>
    <h2>Congratulations!</h2>
    <p>You guessed my number: <?php echo $number?>!</p>

    <form action="" method="post">
      <p><input type="submit" name="tryAgain" value="Try Again"/></p>
    </form>
<?php
}

function displayFailure($number) {
?>
    <h2>Bad luck!</h2>
    <p>You ran out of guesses. My number was <?php echo $number?>!</p>

    <form action="" method="post">
      <p><input type="submit" name="tryAgain" value="Try Again"/></p>
    </form>
<?php
}
?>
  </body>
</html>

Related Exercise