interstellar_website/secret/guessMyNumber/game.js

55 lines
2.1 KiB
JavaScript
Raw Normal View History

2025-01-04 21:00:39 +01:00
'use strict';
const targetNum = Math.trunc(Math.random() * 20) + 1;
let highScore = Number(localStorage.getItem('highscore')) || 0;
let userGuess = 10; // Default guess
let currScore = 20;
const screenEl = document.querySelector('.screen');
const msgEl = document.querySelector('.message');
const guessInput = document.querySelector('#guess');
const scoreEl = document.querySelector('.score');
const highScoreEl = document.querySelector('.highScore');
const checkBtn = document.querySelector('#check');
const restartBtn = document.querySelector('#restart');
const incBtn = document.querySelector('#up');
const decBtn = document.querySelector('#down');
const setMsg = msg => msgEl.textContent = msg;
const setScore = score => scoreEl.textContent = `Score: ${currScore = score}`;
const setHighScore = () => {
highScoreEl.textContent = `Highscore: ${highScore}`;
localStorage.setItem('highscore', highScore);
};
const changeColor = color => screenEl.style.backgroundColor = color;
checkBtn.addEventListener('click', () => {
userGuess = Number(guessInput.textContent);
if (!userGuess || userGuess < 1 || userGuess > 20) {
setMsg("Please enter a valid number between 1 and 20.");
} else if (userGuess === targetNum) {
highScore = Math.max(highScore, currScore);
setHighScore();
setMsg(currScore !== 20 ? 'Correct Number!' : 'Are you sure you didn\'t cheat?');
changeColor(currScore !== 20 ? '#1ba100' : '#FFC300');
} else {
setMsg(userGuess > targetNum ? 'Too High!' : 'Too Low!');
if (currScore > 1) {
setScore(currScore - 1);
} else {
setScore(1);
setMsg("You lost the game!");
changeColor('#a10000');
}
}
});
restartBtn.addEventListener('click', () => location.reload());
incBtn.addEventListener('click', () => guessInput.textContent = Math.min(Number(guessInput.textContent) + 1, 20));
decBtn.addEventListener('click', () => guessInput.textContent = Math.max(Number(guessInput.textContent) - 1, 1));
guessInput.textContent = userGuess;
setMsg('Guess a number');
setScore(currScore);
setHighScore();