Share
Explore

JavaScript Lab: Guessing Game CSD2103

Learning Outcome:

Write an HTML file and corresponding javascript file to make a number guessing game between human user and computer.
Use CSS to Style your Page.

Starter:

An HTML file and a corresponding JavaScript file to create a simple number guessing game. The computer will generate a random number between 1 and 100, and the user will try to guess the number.
Create an HTML file, index.html, with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Number Guessing Game</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Number Guessing Game</h1>
<p>Try to guess the number between 1 and 100:</p>
<input type="number" id="userGuess" min="1" max="100">
<button id="submitGuess">Submit Guess</button>
<p id="message"></p>
<script src="script.js"></script>
</body>
</html>
Next, create a JavaScript file, script.js, with the following content:
javascript
Copy code
document.getElementById('submitGuess').addEventListener('click', function () {
const randomNumber = Math.floor(Math.random() * 100) + 1;
const userGuess = parseInt(document.getElementById('userGuess').value);
let message;

if (userGuess < 1 || userGuess > 100) {
message = 'Invalid input. Please enter a number between 1 and 100.';
} else if (userGuess === randomNumber) {
message = 'Congratulations! You guessed the correct number!';
} else if (userGuess < randomNumber) {
message = 'Your guess is too low. The correct number was ' + randomNumber + '.';
} else {
message = 'Your guess is too high. The correct number was ' + randomNumber + '.';
}

document.getElementById('message').textContent = message;
});
This code will create a simple number guessing game where the user can input a number and click the "Submit Guess" button. The script will generate a random number between 1 and 100 and compare it with the user's guess. The result will be displayed as a message below the button.
You can also create an optional CSS file, style.css, to style the game:
css
Copy code
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f0f0f0;
padding: 50px;
}

input[type="number"] {
width: 50px;
text-align: center;
}

button {
background-color: #4CAF50;
color: white;
padding: 5px 15px;
border: none;
cursor: pointer;
}

button:hover {
background-color: #45a049;
}
This CSS file will style the game with a simple design and make the "Submit Guess" button change color when hovered.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.