Skip to content

Instantly share code, notes, and snippets.

@winfamy
Last active March 20, 2018 14:03
Show Gist options
  • Save winfamy/5bd24d0cec5c461dc0645fa4880e3ba4 to your computer and use it in GitHub Desktop.
Save winfamy/5bd24d0cec5c461dc0645fa4880e3ba4 to your computer and use it in GitHub Desktop.
php jelly beans
<? session_start(); ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Jellybean Game</title>
</head>
<body>
<?php
if (isset($_POST['number'])) {
$_SESSION['maxbeans'] = $_POST['number'];
$_SESSION['beans'] = rand(0, $_SESSION['maxbeans']);
// can probably put your other form here
}
if (isset($_POST['guess'])) {
// sets to 0 if the session variable not found, otherwise increments by 1
$_SESSION['guesscount'] = isset($_SESSION['guesscount']) ? $_SESSION['guesscount']+1 : 1;
$userguess = $_POST['guess'];
// these next two if statements do the same thing?
if ($userguess === $beans && $_SESSION['guesscount'] === 1) {
echo "<p>You guessed correctly. It took you " . $guesscount . " attempt. Well done <a href='#'>Click here to play again.</a></p>";
}
elseif ($userguess === $beans) {
echo "<p>You guessed correctly. It took you " . $guesscount . " attempt. Well done<a href='#'>Click here to play again.</a></p>";
}
elseif ($userguess < $beans) {
echo "<p>Guess too high, try a little lower.</p>";
}
elseif ($userguess > $beans) {
echo "<p>Guess too low, try a little higher.</p>";
}
}
if (!isset($_POST['number']) && !isset($_POST['guess'])) {
// no other needed behavior, default to displaying original form
?>
<form action="" method="post">
<p>How many beans will be in the jar?</p>
<input name="number" type="text">
<button type="submit" value="Play!">Play!</button>
<input type="hidden" name="step" value="1">
</form>
<?php
}
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment