Lets Make A Game In PHP - Part 1



We make a simple number guessing game with few lines of PHP and HTML code. The goal of the game is to find the secret number generated by server using rand() function.

Random Number Generation

Most games need to do actions based on random conditions . PHP provide rand() function to generate random numbers.

day_8_ex_1.php


PHP Code:
<?php

echo 'My Random Number is: ' rand(1,100);
Above code will generate a random number between 1 and 100.

Modify the script, change numbers 1 and 100, so that you can have random number in different range. For example, if we are making Snakes and Ladders game, we will have 1 to 6 as result when we throw (or rolls) the dice. In that cause, above example will be




PHP Code:
<?php

echo '<h1>Computer as Dice</h1>';
echo 
'<p>Use it when your Dice broken.</p>';

echo 
'Your number is: ' rand(1,6);


day_8_ex_2.php

Time to write our own Number Guessing Game. Try to understand the code, if you don't understand any part of the code, ask in the forum. Don't worry if you don't understand the code, we will be working on it in next few days, you will eventually get used to the code

PHP Code:
<html>
<body>

<h1>Number Guessing Game.</h1>

<?php

if (isset($_GET['secretNumber'])) {
    
$secretNumber $_GET['secretNumber'];
} else {
    
$secretNumber rand(1,10);
}

if (isset(
$_GET['userNumber'])) {
    
$userNumber $_GET['userNumber'];

    if (
$secretNumber $userNumber) {
        echo 
'<h1 style="color:red">Your number is too SMALL.</h1>';
    } else if (
$secretNumber $userNumber) {
        echo 
'<h1 style="color:blue">Your number is too BIG.</h1>';
    } else {
        echo 
'<h1 style="color:green">You win the game.</h1>';
    }
}

?>

<form method="GET" action="">
    Enter Number: <input name="userNumber" type="text">
    <button type="submit">Check</button>
    <input type="hidden" name="secretNumber" value="<?php echo $secretNumber?>">
</form>

<h2>How to Play:</h2>

<pre>
* Server will pick a secret number between 1 and 10.
* You guess what number it is.
* If your guess is too high or too low, Server will give you a hint.
* See how many turns it takes you to win!
</pre>

</body>
</html>
This is simple game, there are multiple way to hack and win this game, this is not meant to play, just for learning.

Tomorrow we will discuss how to make this game more secure, add some more features like how many try it take you to get the correct answer, this way game will be more interesting.

Exercise

* Update the script so that the random number range will be 1 to 100 instead of 1 to 10.