PHP even or odd number script - php

I'm using this code to check a number if it's an even or an odd number. I'm learning PHP and when I run this code it gives an unusual error.
<html>
<body>
<head>
<title>Judging even and odd numbers</title>
</head>
<form method = "post" action="EAO.php" >
<font size = "20">Please enter a number to check if it is even or odd:</font>
<input type = "text" name = "number" />
<input type = "hidden" name="checker" value="true" />
<input type = "submit" value = "submit" />
</form>
<?PHP
if (isset($_POST['checker'])) {
$number = $_POST['number'];
if ($number % 2 == 0 ) {
echo "The number is Even";
}
if($number % 2 == 1 ) {
echo "The number is odd";
}
if ($number == "") {
echo "Please enter a number";
}
}
?>
</body>
</html>
It works good when you input a number but when you submit the form empty, Its says "Please enter a number. The number is even". Help me correct it if I'm doing something wrong. If my code isn't of standard to judge a number, please write your code that is better. Thank you.

Just reversing your logic will do the magic for you. You must always use if () {....} elseif () {....} so that only one logic runs at a given time.
<html>
<head>
<title>Judging even and odd numbers</title>
</head>
<body>
<form method = "post" action="EAO.php" >
<font size = "20">Please enter a number to check if it is even or odd:</font>
<input type = "text" name = "number" />
<input type = "hidden" name="checker" value="true" />
<input type = "submit" value = "submit" />
</form>
<?PHP
if (isset($_POST['checker'])) {
$number = $_POST['number'];
if ($number == "") {
echo "Please enter a number";
}
else if ($number % 2 == 0 ) {
echo "The number is Even";
}
else if($number % 2 == 1 ) {
echo "The number is odd";
}
}
?>
</body>
</html>

Try this :
<html>
<head>
<title>Judging even and odd numbers</title>
</head>
<body>
<form method = "post" action="" >
<font size = "20">Please enter a number to check if it is even or odd:</font>
<input type = "text" name = "number" />
<input type = "hidden" name="checker" value="true" />
<input type = "submit" value = "submit" />
</form>
<?PHP
if (isset($_POST['checker'])) {
$number = $_POST['number'];
if(empty($number))
{
echo "Please enter a number";
}
elseif ($number % 2 == 0 ) {
echo "The number is Even";
}
else {
echo "The number is odd";
}
}
?>
</body>
</html>
Place body tag after head tag. If you are posting the form to the same page then action parameter is optional.
Use if...elseif...else condition http://www.w3schools.com/php/php_if_else.asp

