Hangman Javascript class
While starting my way with React hooks, I created a Javascript class for the Hangman game, using most of the methods mentioned in the post about the Javascript class. Why? since I can, and it’s fun to create some #NotFancyAppChallenge 🙂
class Hangman{ #words = ["will","will this","how will this", "can it be that it works?", "it works!"]; #word = ''; #selected = ['']; #failsLeft = 10; #gameOver = false; constructor(){ this.init(); } get failsLeft(){ return this.#failsLeft; } get gameOver(){ return this.#gameOver; } get word(){ let res = this.#word.split('').map(l => { return this.selected.some(s => s === l || !this.isValidChar(l))? `${l}`: `_` }); if(!res.includes('_')){ this.#gameOver = true; } return res; } get selected(){ return this.#selected; } isValidChar(key){ return key.charCodeAt() > 96 && key.charCodeAt() < 123; } checkLetter(key){ if(this.isValidChar(key) && !this.selected.some(l => l === key) && !this.#gameOver){ this.#selected.push(key); if(!this.#word.includes(key)){ --this.#failsLeft; } if(!this.#failsLeft){ this.#gameOver = true;} } } reset(){ this.init(); } init(){ this.#word = this.#words[Math.round(Math.random()*this.#words.length)-1]; this.#selected = ['']; this.#failsLeft = 10; this.#gameOver = false; } }