Lesson 16

Objects and Logic

Creating player logic

Our app is really taking shape now. Let's weave in some behaviour to turn our app into a game.

First of all we need to store some information about our players. Rather than using individual variables, we're going to create an object and use this in our game logic.

1. Create objects for Player 1 and Player 2

Under the lines where we created our 'num1' and 'num2' variables, create two 'objects'. These look like the variables created just above, but they contain multiple pieces of information, a score and an ID.

We set their initial scores to zero and give them each a unique ID.

Why are we using objects?

An object is a good way of storing a number of variables. Rather than saving the score and the ID of one player separately, we can save them together. This means they will be easier to compare when we need to pick a winner.

2. Create Snap Check Function

Next, we're going to check if a snap has been made.

Create a new function at the bottom of script.js. We can call this anything, but snapCheck seems like a good name. Inside the function we are going to compare the two 'num' variables to see if they are the same. In JavaScript we use '==' to compare two things. If they are the same an alert is triggered that will say 'SNAP!' If they are not the same an alert will display saying 'NO SNAP!'

Our new snapCheck function won't change anything quite yet though, as we aren't running this new function.

Remind me about logic...

Logic are decisions we make in code. In this case we are comparing 'num1' and 'num2' and asking if they are the same (==). If they are, this means the images must be the same, an alert pops up that says 'SNAP!'

3. Run snapCheck in playTouch functions

Finally, we're going to add in a line which will run our new snapCheck function.

Comment out the lines in playTouch1 and playTouch2 which run the two alerts and add in snapCheck();

What is the difference between creating and running a function?

When you create a function it saves it to the computer’s memory. However, just because it’s saved nothing will happen until we run (or “call”) a function.


Now when a player taps an image, our new snapCheck function will run to see if there is snap. Test this is working on your smart phone or tablet. Tap 'Play Snap That' and if the images are the same you should see a popup which says 'SNAP!'

Go to the next lesson



the web page

New Window
Next Lesson