Skip to content

Instantly share code, notes, and snippets.

@lantins
Created September 5, 2008 15:13
Show Gist options
  • Save lantins/8976 to your computer and use it in GitHub Desktop.
Save lantins/8976 to your computer and use it in GitHub Desktop.
secret number game example
<?
// setup our session.
ini_set('session.use_only_cookies', true);
session_name('secret_number_game');
session_start();
// set the secret number; once!
function secret_number()
{
if (isset($_SESSION['secret_number']) == false) {
$_SESSION['secret_number'] = rand(1, 10);
}
$secret_number = $_SESSION['secret_number'];
return $secret_number;
}
function check_guess($guess)
{
$secret_number = secret_number();
if ($guess == $secret_number) {
// here we unset our secret_number. So we can have a new one for the next game!
unset($_SESSION['secret_number']);
return true;
}
return false;
}
// we call this; encase its the first time the user has accessed the site.
secret_number();
$winner = false;
$guess = false;
// see if the user has guessed at the number.
if (isset($_POST['guess'])) {
$winner = check_guess($_POST['guess']);
$guess = $_POST['guess'];
}
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Guess The Secret Number</title>
</head>
<body>
<h1>Guess the secret number!</h1>
<? if ($winner == false): ?>
<p>Guess the secret number. Number is set between 1-10 inc.</p>
<? if ($guess != false): ?>
<p>
<strong>You guessed:</strong> <?= $guess ?><br />
Unfortunately for you loser; thats the wrong number; try again!
</p>
<? endif; ?>
<form method="post" action="/secret_number_game.php">
<p>Your Guess: <input type="text" name="guess" /></p>
<p><input type="submit" /></p>
</form>
<? else: ?>
<p><strong>Your a winner!</strong> You sucsesfully guessed the secret number!</p>
<p><a href="/secret_number_game.php">Click Here</a> to play again.</p>
<? endif; ?>
<hr />
<h5>Debug Data</h5>
<pre><? var_dump($_SESSION) ?></pre>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment