java-web/examples/chapter02/065-hangman game/script.js

126 lines
3.1 KiB
JavaScript
Raw Permalink Normal View History

2024-09-30 08:10:21 +08:00
const wordElement = document.getElementById("word");
const wrongLettersElement = document.getElementById("wrong-letters");
const playAgainButton = document.getElementById("play-button");
const popup = document.getElementById("popup-container");
const notification = document.getElementById("notification-container");
const finalMessage = document.getElementById("final-message");
const finalMessageRevealWord = document.getElementById(
"final-message-reveal-word"
);
const figureParts = document.querySelectorAll(".figure-part");
const words = [
"application",
"programming",
"interface",
"wizard",
"element",
"prototype",
"callback",
"undefined",
"arguments",
"settings",
"selector",
"container",
"instance",
"response",
"console",
"constructor",
"token",
"function",
"return",
"length",
"type",
"node",
];
let selectedWord = words[Math.floor(Math.random() * words.length)];
let playable = true;
const correctLetters = [];
const wrongLetters = [];
function displayWord() {
wordElement.innerHTML = `
${selectedWord
.split("") // to array
.map(
(letter) => `
<span class="letter">
${correctLetters.includes(letter) ? letter : ""}
</span>
`
)
.join("")}
`; // to string
const innerWord = wordElement.innerText.replace(/\n/g, "");
if (innerWord === selectedWord) {
finalMessage.innerText = "Congratulations! You won! 😃";
finalMessageRevealWord.innerText = "";
popup.style.display = "flex";
playable = false;
}
}
function updateWrongLettersElement() {
wrongLettersElement.innerHTML = `
${wrongLetters.length > 0 ? "<p>Wrong</p>" : ""}
${wrongLetters.map((letter) => `<span>${letter}</span>`)}
`;
figureParts.forEach((part, index) => {
const errors = wrongLetters.length;
index < errors
? (part.style.display = "block")
: (part.style.display = "none");
});
if (wrongLetters.length === figureParts.length) {
finalMessage.innerText = "Unfortunately you lost. 😕";
finalMessageRevealWord.innerText = `...the word was: ${selectedWord}`;
popup.style.display = "flex";
playable = false;
}
}
function showNotification() {
notification.classList.add("show");
setTimeout(() => {
notification.classList.remove("show");
}, 2000);
}
window.addEventListener("keypress", (e) => {
if (playable) {
const letter = e.key.toLowerCase();
if (letter >= "a" && letter <= "z") {
if (selectedWord.includes(letter)) {
if (!correctLetters.includes(letter)) {
correctLetters.push(letter);
displayWord();
} else {
showNotification();
}
} else {
if (!wrongLetters.includes(letter)) {
wrongLetters.push(letter);
updateWrongLettersElement();
} else {
showNotification();
}
}
}
}
});
playAgainButton.addEventListener("click", () => {
playable = true;
correctLetters.splice(0);
wrongLetters.splice(0);
selectedWord = words[Math.floor(Math.random() * words.length)];
displayWord();
updateWrongLettersElement();
popup.style.display = "none";
});
// Init
displayWord();