Reputation: 103
I'm creating a memory game React app. 12 images of dogs are displayed, each of which have a different image. Their placement is shuffled every time you click one. If you click the same image more than once in the current game, you lose and the game resets. If you click all 12 without clicking any of them twice, you win.
Everything seems to be working, except for the win condition. What I want to happen is if the score equals 12, then the score and guesses will be reset and it will display a message that says you win. Currently though, once I reach a score of 12 nothing happens and the game continues. Since there are no more unique images, any image I click after the 12th will result in a loss. I get no errors in npm. Am I not doing something correct here?
Below is the relevant code pertaining to this logic.
class GameArea extends Component {
state = {
score: 0,
guessed: [],
message: ""
}
handleClick(e) {
const clicked = e.target.dataset.id
if (this.state.guessed.indexOf(clicked) > -1) {
this.setState({
score: 0,
guessed: [],
message: "You lose!"
})
} else if (this.state.score === 12) {
this.setState({
score: 0,
guessed: [],
message: "You win!"
})
} else {
this.setState({
score: this.state.score + 1,
guessed: this.state.guessed.concat(clicked),
message: ""
})
}
}
Upvotes: 1
Views: 723
Reputation: 498
I think you want to check if the score is ===11
instead of 12
. This is because of the way you are counting the score. On your 12th click, this.state.score
is equal to 11
. Then your else block will set it to 12
. On your 13th click, this.state.score
is equal to 12
when it runs the loop, but you've re-clicked an image because you only have 12 images.
Upvotes: 1