×
Namespaces

Variants
Actions

HTML & PHP - Number guessing game - simple

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Article
Created: Maveric (27 Jun 2012)
Last edited: BuildNokia (13 Jun 2014)

This article explains how to create a simple number guessing game in HTML and PHP.


Contents

Introduction

This article shows how to create a number guessing game with HTML and embedded PHP. The game concept is simple; the user is to guess a computer generated "secret" number between 1 and 10. User will be told if the guess was lower or higher than the "secret" number.

Prerequisites

  • Code editor of your choise
  • PHP installed
  • Web browser

Implementation

We will only need to create one file for this example, and we are saving it with the name "game.php". You can choose any name you want ofcourse.

Example code

<html>
<head>
<title>Number guessing game example</title>
</head>
<body>
<?php
if(isset($_POST['posted']))
{
$user_guess = $_POST['guess'];
$number = rand(1,10);
if($user_guess > $number)
{
echo "<h2>The number you guessed is higher than the secret: $number</h1><br/>";
echo "Try again";
}
else if($user_guess < $number)
{
echo "<h1>The number you guessed is lower than the secret: $number</h1>";
echo "Try again";
}
else
{
echo "<h1>You had guessed right!"</h1>
}
 
}
?>
<form action="game.php" method="post">
Please try to guess what is the secret number, between 1 and 10:
<input type="text" name="guess" /><br />
<input type="hidden" name="true" name="posted" />
<input type="submit" value="submit" />
</form>
</body>
</html>


Tested on

Google Chrome 19.0.1084.52 m

Summary

You could easily extend this game.

This page was last modified on 13 June 2014, at 02:31.
79 page views in the last 30 days.
×