Created
February 22, 2017 17:54
-
-
Save jaredatron/047a5042d0a6df0e480f612b15d59df2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HangManGame extends Component { | |
constructor(props){ | |
super(props) | |
this.state = { | |
guesses: [] | |
} | |
} | |
gameLogic(){ | |
return new HangManGameLogic( | |
this.props.word, | |
this.state.guesses, | |
) | |
} | |
onGuess = guess => { | |
if (this.gameLogic().gameOver()) return | |
const guesses = this.state.guesses.concat(guess) | |
this.setState({guesses}) | |
} | |
render(){ | |
const gameLogic = this.gameLogic() | |
return <div className="HangManGame"> | |
<HangManMan stageOfDeath={gameLogic.badGuesses().length} /> | |
<HangManWord letters={gameLogic.letters} guesses={gameLogic.guesses} /> | |
<HandManGuessForm onGuess={this.onGuess} /> | |
</div> | |
} | |
} | |
const HangManWord = ({letters, guesses}) => { | |
const letterNodes = letters.map(letter => | |
<span className="HangMan-letter"> | |
{guesses.includes(letter) ? letter : '_'} | |
</span> | |
) | |
return <div className="HangManWord">{letterNodes}</div> | |
} | |
const HangManMan = ({stageOfDeath}) => { | |
return <img | |
className="HangManMan" | |
src={`/images/hangman-${stageOfDeath}.jpg`} | |
/> | |
} | |
const MAX_BAD_GUESSES = 6 | |
class HangManGameLogic { | |
constructor(word, guesses){ | |
this.word = word | |
this.guesses = guesses | |
this.letters = this.word.split('') | |
} | |
badGuesses(){ | |
return this.state.guesses.filter(letter => | |
!this.letters.includes(letter) | |
) | |
} | |
gameWon(){ | |
return this.letters.every(letter => | |
this.guesses.includes(letter) | |
) | |
} | |
gameLost(){ | |
return this.badGuesses().length > MAX_BAD_GUESSES | |
} | |
gameOver(){ | |
return this.gameWon() || this.gameLost() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment