Jump to content

[SOLVED] Need help constructing a for loop


Trium918

Recommended Posts

Ok, Im trying to write the classic I'm Thinking of a Number game.

The user generates a number between 1 to 100 and the computer

guesses the number. The user is able to choose from high to low.

My algorithm should always be able to guess the number in seven

turns or fewer.

 

The follow code works but I need to insert a loop that will

keep up with the number of guess so that it will stop when

it reaches seven turns. I tried everything , so could

someone please help me out by trying this code to see what you

can come up with. Like I said, this code already works.

 

 

   echo "<form method=\"GET\">";
   echo "<input type=\"submit\"  name=\"Guess\" value=\"Guess\">";   
   echo "<input type=\"submit\"  name=\"Higher\" value=\"Higher\">";   
   echo "<input type=\"submit\"  name=\"Lower\" value=\"Lower\">";   
   
   if($_GET["Guess"]){
   	  $guess=50;
  $count++;
  print"<h2>My first number is: $guess <br></h2>";
  $max = 100;
  $min = 0;
   }
   
    if($_GET["Higher"]){
   	  $min = $guess;
  $guess = round($guess + (($max - $min)/2));
  $count++;
  print"<h2>Now my guess is: $guess <br></h2>";
  print"max = $max min = $min </h2>";
  print"count = $count";
   }
   
    if($_GET["Lower"]){
   	  $max = $guess;
  $guess = round($guess -(($max - $min)/2));
  $count++;
  print"<h2>Now my guess is: $guess <br></h2>";
  print"max = $max min = $min </h2>";
  print"count = $count";
   }
   
   
    
   echo "<input type=\"hidden\"  name=\"count\" value=\"$count\">";   
   echo "<input type=\"hidden\"  name=\"guess\" value=\"$guess\">";   
   echo "<input type=\"hidden\"  name=\"max\" value=\"$max\">";  
   echo "<input type=\"hidden\"  name=\"min\" value=\"$min\">";  
   
   echo"</form>";

Link to comment
Share on other sites

A for loop isn't the right structure here.  Sessions would be appropriate.

 

At the VERY TOP of your script, before ANY output at all, add

 

session_start();

 

Then, each time a guess is made, do

 

$_SESSION['guesses'] += 1;

 

Then, each time the script is run, also do

 

if ($_SESSION['guesses'] == 7) {
  echo "You're out of guesses!<br>";
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.