Jump to content

Can somebody help me with this (simple program, messing up session variables?)


Recommended Posts

Sorry for my noob question, I've learned about sessions a bit and tried to make a simple "game", basically a user has to enter one of the colors of the rainbow and after they name all 7, they win. Sounds simple enough, but I'm clearly making an obvious mistake and I've googled and read and experimented, but obviously something is alluding me.

 

Here is the pastebin:

http://pastebin.com/XmN4YLp8

 

 

I suppose what I want to know is...how do I store the values from the form (that is, $_POST['color']) and save that information to something like an array, because whatever I'm doing now is resetting the counter ($_SESSION['left']) and if a user guesses "red" for instance, it temporarily goes from 7 to 6, but then bumps up to 7?

 

 

Try:

    <?php
    session_start();
    $sessionID = session_id();
$_SESSION['left'] = (isset($_SESSION['left'])) ? $_SESSION['left'] : 7;
    ?>
     
    <html>
     
    <head>
      <title>Rainbow</title>
    </head>
     
    <body>
       
    Do you know all the colors in the rainbow?<br /><br />
     
    <form name="input" action="rainbow.php" method="POST">
    Color: <input type="text" name="color" value="" />
    <input type="submit" value="Guess!" name ="guess"/>
    </form>
     
              <?php
             
              // the goal of the game is to have a user enter a color in the form,
              // when it detects one of the correct 7 colors, it subtracts from
              // $_SESSION['left'], when $_SESSION['left'] = 0, the user wins
  if(isset($_POST['color'])) {         
                    $rainbowcolors = array ("red",
										"orange",
                                            "yellow",
                                            "green",
                                            "blue",
                                            "indigo",
                                            "violet");                

				if (in_array($_POST['color'],$rainbowcolors)) {          
                       $_SESSION['left']--;         // correct guess!
               
                    } else
                    {
                        $wrong = "Your guess '{$_POST['color']}' was wrong, try again.";
                 
                    }

                     
                    // when the amount of remaining colors reaches 0, end the game
                     if ($_SESSION['left'] == 0){
                        echo "Congratultions, you got them all! <br /><br />";
                        echo '<a href="rainbow.php">Play again?</a>';
                     }
				 else {
				 echo "You have " . $_SESSION['left'] . " colors left to guess<br /><br />";
				 }
                      
				 if(isset($wrong)) { echo $wrong; }
                       
                    ?>
     
     
     <br /><br />    
             
     
     
            <?php
                        // array info for debugging
                        '<pre>'; print_r($_SESSION); echo '</pre>';
                       
                        echo "<br /><br />Session ID:    " . $sessionID;
     }
              ?>
          
             
    </body>
     
    </html>

 

Let us know how it goes!

I ended up making a few changes, such as putting $_SESSION['left'] into a conditional statement.

 

- I have to make two correct guesses in order for the "You have " . $_SESSION['left'] . " colors left to guess" to start subtracting, why does it do this?

- Also, how do I prevent it from registering the same answer twice, like red/red/red/red/red/red/blue ?

 

Try this:

<?php
    session_start(); //start session.
    $sessionID = session_id();

if(isset($_GET['reset']) && $_GET['reset'] == 1) { //if you click the play again button, reset the session variables.
	unset($_SESSION['left']);
	unset($_SESSION['colors']);
}

$_SESSION['left'] = (isset($_SESSION['left'])) ? $_SESSION['left'] : 7; //if session left exists, use it, if not, then create it.

