Lesson 17

Scoring

Is there a snap?

We can now detect if there is a snap or not. We should award players points when they get a snap, and let's also give them some feedback while they are playing so it's easy to see who won.

1. Adding in a score span

We need an area to display the score in our HTML content. Find the two p elements for PLAYER 1 & 2 and add in spans with the ID score1 and score2.

What is a span?

A span is an HTML element that we can use to hold a word or piece of text. Spans can be dynamically updated - in the case of a score for example.

2. Tell snapcheck which player touched screen

When we call 'snapCheck' from within 'playTouch1' and 'playTouch2' we can be clear which player has touched the screen. Add 'player1' and 'player2' as an argument in between the brackets which follow 'snapCheck'.

3. Add a player argument to snapCheck

Now in our 'snapCheck' function we can use our player object as an argument to give that player a point.

First, add an argument into the brackets which follow 'snapCheck' - snapCheck(player). Then inside snapCheck it will replace 'player' with the information sent from 'playTouch1' or 'playTouch2'. It will then change player1.score or player2.score.

We use ++ to increase by 1, and -- to decrease by 1.

How does ++ and -- work?

A double plus adds one to a variable, and a minus one takes away one from a variable.

4. Display updated score and highlight winner

Now the score has changed, we can display it in our page using a jQuery '.html' function.

Comment out the alerts in 'snapCheck' and add in two new jQuery functions. Remember, $ means the program is using a jQuery function.

Finally, we use another jQuery css function to change the background of our player p to show who won, or lost a point.

What is the jQuery '.html' function?

jQuery’s HTML function replaces any existing HTML in an element with updated content. This is great when you want to dynamically give a user new text or information.

5. Reset player p background

So when a snap is attempted, the background colour of our player p elements will change. When a new pair of images is shown, we need to reset our player p backgrounds to yellow. Add a new jQuery css function in the play function.

6. Add p player IDs in HTML

Finally, we need to add the p paragraph IDs into our HTML so they will change colour.

Congratulations!

You should find that if the images are matching, the player's score will increase and the p background will change to green. If the images are different, the player will lose a point and the background colour will change to pink. The colours should reset when a new image is displayed.

Go to the next lesson

index.html

script-1.js

the web page

New Window
Next Lesson