WEEK 05

Web Games Development · HTML5 Lab

Memory Game

Arrays of card objects, shuffling, click hit-testing and match logic, plus polygons on the canvas.

arrays

shuffle

setTimeout

Date

polygons

Book: Chapter 5 · The Memory Game · pp. 141–177

Today · 90 minutes

Plan for the session

StartSegmentTime
0:00Warm-up review10 min
0:10This week’s game and objectives10 min
0:20Concepts: idea, code, line by line, try it35 min
0:55Common mistakes and check your understanding5 min
1:00Lab: build the files25 min
1:25Build-your-own task, recap and exit quiz5 min

Week 5 · Memory Game

2 / 35

Warm-up · 5 minutes

Remember Week 4?

1

What does new Ball(…) create?

2

What does everything.push(x) do?

3

How is a drag turned into a launch?

4

Why convert degrees to radians?

Week 5 · Memory Game

3 / 35

This week’s game

Flip two cards, find every pair

Cards start face down. The player clicks two. Matches are removed; non-matches flip back after a pause. When every pair is found, the game shows the time taken.

Version one uses polygons on the card fronts. Version two uses photos, and a match means the same person in different pictures, like the 2 of hearts matching the 2 of diamonds.

FROM THE BOOK

Chapter 5 · The Memory Game
pp. 141–177


YOU WILL BUILD

  • triangle.html
  • memoryPolygons.html
  • memoryPictures.html

Week 5 · Memory Game

4 / 35

Objectives

By the end of Week 5 you can…

01

Model each card as an object with a draw() method.

02

Build a deck of pairs and store it in an array.

03

Shuffle by swapping two random cards many times.

04

Load photos with new Image(); draw them with drawImage.

05

Hit-test a mouse click against card rectangles.

06

Track turn state: firstpick, firstcard, secondcard.

07

Pause before flipping back with setTimeout.

08

Time the game with Date and detect the end.

09

Draw regular polygons with paths and trigonometry.

Week 5 · Memory Game

5 / 35

Key words this week

Vocabulary

TermMeaning
deckThe array that holds every card object
infoThe value that says which pair a card belongs to
shufflePut the deck in a random order
hit-testChecking whether a click is inside a shape
setTimeoutRuns a function once, after a delay
getTime()The current time in milliseconds
elapsed timeEnd time minus start time
polygonA closed shape with straight sides

Week 5 · Memory Game

6 / 35

What the program must do

What a memory game needs

Cards

Backs that all look the same, and fronts that differ.

Matching

Know which cards match and where each card is on the board.

A pause

Show both faces, wait so the player can see them, then remove or flip back.

No cheating

Clicking the same card twice must not count as a match.

Week 5 · Memory Game

7 / 35

Big idea 1 · Arrays of cards

A card is data plus a way to draw it

1

Where

sx, sy, swidth, sheight

2

What

info: which pair it belongs to.

3

How

draw = drawback until it is picked.

Week 5 · Memory Game

8 / 35

Example 1 · Arrays of cards

A deck is an array of objects

Each card is an object with a position and an info value. Same info = a pair.

CODE · script · canvas 400 × 200

var deck = [];
for (var i = 0; i < 4; i++) {
  deck.push({ x: 20 + i * 95, y: 15, info: i });
  deck.push({ x: 20 + i * 95, y: 105, info: i });
}
ctx.font = "32px Arial";
deck.forEach(function (card) {
  ctx.fillStyle = "teal";
  ctx.fillRect(card.x, card.y, 75, 80);
  ctx.fillStyle = "white";
  ctx.fillText(card.info, card.x + 28, card.y + 52);
});

OUTPUT · cards shown face up so you can see the pairs

Week 5 · Memory Game

9 / 35

Line by line · Example 1

A deck is an array of objects

var deck = [];

An empty array for the cards.

{ x: …, y: …, info: i }

An object literal: one card’s data.

deck.push(…) twice

Two cards per pair, with the same info.

