Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.