I had a task to create a simple hangman game using O.O.P. with Javascript. It had to render the puzzle and remaining guesses to the DOM but didn't require any C.S.S.
This is what I created.
This is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2 id="render-puzzle"></h2>
<h2 id="guesses"></h2>
<script src="hangman.js"></script>
<script src="app.js"></script>
</body>
</html>
This is my hangman.js which is used to create a hangman object
"strict";
const Hangman = function (word, remainingGuesses) {
this.word = word.toLowerCase().split("");
this.remainingGuesses = remainingGuesses;
this.guessedWords = new Set();
this.status = "Playing";
};
Hangman.prototype.getPuzzle = function () {
let puzzle = [];
this.word.forEach((char) => {
this.guessedWords.has(char) || char === " "
? puzzle.push(char)
: puzzle.push("*");
});
return puzzle.join("");
};
Hangman.prototype.makeGuess = function (guess) {
guess = guess.toLowerCase();
const isUnique = !this.guessedWords.has(guess);
const isBadGuess = !this.word.includes(guess);
if (isUnique) {
this.guessedWords.add(guess);
}
if (isUnique && isBadGuess && this.status === "Playing") {
this.remainingGuesses--;
}
this.calculateStatus();
};
Hangman.prototype.calculateStatus = function () {
const finsished = this.word.every((letter) => this.guessedWords.has(letter));
if (this.remainingGuesses === 0) {
this.status = "Failed";
} else if (finsished) {
this.status = "Finished";
} else {
this.status = "Playing";
}
};
Hangman.prototype.getStatus = function(){
let message = "";
if (this.status === "Playing") {
message = `Remaining Guesses: ${this.remainingGuesses}`
} else if(this.status === "Failed") {
message = `Nice try! The word was ${this.word.join("")}`;
} else {
message = `Great Work! You guessed the word!!!`
}
return message;
}
and this is the app.js where I create an instance of the hangman game
"strict";
const puzzle = document.querySelector("#render-puzzle");
const guesses = document.querySelector("#guesses");
const hangman = new Hangman("Cat", 2);
generatePuzzleDom();
window.addEventListener("keypress", (e) => {
hangman.makeGuess(e.key);
generatePuzzleDom();
console.log(hangman.status);
});
function generatePuzzleDom() {
puzzle.innerHTML = hangman.getPuzzle();
guesses.innerHTML = hangman.getStatus();
}