if(!isset($_SESSION['colors'])) { //if session colors doesn't exists, make it an array.
	$_SESSION['colors'] = array();
}
    ?>
     
    <html>
     
    <head>
      <title>Rainbow</title>
    </head>
     
    <body>
       
    Do you know all the colors in the rainbow?<br /><br />
     
    <form name="input" action="" method="POST">
    Color: <input type="text" name="color" value="" />
    <input type="submit" value="Guess!" name ="guess"/>
    </form>
     
              <?php
             
              // the goal of the game is to have a user enter a color in the form,
              // when it detects one of the correct 7 colors, it subtracts from
              // $_SESSION['left'], when $_SESSION['left'] = 0, the user wins
     if(isset($_POST['color'])) { 	 //if form is submitted.
                    $rainbowcolors = array ("red",
                                            "orange",
                                            "yellow",
                                            "green",
                                            "blue",
                                            "indigo",
                                            "violet");                   
                    
                if(!in_array($_POST['color'],$_SESSION['colors'])) {   //if the color doesn't match the a color in the used colors array.
				$_SESSION['colors'][] = $_POST['color']; //add the color to the used colors array.
				if (in_array($_POST['color'],$rainbowcolors)) {  //if the color exist in the rainbow array, then it is correct, subtract the session left variable..
                       $_SESSION['left']--;         // correct guess!
               
                    } else //if the color doesn't exist in the rainbow array, set a wrong answer variable.
                    {
                        $wrong = "Your guess '{$_POST['color']}' was wrong, try again.";
                 
                    }
			}
			else { //if the color exists in the used color array, set a wrong answer variable.
				$wrong = 'You have already guessed \''. $_POST['color'] . '\', try again.';
			}
                   
                   
                    // when the amount of remaining colors reaches 0, end the game
                    if ($_SESSION['left'] == 0){
                        echo "Congratultions, you got them all! <br /><br />";
                        echo '<a href="?reset=1">Play again?</a>';
                     }
				else {
					echo "You have " . $_SESSION['left'] . " colors left to guess<br /><br />";
				}
                      
				if(isset($wrong)) { echo $wrong; }  //if the wrong answer variable is set, print it to the screen.
                       
                    ?>
     
     
     <br /><br />    
             
     
     
            <?php
                        // array info for debugging
                        echo '<pre>'; print_r($_SESSION); echo '</pre>';
                       
                        echo "<br /><br />Session ID:    " . $sessionID;
                }   
              ?>
             
         
    </body>
     
    </html>

reading this post, my mind is thinking of an alternative method/solution.

I might give it ago in the morning (3am here)

but essentially it involves 1 session object which is an array of keys being the colours and values all being 0 (at start of game), and then update each value to 1 when the colour(session array key) is posted in the form, and of course the usual checks to clarify if its been chosen already or not.

 

it avoids the maths part at any rate

theres always more than one way to skin a cat, here is my effort, I made functions rather than just procedural code. I was thinking of adding a css bit which outputs colored divs to simulate a rainbow, but perhaps later...

<?php
//functions
function startgame(){
if (isset($_SESSION['rainbow'])) unset($_SESSION['rainbow']);
$_SESSION['rainbow'] = array("red"=>0,"orange"=>0,"yellow"=>0,"green"=>0,"blue"=>0,"indigo"=>0,"violet"=>0);
}
function checkcolor($color){
if(array_key_exists($color, $_SESSION['rainbow'])){
if($_SESSION['rainbow'][$color] == 0){
	$_SESSION['rainbow'][$color] = 1;
	if(array_sum($_SESSION['rainbow'] ) == 7){
		return "you have guessed all colors correctly";
		//you could reset session varialbe here too, to auto reset the game.
	}
	else {
		return "you need " . (7 - array_sum($_SESSION['rainbow'] )) . " more color(s) to finish.";
	}
}
else
{
	return "You already chose this color, please try again";
}
}
else
{
return "The color " . $color . " is not in the rainbow";
}
}
//runtime
session_start();
$output = "";
if (!isset($_SESSION['rainbow']) || isset($_GET['reset'])){ startgame();}
if (isset($_POST['color']) && $_POST['color'] <> "") {
$output = checkcolor($_POST['color']);
}
else
{
$output = "nothing was entered";
}

?>
<!DOCTYPE HTML>
<html>
<head>
<title>I can see a rainbow</title>
<style>
body {font-family:arial;}
</style>
</head>
<body>
Do you know all the colors in the rainbow?<br><br>
<?php
echo $output;
?>
<form name="input" action="rainbow.php" method="POST">
Color: <input type="text" name="color" value="" >
<input type="submit" value="Guess!" name ="guess">
</form> 
<a href="rainbow.php?reset=1">Start over</a>
</body>
</html>

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.