How do I imitate the game "Guess Who?

Can anyone help me with a php 'guess the number' game?

  • I have it pretty much working, except that every time I guess a number the number re-randomizes, and I am unsure how to fix it. Here is the code I have so far: <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www/w3.org/TR/xhtml1/DTD/xhtm… <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Guess the Number! </title> </head> <body> <?php ?> <h2>Time to Guess!</h2> <form method="get" action="guessgame.php"> <div> Guess the number! <br/> <input type="text" name="guess"/> <button type="submit"> Give a Guess! </button> </div> <?php $guess = filter_input(INPUT_GET,"guess"); if(isset($_GET['thenumber'])) { $thenumber = $_GET['thenumber']; } else { $thenumber = rand(1,100); } $guesscount=0; echo $thenumber; if ($guess<$thenumber) { echo "That is too low. Try again!"; $guesscount++; } else if ($guess>$thenumber) { echo "That is too high. Try again!"; $guesscount++; } else { echo "You guessed right! It took you" .$guesscount. "times!"; } ?> </form> </body> </html> Any and all help would be great

  • Answer:

    Right now you have it so that the only data being saved between page loads is the user's guess (php is only going to save things used in POST/GET, if you start a user session, or if you set a cookie). I would recommend setting a cookie (http://www.w3schools.com/php/php_cookies.asp) with the random number. Only create a random number if the cookie is empty. Then set $guess = $_COOKIES["rightanswer"] and the rest should be fine. If you don't want to mess with cookies, you can try and get creative with POST data (setting an invisible text field with your form that sets itself or something) but you need to make sure there is some way for php to save the guess between page loads.

shawneef... at Yahoo! Answers Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.