Post: [TuT] Guess A Number Game [TuT]
05-10-2011, 01:06 AM #1
(adsbygoogle = window.adsbygoogle || []).push({});
Originally posted by 039

Hey everyone,
This is just a little number guessing game.

Let's start.

Ok First of all we will make a simple html form.

    
<html>
<head>
<title>Guess The Number by $$infection$$</title>
</head>

<body>

<div align="center">
<h2> Guess the Number by $$infection$$</h2>
<form action="guess.php" method="post">
Guess a number between 1 and 10 <input type="text" name="number"><br />
<input type="submit" value="Guess">
</form>
</div>

</body>
</html>


I hope no one is confused with the above code as its simple HTML, but still some people will get confused with the form tags so lemme explain it for you.
We made a simple form and the action page is guess.php means that once the submit button is clicked it will go to guess.php page and the method is post.
The a simple user input area whose name is number. (Remember we need this name as in our next page we will make a variable for this.
After that we have a simple submit button whose value is Guess.


Ok write that code, our copy paste it in a notepad file and save it with any name but with .html extension. We will name it game.html.

PHP Page.
As you all see that our name of the php page is already defined in the above form named guess.php. So we will make a php page and name it guess.php
Here is the code. Just try to look at it we will be working on each line later.
    
<?php
$number = $_POST['number'];
$random = rand(1,10);

if ($number < $random) {
echo "<h2>Sorry your guess was high, the number is $random</h2>";
}
elseif ($number > $random) {
echo "<h2>Sorry your guess was too low, the number is $random</h2>";
}
else {
echo "<h2>Your guess was right and you won</h2>";
}
?>

Confused!!! Don't be. Here is what we did, we made a variable called $number and its value is being picked from the game.html page if you remember it, $_POST is a global variable used for picking up data from html forms if the POST method is used in it.
Next we created another variable called $random and its value is rand(1,10) which is a builtin php function used to create random numbers according to the info given and as you see we have declared it between 1 to 10 (You can always change the value to anything you want like 1,100 or anything else).
Then we have simply used if elseif and else.
First we check if $number is greater than $random the display that our guess was high, elseif $number is less than $random then display the guess was low, else display the guess was right and you won. Its simple common sense if a first value is not greater nor than less than second value then its equal to it.

Now save this page as guess.php and run it in your localhost pc or any PHP enabled webserver and play the game and enjoy.

Enjoy :pirate:



source You must login or register to view this content.

Copyright © 2024, NextGenUpdate.
All Rights Reserved.

Gray NextGenUpdate Logo