body {
font-family: ‘Arial’, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
color: #333;
}
.guessField {
margin-right: 10px;
}
.guessSubmit {
cursor: pointer;
}
.resultParas p {
margin: 5px 0;
}
.lowOrHi {
color: #666;
}
.lastResult {
color: white;
padding: 3px;
}
#resetButton {
margin-top: 20px;
padding: 10px 20px;
font-size: 16px;
background-color: #333;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
Number Guessing Game
We have selected a random number between 1 and 1000. See if you can guess it in 10 turns or fewer. We’ll tell you if your guess was too high or too low.
let randomNumber = Math.floor(Math.random() * 1000) + 1;
let guesses = document.querySelector(‘.guesses’);
let lastResult = document.querySelector(‘.lastResult’);
let lowOrHi = document.querySelector(‘.lowOrHi’);
let guessSubmit = document.querySelector(‘.guessSubmit’);
let guessField = document.querySelector(‘.guessField’);
let guessCount = 1;
let resetButton = document.getElementById(‘resetButton’);
function checkGuess() {
let userGuess = Number(guessField.value);
if (guessCount === 1) {
guesses.textContent = ‘Previous guesses: ‘;
}
guesses.textContent += userGuess + ‘ ‘;
if (userGuess === randomNumber) {
lastResult.textContent = ‘Congratulations! You got it right!’;
lastResult.style.backgroundColor = ‘green’;
lowOrHi.textContent = ”;
setGameOver();
} else if (guessCount === 10) {
lastResult.textContent = ‘!!!GAME OVER!!!’;
setGameOver();
} else {
lastResult.textContent = ‘Wrong!’;
lastResult.style.backgroundColor = ‘red’;
if(userGuess randomNumber) {
lowOrHi.textContent = ‘Last guess was too high!’;
}
}
guessCount++;
guessField.value = ”;
guessField.focus();
}
guessSubmit.addEventListener(‘click’, checkGuess);
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton.style.display = ‘block’;
resetButton.addEventListener(‘click’, resetGame);
}
function resetGame() {
guessCount = 1;
let resetParas = document.querySelectorAll(‘.resultParas p’);
for(let i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = ”;
}
resetButton.style.display = ‘none’;
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = ”;
guessField.focus();
lastResult.style.backgroundColor = ‘white’;
randomNumber = Math.floor(Math.random() * 1000) + 1;
}