Lesson 19

Winner logic

Is there a winner?

It's possible that you've already had some fun playing your snap game. We think every game benefits from a goal - so next we're going to set a winning score, and when that target is reached we'll display a winner.

1. Add isTheWinner logic to play function

Inside your play function, add some logic which checks if 'player1' or 'player2' is the winner. If not, the play function will carry on looping the images as before.

Watch where this code is added. The check code starts just after the 'play' function starts, and ends just before the 'play' function finishes.

What does || mean?

A double “pipe” means “or”.

2. Create isTheWinner function

Now we need to create our 'isTheWinner' function. You can put this right at the bottom of script.js. This will receive either 'player1' or 'player2' when it is run from our 'play' function.

It then compares the score value with a number. We've set the number of wins to 2 - you can set it to whatever you like!

If the the player score is equal to 2, it will send a message back to the play function that there is a winner. If the player score is not equal to 2 it will send a message that there is currently no winner. Our play function checks both player1 and player2. If there are no winners it will continue looping our images.

What does 'return true' and 'return false' mean?

Return true means that the function will stop and record a value of “true”, return false means the same but that a value of “false” will be recorded.

3. Hide p and show new h1 content

If there is a winner, we can add jQuery functions to hide our player scores, show our h1 and change the content of our h1 to display the winner.

Check this is working properly. You can also play around with the target score to make it harder or easier to win!


You've now finished all the JavaScript in your Snap That game. When you play your game, there should be a set number of wins, and when reached, the looping images will stop and the h1 will change to display the winner!

In the final lesson, we're going to get the images in your game loading more quickly, as the final icing on the cake.

Your final Snap That JavaScript code should look like this:

Go to the next lesson



the web page

New Window
Next Lesson