deck.forEach(function (card) {

Run the drawing code once for each card.

fillText(card.info, …)

Write the info on the card.

Week 5 · Memory Game

10 / 35

Try it · 5 minutes

Resize the board

  1. Change the loop to i<7 (fewer pairs).
  2. Then try i<10.
  3. What else has to change for more cards to fit?

YOU SHOULD SEE

Fewer or more cards appear. With more cards you need a bigger canvas or smaller cards.

Week 5 · Memory Game

11 / 35

Big idea 2 · Shuffling

Swap, swap, swap

1

Pick

Two random positions, i and k.

2

Swap

Exchange their info using a holder.

3

Repeat

3 × the deck length.

Week 5 · Memory Game

12 / 35

Example 2 · Shuffling

Shuffle by swapping

Pick two random positions and swap them. Do it many times and the order is mixed.

CODE · shuffle.html · script

var cards = ["A","A","B","B","C","C","D","D"];
var out = "Before: " + cards.join(" ") + "<br>";
var len = cards.length;
for (var n = 0; n < 3 * len; n++) {
  var i = Math.floor(Math.random() * len);
  var k = Math.floor(Math.random() * len);
  var holder = cards[i];      // swap i and k
  cards[i] = cards[k];
  cards[k] = holder;
}
out = out + "After: " + cards.join(" ");
document.body.innerHTML = out;

OUTPUT · a new shuffle every 2 seconds

Week 5 · Memory Game

13 / 35

Line by line · Example 2

Shuffle by swapping

Math.floor(Math.random() * len)

A random position from 0 to len − 1.

var holder = cards[i];

Keep a copy so it is not lost.

cards[i] = cards[k];

Copy k into i.

cards[k] = holder;

Put the saved value into k: swapped.

n < 3 * len

Repeat three times the number of cards.

Week 5 · Memory Game

14 / 35

Try it · 5 minutes

Test the shuffle

  1. Comment out the call to shuffle(). Where are the pairs?
  2. Now shuffle with only one swap.
  3. Put it back to 3*dl.

YOU SHOULD SEE

Unshuffled, each pair sits one above the other. One swap barely mixes the deck.

Week 5 · Memory Game

15 / 35

Big idea 3 · Hit-tests & pauses

One turn = two picks and a pause

1

First pick

Show it and remember it.

2

Second pick

Show it and compare info.

3

Pause

setTimeout(flipback, 1000), then remove or hide.

Week 5 · Memory Game

16 / 35

Example 3 · Hit-tests & pauses

Was the click inside the card?

Compare the click with the card’s edges. setTimeout waits, then runs code once.

CODE · script · c = canvas 760 × 380

var box = { x: 250, y: 100, w: 260, h: 180 };
function paint(color) {
  ctx.fillStyle = color;
  ctx.fillRect(box.x, box.y, box.w, box.h);
}
c.addEventListener("click", function (e) {
  var mx = e.offsetX, my = e.offsetY;
  var hit = mx > box.x && mx < box.x + box.w &&
            my > box.y && my < box.y + box.h;
  paint(hit ? "gold" : "salmon");
  setTimeout(function () { paint("teal"); }, 1000);
});
paint("teal");

OUTPUT · demo clicks by itself: inside, then outside

Week 5 · Memory Game

17 / 35

Line by line · Example 3

Was the click inside the card?

e.offsetX, e.offsetY

Click position inside the canvas.

mx > box.x && mx < box.x + box.w

Between the left and right edges?

my > box.y && my < box.y + box.h

Between the top and bottom edges?

hit ? "gold" : "salmon"

Pick gold on a hit, salmon on a miss.

setTimeout(…, 1000)

Once, after 1000 ms, paint it teal again.

Week 5 · Memory Game

18 / 35

Try it · 5 minutes

Tune the pause

  1. Change 1000 to 200.
  2. Then change it to 3000.
  3. Which feels fair to the player?

YOU SHOULD SEE

200 is too fast to see the cards; 3000 feels slow. About one second works well.

Week 5 · Memory Game

19 / 35

Big idea 4 · Polygons

Polygon corners sit on a circle

1

Angle step

2π ÷ n

2

Corner

(x + r·cos, y + r·sin)

3

Join

moveTo, then lineTo each corner, then fill.

Week 5 · Memory Game

20 / 35

Example 4 · Polygons

Any polygon from one function

The corners of a regular polygon sit on a circle. cos gives each corner’s x, sin gives its y.

CODE · script · canvas 400 × 200

function polygon(cx, cy, r, n) {
  var step = 2 * Math.PI / n;
  ctx.beginPath();
  ctx.moveTo(cx + r, cy);
  for (var i = 1; i < n; i++) {
    ctx.lineTo(cx + r * Math.cos(i * step),
               cy + r * Math.sin(i * step));
  }
  ctx.closePath();
  ctx.fill();
}
polygon(60, 100, 45, 3);  polygon(170, 100, 45, 5);
polygon(290, 100, 45, 8);

OUTPUT · canvas 400 × 200, shown enlarged

Week 5 · Memory Game

21 / 35

Line by line · Example 4

Any polygon from one function

2 * Math.PI / n

The angle between neighbouring corners.

ctx.moveTo(cx + r, cy);

Start at the corner straight to the right.

r * Math.cos(i * step)

Corner i’s horizontal distance from the centre.

r * Math.sin(i * step)

Corner i’s vertical distance from the centre.

ctx.closePath(); ctx.fill();

Join back to the start and fill the shape.

Week 5 · Memory Game

22 / 35

Try it · 5 minutes

Draw more shapes

  1. In triangle.html change 3 to 5, then 6, then 12.
  2. Try a bigger radius.

YOU SHOULD SEE

A pentagon, a hexagon, then a shape that looks almost like a circle.

Week 5 · Memory Game

23 / 35

Common mistakes

When it goes wrong, check these first

Clicking one card twice “matches”

Fix: Check that the second pick is a different card from the first.

Clicks hit the wrong card

Fix: pageX / pageY are page positions. Keep the canvas at the top-left, or subtract its offset.

The photos do not appear

Fix: Keep the jpg files in the Week5 folder and match the names exactly.

The time is a huge number

Fix: Subtract starttime, then divide by 1000 to get seconds.

Week 5 · Memory Game

24 / 35

Check your understanding · 1 of 4

Two cards match when they have the same…

A

Position

B

info

C

Colour

D

Size

Week 5 · Memory Game

25 / 35

Check your understanding · 2 of 4

setTimeout(flipback, 1000) will…

A

Call flipback every second

B

Call flipback once, after 1 second

C

End the game

D

Call it 1000 times

Week 5 · Memory Game

26 / 35

Check your understanding · 3 of 4

How many degrees between the corners of a hexagon?

A

30

B

45

C

60

D

90

Week 5 · Memory Game

27 / 35

Check your understanding · 4 of 4

Why store starttime?

A

To shuffle

B

To work out the elapsed time

C

To flip cards

D

To draw text

Week 5 · Memory Game

28 / 35

Check your understanding

Answers

QAnswerWhy
Q1B · infoinfo records which pair a card belongs to.
Q2B · Call flipback once, after 1 secondsetTimeout runs once; setInterval repeats.
Q3C · 60360° ÷ 6 = 60°, which is 2π ÷ 6 in radians.
Q4B · To work out the elapsed timeElapsed time = time at the end − starttime.

Week 5 · Memory Game

29 / 35

Lab time · 25 minutes

Your workflow for every file

1

Folder

Create a folder named Week5.

2

Copy

Copy the example files and their images, audio or video into it.

3

Open

Open the folder in VS Code or Sublime Text.

4

Save

Edit, then save with Ctrl+S.

5

Check

Refresh the browser (F5). Open the console (F12).

Never edit the original example for grading. Work on a copy named with your name, for example memoryPictures_yourname.html.

Week 5 · Memory Game

30 / 35

Lab activity · Week5 folder

Warm up, then two versions of the game

FileObjectivesCheckpoint
triangle.html9Draws a triangle with a path and trig
memoryPolygons.html1, 2, 3, 5, 6, 7, 8, 9Shuffles, matches pairs, flips back
memoryPictures.html4, 7, 8Matches photos; shows the time when finished

Compare the two versions: what is the same, and what changes when the fronts become photos?

Week 5 · Memory Game

31 / 35

Stuck?

A five-step debugging checklist

  1. Open the console (F12) and read the first red error.
  2. Check the spelling and capitals of every name and id.
  3. Check that brackets, braces and quotes come in pairs.
  4. Check file names, and that every file is in the same folder.
  5. Save, then hard-refresh with Ctrl+F5.

THIS WEEK’S TIP

Add console.log(deck) after shuffle() to see each card’s info and check the pairs.

Week 5 · Memory Game

32 / 35

BUILD YOUR OWN · ALL OBJECTIVES

Add a moves counter

Week5\memoryPictures_yourname.html

Week 5 · Memory Game

33 / 35

How the build-your-own task is marked

Marking guide

CriterionWhat we look forMarks
Runs cleanlyOpens with no errors in the console (F12)2
Required featuresA moves counter counts each pair of picks, shows next to matches, and resets for a new game4
Readable codeIndented, sensible names, a comment on each function2
Your own touchA personal change: colours, images, text or an extra feature2
Total10

Week 5 · Memory Game

34 / 35

RECAP · CHAPTER 5 · THE MEMORY GAME SUMMARY

What you can do now

  • Programmer-defined functions and objects.
  • Polygons with moveTo, lineTo and Math trig.
  • Using a form to show information to players.
  • Drawing text and images on the canvas.
  • setTimeout for a pause; Date for elapsed time.

NEXT WEEK

Week 6 · Audio, Video & Rewards

Creating HTML elements with code, and rewarding a correct answer with sound and video.

Week 5 · Memory Game

35 / 35

Keyboard
→ Space next   ← previous   Home/End first / last
F full screen   N speaker notes   P print / save as PDF
Click the right or left half of a slide to move forward or back.

Save as PDF: press P, choose “Save as PDF”, and turn on “Background graphics”.