another working version is (improved security):
<?php
if (isset($_POST['checker']) && $_POST['checker'] == 'true') {
if (empty($_POST['number'])) { // 0 or empty values will be blocked
echo "Please enter a number";
} else {
if (ctype_digit($_POST['number'])) { // only number will be accepted
$number = $_POST['number'];
if ($number % 2 == 0 ) {
echo "The number is Even";
}
if($number % 2 == 1 ) {
echo "The number is odd";
}
else {
echo 'Numbers only please!';
}
}
}
?>

HI bro here we go with you code
<html>
<body>
<head><title>Judging even and odd numbers</title></head>
<form method = "post" action="" >
<font size = "20">Please enter a number to check if it is even or odd:</font>
<input type = "text" name = "number" />
<input type = "hidden" name="checker" value="true" />
<input type = "submit" value = "submit" name="submit" />
</form>
<?PHP
if (isset($_POST['submit'])) {
$number = $_POST['number'];
if ($number % 2 == 0 ) {
echo "The number is Even";
}
if($number % 2 == 1 ) {
echo "The number is odd";
}
if ($number == "") {
echo "Please enter a number";
}
}
?>
</body>
</html>

Related

My form is not working, please do tell me where it went wrong(PHP validation)

I would like to know where in my code the form went wrong.
<?php
if(isset($_POST['submit'])) {
$arrayName = array("TeacherA", "TeacherB", "TeacherC" , "TeacherD", "TeacherE");
$minimum = 5;
$maximum = 10;
$name = $_POST['yourName'];
$email = $_POST['yourEmail'];
if(strlen($name) < $minimum) {
echo "Your name should be longer than 5 characters";
}
if(strlen($name) > $maximum) {
echo "Your name should not be longer than 10 characters";
}
if(!in_array($name,$arrayName)){
echo "Please do register with us before you can login";
} else {
echo "Welcome!";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blank</title>
</head>
<body>
<form action="form.php" method="post">
<label>Your Name: </label>
<input type="text" name="yourName"> <br>
<label for="">Your E mail:</label>
<input type="email" name="yourEmail" id=""><br>
<!-- <textarea name="yourMessage" id="" cols="30" rows="10"></textarea><br> -->
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
I run through the localhost, however, I could not get result that I wanted.
The result that I wanted is if I didn't enter the names in the "Your Name" field, then it should show the result:
Please do register with us before you can login
if the the "Your Name" field is empty, then its strlen($name) should be 0 and the first if statement is true and it will show Your name should be longer than 5 characters
you can try this :
<?php
if (isset($_POST['submit'])) {
$arrayName = array("TeacherA", "TeacherB", "TeacherC", "TeacherD", "TeacherE");
$minimum = 5;
$maximum = 10;
$name = $_POST['yourName'];
$email = $_POST['yourEmail'];
if (empty($name)) {
echo "Please do register with us before you can login";
} else {
if (strlen($name) < $minimum) {
echo "Your name should be longer than 5 characters";
} else {
if (strlen($name) > $maximum) {
echo "Your name should be less than 10 characters";
} else {
if (in_array($name, $arrayName)) {
echo "Welcome!";
} else {
echo "Your login is not correct";
}
}
}
}
}
?>
i used empty() to test if the field empty
and i used if-else statements because i want the script to stop if it founds a 'true' condition
in your script you can use return; but that will exit the rest of your script
have a nice code :)
Try this:
if(!isset($name)){
echo "Please do register with us before you can login";
}
else{
echo "Welcome";
}
And also:
<input type="text" name="yourName" required>

"Fatal error: Can't use function return value in write context" in PHP

Why does this happen:
Fatal error: Can't use function return value in write context in C:\xampp\htdocs\phps\site.php on line 14
Code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form action="site.php" method="post">
enter your name :<input type="text" name="fn">
enter your age :<input type="number" name="age">
<input type="submit" value="click me" name="submit">
</form>
<?php
if (isset($_POST["submit"]) && strlen($_POST["fn"]) = 0 &&
strlen($_POST["age"]) = 0) {
echo "enter your name and your age";
}
elseif (isset($_POST["submit"]) && strlen($_POST["fn"]) > 0 &&
strlen($_POST["age"]) = 0) {
echo "enter your age";
}
elseif (isset($_POST["submit"]) && strlen($_POST["fn"]) = 0 &&
strlen($_POST["age"]) > 0) {
echo "enter your name";
}
else {
$name = $_POST["fn"];
$age = $_POST["age"];
echo "my name is $name<br>";
echo "i am $age years old";
}
?>
</body>
</html>
to show text boxes
A single = means assignment. You need to use == to check for equality:
// WRONG
strlen($_POST["fn"]) = 0
// RIGHT
strlen($_POST["fn"]) == 0

PHP form reloads on submit, but resets variables

I've been tasked to create a guessing game. A random number is generated and the user tries to guess it. It tells you if you should try a larger or a smaller number, and eventually the user guesses the correct number.
<?php
session_start();
if(empty($_SESSION['num_to_guess'])) { $_SESSION['num_to_guess'] = mt_rand(1,99); }
if (!isset($_POST['guess'])) {
$message = "Welcome to the Odd Number Guessing Game!";
}
elseif (!is_numeric($_POST['guess'])) { //is not numeric
$message = "I don't understand that response. Please enter a number.";
}
elseif ($_POST['guess'] == $_SESSION['num_to_guess']) { //matches
$message = "Well done! You've found the secret number. Now try to guess another.";
$_SESSION['num_to_guess'] = mt_rand(1,99);
}
elseif ($_POST['guess'] < $_SESSION['num_to_guess']) { //greater
$message = "Try a larger number!";
}
elseif ($_POST['guess'] > $_SESSION['num_to_guess']) { //lesser
$message = "Try a smaller number!";
}
else {
$message = "I'm terribly confused.";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Odd Number Guessing Machine!</title>
</head>
<body>
<h1><?php echo $message; ?>
<?php echo $_SESSION['num_to_guess']; ?>
</h1>
<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "POST">
<p><label for="guess">Try to guess an odd number between 1 and 99:</label> <br/>
<input type="text" id="guess" name="guess" /></p>
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</body>
</html>
My problem is the form reloads every time the user submits the data, thereby changing the random number. I'm sure there is a workaround but I just can't seem to find it.
I want to generate a new number ONLY when the correct number is guessed. I tried adding rand() function on the elseif loop where the number is guessed correctly, but that doesn't work.
Please help. :)
Now browser compatible
<?php
session_start();
$url_of_page = $_SERVER['REQUEST_URI'];
if(!isset($_SESSION['correct_number'])){
// Create random number only when the previous one has been correctly guessed
$number_to_guess = rand(0,9);
$_SESSION['correct_number'] = $number_to_guess;
}
if(isset($_SESSION['correct_number'])){
$num_to_guess = $_SESSION['correct_number'];
}
if(isset($_POST['guess'])){
$guessed_number = trim($_POST['guess']);
$reg_exp = '/^([0-9]+)$/';
$reg_exp_match = preg_match($reg_exp,$guessed_number);
}
if(isset($_POST['submit'])){
if(isset($reg_exp_match)){
if(!$reg_exp_match){
$message = "Enter a number";
}else{
if($guessed_number < $num_to_guess){
// is small
$message = "Try a larger number!";
}elseif($guessed_number > $num_to_guess){
// is large
$message = "Try a smaller number!";
}elseif($guessed_number == $num_to_guess){
//matches
$message = "Well done...You got it";
$new_game = TRUE;
unset($_SESSION['correct_number']);
// A new number can now be created
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Odd Number Guessing Machine!</title>
</head>
<body>
<h3>Welcome to the Guessing Machine!</h3>
<p>
<?php
if(isset($new_game) && ($new_game == TRUE)){ // The correct number
if(isset($message) && isset($url_of_page)){
echo $message . '. Start a new game';
}
}else{ // Not the correct number
if(isset($message)){ echo $message; }
}
?>
</p>
<form action="<?php if(isset($url_of_page)){ echo $url_of_page; } ?>" method="POST">
<p>
<label for="guess">Enter a number, 0 to 9:</label> <br/>
<input type="text" id="guess" name="guess" />
</p>
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</body>
</html>

PHP Guessing Number

This is a random number guessing game between 1 and 100.
I am stuck on the guessing number part. The code doesn't work, whatever number I put it just show me the message "Your number is lower!".I need help.
This is what I have so far.
<?php
$x = rand(1, 100);
$num = '';
if (isset($_POST['submit'])) {
if ($num < $x)
{
echo " Your number is lower! <br />";
} elseif ($num > $x)
{
echo " Your number is higher! <br />";
} elseif ($num == $x)
{
echo " Congratulations! You guessed the hidden number. <br />";
} else
{
echo " You never set a number! <br />";
}
}
?>
<p>
<form action="" method="post">
<input type="text" name="num">
<button type="submit" name="submit">Guess</button>
<button type="reset" name="Reset">Reset</button>
</form>
</p>
You will always get lower because There isn't any value inside you $num.So, You need to assigning $num
<?php
$x = rand(1, 100);
$num = '';
if (isset($_POST['submit'])) {
$num = $_POST['num']; // Add this to set value for $num variable
if ($num < $x)
{
echo " Your number is lower! <br />";
} elseif ($num > $x)
{
echo " Your number is higher! <br />";
} elseif ($num == $x)
{
echo " Congratulations! You guessed the hidden number. <br />";
} else
{
echo " You never set a number! <br />";
}
}
?>
You need to set the num after submit the form.
if (isset($_POST['submit'])) {
$num = $_POST['num'];
if ($num < $x)
{
echo " Your number is lower! <br />";
} elseif ($num > $x)
{
echo " Your number is higher! <br />";
} elseif ($num == $x)
{
echo " Congratulations! You guessed the hidden number. <br />";
} else
{
echo " You never set a number! <br />";
}
}
// value of $x is in between 1 and 100 means greater than 0 and lesser than 101
$x = rand(1, 100);
// $num value is empty and while you attempt to compare with this this will converted to zero
$num = '';
// thus $num<$x always returns true, thats the mistake you need to assign the submitted value to the $num variable like
$num=$_POST['num'];
// put above line just before the if($num<$x)
This would be a lot easier if you had it as a switch/case statement:
$x = rand(1,1000);
if(isset($_POST['submit'])) {
$num = $_POST['num'];
switch($num) {
case ($num < $x):
echo " Your number is lower! <br />";
break;
case ($num > $x):
echo " Your number is higher! <br />";
break;
case ($num == $x):
echo " Congratulations! You guessed the hidden number. <br />";
break;
case '':
echo " You never set a number! <br />";
break;
}
}
Example/Demo
You have set $num = '' (a fix empty string) and compare it with a random generated number. It's obvious that this can not work. You have to read $_POST['num'] in PHP.
This will work, however, not as probably expected. You will need to either store the random number in a session or easier add a hidden field to the form. Otherwise the random number will change on each try.
on 22.6.2021 i wrote a Guess Number in Range [0 .. aMaxIntValue] sample Web Application using PHP.
i think the following code may help you.
the code is kept in a Single PHP file.
it generates #4 HTML pages ...
the 1st initial page is used to collect application parameters (e.g. the Max Int Number to Guess)
the 2nd page is the Main Play Game Page where the user is asked to Guess the Secret Number or to Reset Game. this page shows the previous user guesses and some tips for the user about the guess
the 3rd page is used to notify the user looses game (that is he has no more tries left)
the 4th page is used to notify the user wins the game (that is the Guess was OK)
the Number of Tries left to the User is computed using the values range [0 .. max]
the Secret Number to Guess is a random generated integer number
this is the PHP + HTML code ...
<? php ?>
<? php ?>
<?php
session_start();
error_reporting (E_PARSE | E_COMPILE_ERROR);
function ResetGame()
{
unset ( $_SESSION['theMaxNumber'] );
}
function InitGame()
{
$_SESSION['theNumberToGuess'] = mt_rand (0, $_SESSION['theMaxNumber']);
$_SESSION['theMaxNumberOfTries'] = floor ( log ($_SESSION['theMaxNumber'], 2) ) + 1;
$_SESSION['theUserTriesCount'] = 0;
$_SESSION['thePrevGuessesString'] = '';
$_SESSION['theUserGuess'] = 0;
}
function ComputeNumberOfTriesLeft()
{
return $_SESSION['theMaxNumberOfTries'] - $_SESSION['theUserTriesCount'];
}
function IsNoMoreTriesLeft()
{
return ComputeNumberOfTriesLeft() <= 0;
}
$aCanPlayGame = false;
$aUserSubmittedGuess = false;
$aIsNoMoreTriesLeft = false;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ( isset ($_REQUEST['playgame']) ) {
$_SESSION['theMaxNumber'] = intval($_REQUEST['theMaxNumber']);
// init game ...
InitGame();
$aCanPlayGame = true;
}
elseif ( isset ($_REQUEST['submituserguess']) ) {
$aCanPlayGame = true;
$aUserSubmittedGuess = true;
$_SESSION['theUserGuess'] = intval($_REQUEST['theUserGuess']);
}
elseif ( isset ($_REQUEST['resetgame']) ) {
ResetGame();
}
else {
ResetGame();
}
}
else {
ResetGame();
}
// check a play
$aUserShouldTryLower = false;
$aUserShouldTryHigher = false;
$aUserWins = false;
$aUserLooses = false;
if ($aCanPlayGame) {
$aIsNoMoreTriesLeft = IsNoMoreTriesLeft();
if ( ! $aIsNoMoreTriesLeft ) {
// user have tries left
if ($aUserSubmittedGuess) {
// check user guess ...
$aUserGuess = intval($_SESSION['theUserGuess']);
if ( $aUserGuess > $_SESSION['theNumberToGuess'] ) {
$aUserShouldTryLower = true;
}
elseif ( $aUserGuess < $_SESSION['theNumberToGuess'] ) {
$aUserShouldTryHigher = true;
}
else {
$aUserWins = true;
// also reset game
ResetGame();
}
// add the current guess to the prev guesses string
$_SESSION['thePrevGuessesString'] .= $_SESSION['theUserGuess'] . ' ';
// increase the user tries count
++ $_SESSION['theUserTriesCount'];
// check tries count
if ( ! $aUserWins ) {
$aIsNoMoreTriesLeft = IsNoMoreTriesLeft();
if ($aIsNoMoreTriesLeft) {
// this was the last try
// no more tries left
$aUserLooses = true;
// also reset game
ResetGame();
}
}
}
}
else {
// no more tries left
$aUserLooses = true;
// also reset game
ResetGame();
}
}
?>
<?php if ($aUserLooses): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Sorry, you loose the game</p>
<p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
<form method="post">
<input type="submit" name="resetgame" value="reset game">
</form>
</body>
</html>
<?php elseif ($aUserWins): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Congrats, you Win the Game</p>
<p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
<form method="post">
<input type="submit" name="resetgame" value="reset game">
</form>
</body>
</html>
<?php elseif ($aCanPlayGame): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>the Max Number is <?php echo $_SESSION['theMaxNumber']; ?></p>
<p>Guess a Number in the Range [ 0 .. <?php echo ($_SESSION['theMaxNumber']); ?> ]</p>
<p>[DEBUG] the secret number to guess is <?php echo $_SESSION['theNumberToGuess']; ?></p>
<p>you have <?php echo ComputeNumberOfTriesLeft(); ?> tries left</p>
<form method="post">
<label for="theUserGuess">Enter your Guess: </label>
<input type="text" id="theUserGuess" name="theUserGuess">
<input type="submit" name="submituserguess" value="Guess">
<input type="submit" name="resetgame" value="reset game">
</form>
<p>Prev Guesses: <?php echo $_SESSION['thePrevGuessesString']; ?> </p>
<p>
<?php
if ($aUserShouldTryLower) {
echo 'you should try a lower < guess';
}
elseif ($aUserShouldTryHigher) {
echo 'you should try a higher > guess';
}
else {
echo 'no guess';
}
?>
</p>
</body>
</html>
<?php else: ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Guess a Number from (0) to ... </p>
<form method="post">
<input id="theMaxNumber" name="theMaxNumber">
<input type="submit" name="playgame" value="play game">
</form>
</body>
</html>
<?php endif; ?>
<? php ?>
that's all folks ...

(PHP) Adding a 'guess counter' to a random number game

I need to modify a block of code and add a counter regarding how many times it took the user to guess the right number.
I was wondering how it would be properly implemented into my code.
This is what I have so far.
<?php
if (!isset($_POST["guess"])) {
$message = "Welcome to the guessing machine!";
$count++; //Declare the variable $count to increment by 1.
$_POST["numtobeguessed"] = rand(0,1000);
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
} else { // must be equivalent
$message = "Well done! You guessed the right number in ".$count." attempt(s)!";
//Include the $count variable to the $message to show the user how many tries to took him.
}
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
You have to use PHP Sessions to keep track of the count.
All you have to do is initialize counter to 0 and have it increment when the user guesses a number
<?php
session_start();
if (!isset($_POST["guess"])) {
$_SESSION["count"] = 0; //Initialize count
$message = "Welcome to the guessing machine!";
$_POST["numtobeguessed"] = rand(0,1000);
echo $_POST["numtobeguessed"];
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
$_SESSION["count"]++; //Declare the variable $count to increment by 1.
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
$_SESSION["count"]++; //Declare the variable $count to increment by 1.
} else { // must be equivalent
$_SESSION["count"]++;
$message = "Well done! You guessed the right number in ".$_SESSION["count"]." attempt(s)!";
unset($_SESSION["count"]);
//Include the $count variable to the $message to show the user how many tries to took him.
}
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
This should work for you.
$count = isset($_POST['count']) ? $_POST['count'] : 0; //Use post value if defined. If not set to 1.
if (!isset($_POST["guess"])) {
$message = "Welcome to the guessing machine!";
$_POST["numtobeguessed"] = rand(0,1000);
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
} else { // must be equivalent
$message = "Well done! You guessed the right number in ".$count." attempt(s)!";
//Include the $count variable to the $message to show the user how many tries to took him.
}
$count++;
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<input type="hidden" name="count"
value="<?php echo $count; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
on 22.6.2021 i wrote a Guess Number in Range [0 .. aMaxIntValue] sample Web Application using PHP. i think the following code may help you. the code is kept in a Single PHP file. it generates #4 HTML pages ...
the 1st initial page is used to collect application parameters (e.g. the Max Int Number to Guess)
the 2nd page is the Main Play Game Page where the user is asked to Guess the Secret Number or to Reset Game. this page shows the previous user guesses and some tips for the user about the guess
the 3rd page is used to notify the user looses game (that is he has no more tries left)
the 4th page is used to notify the user wins the game (that is the Guess was OK)
the Number of Tries left to the User is computed using the values range [0 .. max]
the Secret Number to Guess is a random generated integer number
this is the PHP + HTML code ...
<?php
session_start();
error_reporting (E_PARSE | E_COMPILE_ERROR);
function ResetGame()
{
unset ( $_SESSION['theMaxNumber'] );
}
function InitGame()
{
$_SESSION['theNumberToGuess'] = mt_rand (0, $_SESSION['theMaxNumber']);
$_SESSION['theMaxNumberOfTries'] = floor ( log ($_SESSION['theMaxNumber'], 2) ) + 1;
$_SESSION['theUserTriesCount'] = 0;
$_SESSION['thePrevGuessesString'] = '';
$_SESSION['theUserGuess'] = 0;
}
function ComputeNumberOfTriesLeft()
{
return $_SESSION['theMaxNumberOfTries'] - $_SESSION['theUserTriesCount'];
}
function IsNoMoreTriesLeft()
{
return ComputeNumberOfTriesLeft() <= 0;
}
$aCanPlayGame = false;
$aUserSubmittedGuess = false;
$aIsNoMoreTriesLeft = false;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ( isset ($_REQUEST['playgame']) ) {
$_SESSION['theMaxNumber'] = intval($_REQUEST['theMaxNumber']);
// init game ...
InitGame();
$aCanPlayGame = true;
}
elseif ( isset ($_REQUEST['submituserguess']) ) {
$aCanPlayGame = true;
$aUserSubmittedGuess = true;
$_SESSION['theUserGuess'] = intval($_REQUEST['theUserGuess']);
}
elseif ( isset ($_REQUEST['resetgame']) ) {
ResetGame();
}
else {
ResetGame();
}
}
else {
ResetGame();
}
// check a play
$aUserShouldTryLower = false;
$aUserShouldTryHigher = false;
$aUserWins = false;
$aUserLooses = false;
if ($aCanPlayGame) {
$aIsNoMoreTriesLeft = IsNoMoreTriesLeft();
if ( ! $aIsNoMoreTriesLeft ) {
// user have tries left
if ($aUserSubmittedGuess) {
// check user guess ...
$aUserGuess = intval($_SESSION['theUserGuess']);
if ( $aUserGuess > $_SESSION['theNumberToGuess'] ) {
$aUserShouldTryLower = true;
}
elseif ( $aUserGuess < $_SESSION['theNumberToGuess'] ) {
$aUserShouldTryHigher = true;
}
else {
$aUserWins = true;
// also reset game
ResetGame();
}
// add the current guess to the prev guesses string
$_SESSION['thePrevGuessesString'] .= $_SESSION['theUserGuess'] . ' ';
// increase the user tries count
++ $_SESSION['theUserTriesCount'];
// check tries count
if ( ! $aUserWins ) {
$aIsNoMoreTriesLeft = IsNoMoreTriesLeft();
if ($aIsNoMoreTriesLeft) {
// this was the last try
// no more tries left
$aUserLooses = true;
// also reset game
ResetGame();
}
}
}
}
else {
// no more tries left
$aUserLooses = true;
// also reset game
ResetGame();
}
}
?>
<?php if ($aUserLooses): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Sorry, you loose the game</p>
<p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
<form method="post">
<input type="submit" name="resetgame" value="reset game">
</form>
</body>
</html>
<?php elseif ($aUserWins): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Congrats, you Win the Game</p>
<p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
<form method="post">
<input type="submit" name="resetgame" value="reset game">
</form>
</body>
</html>
<?php elseif ($aCanPlayGame): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>the Max Number is <?php echo $_SESSION['theMaxNumber']; ?></p>
<p>Guess a Number in the Range [ 0 .. <?php echo ($_SESSION['theMaxNumber']); ?> ]</p>
<p>[DEBUG] the secret number to guess is <?php echo $_SESSION['theNumberToGuess']; ?></p>
<p>you have <?php echo ComputeNumberOfTriesLeft(); ?> tries left</p>
<form method="post">
<label for="theUserGuess">Enter your Guess: </label>
<input type="text" id="theUserGuess" name="theUserGuess">
<input type="submit" name="submituserguess" value="Guess">
<input type="submit" name="resetgame" value="reset game">
</form>
<p>Prev Guesses: <?php echo $_SESSION['thePrevGuessesString']; ?> </p>
<p>
<?php
if ($aUserShouldTryLower) {
echo 'you should try a lower < guess';
}
elseif ($aUserShouldTryHigher) {
echo 'you should try a higher > guess';
}
else {
echo 'no guess';
}
?>
</p>
</body>
</html>
<?php else: ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Guess a Number from (0) to ... </p>
<form method="post">
<input id="theMaxNumber" name="theMaxNumber">
<input type="submit" name="playgame" value="play game">
</form>
</body>
</html>
<?php endif; ?>
that's all folks ...

Categories