<< Click to Display Table of Contents >> Navigation: Analogues > JavaScript > Guess Web Application |
A simple number-guessing game where the user inputs a value between 1 and 100. After each guess, the application displays feedback and tracks the number of attempts until the correct number is found.
Create the Project Directory
To begin, create a new directory GuessJS for the project in C:\src\IW17\Demos\.
Navigate to this folder — it will contain all files related to the GuessJS application.
Create the HTML Layout
Inside the GuessJS directory, create a file named index.html.
This file defines the structure and layout of the web application.
Paste the following content into it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Guess the Number</title>
</head>
<body>
<div>
<h1>Guess the Number</h1>
<div>
<!-- Input field for the user's guess -->
<input id="guessInput" type="text" placeholder="Enter a number (1-100)">
<!-- Message displayed to the user (too high/low/correct) -->
<p id="message"></p>
<!-- Attempt counter -->
<p id="count">Attempt #0</p>
<!-- Button to submit the guess -->
<button id="guessButton">Guess</button>
</div>
</div>
<!-- JavaScript file with game logic -->
<script src="game.js"></script>
</body>
</html>
Add Game Logic in JavaScript
Next, create a file named game.js in the same folder. This file will contain the full game logic.
Paste the following JavaScript code:
let guess = '';
let message = '';
let count = 0;
// Generate a random number between 1 and 100
let magicNo = Math.floor(Math.random() * 100) + 1;
let isButtonEnabled = true;
// Get references to HTML elements
const guessInput = document.getElementById('guessInput');
const messageElement = document.getElementById('message');
const countElement = document.getElementById('count');
const guessButton = document.getElementById('guessButton');
// Focus input and check for a preset number from URL (?MagicNo=42)
window.onload = () => {
guessInput.focus();
const params = new URLSearchParams(window.location.search);
const magicNoParam = params.get('MagicNo');
if (magicNoParam && !isNaN(parseInt(magicNoParam))) {
magicNo = parseInt(magicNoParam);
}
};
// Handle user guess when button is clicked or Enter is pressed
const handleGuess = (event) => {
// Debug: Show the correct number if Shift key is held
if (event.shiftKey) {
alert(`The magic number is: ${magicNo}`);
return;
}
message = '';
messageElement.textContent = '';
const guessValue = parseInt(guessInput.value);
// Check if input is a number
if (isNaN(guessValue)) {
message = `${guessInput.value} is not a number.`;
} else if (guessValue < 1 || guessValue > 100) {
message = `${guessValue} is out of range (1–100).`;
} else {
count++;
// Compare with magic number and update message
if (guessValue < magicNo) {
message = `${guessValue} is too low.`;
} else if (guessValue > magicNo) {
message = `${guessValue} is too high.`;
} else if (guessValue === magicNo) {
alert('Congratulations! You guessed the number!');
isButtonEnabled = false;
guessButton.disabled = true;
guessInput.disabled = true;
}
}
// Update UI
messageElement.textContent = message;
countElement.textContent = `Attempt #${count}`;
guessInput.value = '';
guessInput.focus();
};
// Update the guess variable on each input
guessInput.addEventListener('input', (e) => {
guess = e.target.value;
});
// Trigger handleGuess when button is clicked
guessButton.addEventListener('click', handleGuess);
// Trigger handleGuess when Enter key is pressed
guessInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
handleGuess(e);
}
});
Launching a web application
Before testing the application, ensure that the Apache Server is running and properly configured.
If it hasn't been started yet, launch it now to make the project accessible in the browser at the following URL:
http://127.0.0.1/demo/GuessJS/
This is what the completed web application looks like in the browser:
See also