const words = [
{ word:
"javascript"
, hint:
"A programming language for the web"
},
{ word:
"giraffe"
, hint:
"A tall African mammal"
},
{ word:
"pizza"
, hint:
"A delicious Italian dish"
},
{ word:
"computer"
, hint:
"An electronic device for processing data"
},
{ word:
"elephant"
, hint:
"A large herbivorous mammal with tusks"
},
{ word:
"ocean"
, hint:
"A vast body of saltwater"
},
{ word:
"mountain"
, hint:
"A large landform that rises prominently"
},
{ word:
"sunflower"
, hint:
"A tall plant with large yellow flowers"
},
{ word:
"jazz"
, hint:
"A genre of music with improvisation and syncopation"
},
{ word:
"galaxy"
, hint:
"A system of millions or billions of stars"
}
];
let currentWord, currentHint, guessesLeft, timer;
function
startGame() {
resetGame();
updateWordAndHint();
timer = setInterval(() => {
const timerElement =
document.getElementById(
"timer"
);
const seconds =
parseInt(timerElement.textContent, 10);
if
(seconds === 0) {
endGame(
"Time's up! You ran out of time."
);
}
else
{
timerElement.textContent = seconds - 1;
}
}, 1000);
}
function
updateWordAndHint() {
const randomIndex =
Math.floor(Math.random() * words.length);
currentWord = words[randomIndex].word;
currentHint = words[randomIndex].hint;
document.getElementById(
"word"
).textContent =
"_ "
.repeat(currentWord.length);
document.getElementById(
"hint"
).
textContent = currentHint;
}
function
checkGuess() {
const guessInput =
document.getElementById(
"guess"
);
const userGuess =
guessInput.value.toLowerCase();
const error =
document.getElementById('error
');
if (userGuess === currentWord) {
error.innerHTML = "";
endGame("Congratulations! You guessed the correct word.");
}
else if(userGuess === ""){
error.innerHTML =
"Please enter a input text."
}
else {
guessesLeft--;
if (guessesLeft === 0) {
endGame("Sorry, you'
re out of guesses!");
}
else
{
document.getElementById(
"guesses"
).
textContent = guessesLeft;
error.innerHTML =
"Incorrect guess. Try again!"
;
}
}
guessInput.value =
""
;
}
function
resetGame() {
guessesLeft = 5;
document.getElementById(
"guesses"
).
textContent = guessesLeft;
document.getElementById(
"timer"
).
textContent = 15;
clearInterval(timer);
}
function
endGame(message) {
clearInterval(timer);
const flashMessage =
document.createElement(
"div"
);
flashMessage.className =
`fixed top-0 left-0 w-full h-full flex items-center
justify-center bg-black bg-opacity-75 text-white text-2xl`;
flashMessage.innerHTML =
`<p>
${message}
</p>
<p>
Correct answer: ${currentWord}
</p>`;
document.body.appendChild(flashMessage);
setTimeout(() => {
flashMessage.remove();
startGame();
}, 1000);
}
window.onload = startGame;