Game making in JavaScript

Pair Up

A memory game: turn over two cards at a time and find all eight matching pairs in as few moves as you can.

Day 4 45 to 60 minutes 6 steps Key Stage 3
Start step 1
pair-up/index.html

Sixteen cards lie face down. Turn over two: if they match, they stay up. If not, they turn back over, and you have to remember where they were. This game needs no canvas: every card is a button that JavaScript makes, and the clever part is remembering which cards are turned over at each moment.

You will learn

  • Build a page from JavaScript with createElement
  • Shuffle an array fairly
  • Remember the state of a game in variables
  • Wait before acting with setTimeout

You will need

  • A computer with a web browser
  • The Web Studio, or Notepad
  • Day 1, for arrays and click events

Words to know

state
What the game is doing right now, kept in variables such as first and busy.
shuffle
Putting a list in a random order, so that every order is equally likely.
createElement
Makes a new part of the page, such as a button, from JavaScript.
setTimeout
Runs a function once, after a wait in milliseconds.

Step by step

  1. Step 1: The board

    Choose Day 4: Pair Up. The page has a message and an empty board. The CSS makes the board a grid of four columns, and styles each card: purple face down, white when flipped, and green once matched. The script starts with the eight pictures, written as emoji.

    index.htmlHTML
    <!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>Pair Up</title>    <link rel="stylesheet" href="style.css">  </head>  <body>    <h1>Pair Up</h1>    <p id="message">Find all eight pairs.</p>    <div id="board"></div>    <script src="script.js"></script>  </body></html>
    style.cssCSS
    body {  font-family: Arial, sans-serif;  text-align: center;  background: #fff4e6;} #board {  display: grid;  grid-template-columns: repeat(4, 68px);  gap: 8px;  justify-content: center;  margin: 20px auto;} .card {  width: 68px;  height: 68px;  font-size: 34px;  border: none;  border-radius: 12px;  background: #6a4c93;  color: white;  cursor: pointer;} .card.flipped {  background: white;  box-shadow: inset 0 0 0 4px #6a4c93;} .card.matched {  background: #b9fbc0;  box-shadow: none;}
    script.jsJavaScript
    const emoji = ["๐Ÿ™", "๐ŸฆŠ", "๐Ÿข", "๐Ÿฆ„", "๐Ÿ•", "๐Ÿš€", "โšฝ", "๐ŸŽธ"];const board = document.getElementById("board");const message = document.getElementById("message"); 
    pair-up/index.html
    An empty board, waiting for its cards.
  2. Step 2: Make the cards

    emoji.concat(emoji) joins the list to a copy of itself: sixteen cards, two of each. A loop makes a button for each with createElement, gives it the class card and its emoji, and adds it to the board with appendChild. They are face up for now, so you can see them.

    New: lines 5 to 12.

    script.jsJavaScript
    const emoji = ["๐Ÿ™", "๐ŸฆŠ", "๐Ÿข", "๐Ÿฆ„", "๐Ÿ•", "๐Ÿš€", "โšฝ", "๐ŸŽธ"];const board = document.getElementById("board");const message = document.getElementById("message"); const cards = emoji.concat(emoji); for (let i = 0; i < cards.length; i++) {  const card = document.createElement("button");  card.className = "card";  card.textContent = cards[i];  board.appendChild(card);}
    pair-up/index.html
    Sixteen cards, face up and in order.
  3. Step 3: Shuffle them

    A fair shuffle goes through the list from the end, swapping each card with a random card at or before it. Every order is equally likely, just like shuffling real cards well.

    New: lines 5 to 14 and 16.

    script.jsJavaScript
    const emoji = ["๐Ÿ™", "๐ŸฆŠ", "๐Ÿข", "๐Ÿฆ„", "๐Ÿ•", "๐Ÿš€", "โšฝ", "๐ŸŽธ"];const board = document.getElementById("board");const message = document.getElementById("message"); // shuffle a list: swap each item with a random one at or before itfunction shuffle(list) {  for (let i = list.length - 1; i > 0; i--) {    const j = Math.floor(Math.random() * (i + 1));    const swap = list[i];    list[i] = list[j];    list[j] = swap;  }} const cards = emoji.concat(emoji);shuffle(cards); for (let i = 0; i < cards.length; i++) {  const card = document.createElement("button");  card.className = "card";  card.textContent = cards[i];  board.appendChild(card);}
    pair-up/index.html
    The same cards, shuffled. Run it again for a new order.
  4. Step 4: Face down, and flip

    Now each card shows ?, and keeps its emoji hidden in card.dataset.emoji, information stored on the button itself. Clicking a card calls flip, which shows the emoji. aria-label tells a screen reader what each card is.

    New: lines 15 to 20, 27 to 33 and 36.

    script.jsJavaScript
    const emoji = ["๐Ÿ™", "๐ŸฆŠ", "๐Ÿข", "๐Ÿฆ„", "๐Ÿ•", "๐Ÿš€", "โšฝ", "๐ŸŽธ"];const board = document.getElementById("board");const message = document.getElementById("message"); // shuffle a list: swap each item with a random one at or before itfunction shuffle(list) {  for (let i = list.length - 1; i > 0; i--) {    const j = Math.floor(Math.random() * (i + 1));    const swap = list[i];    list[i] = list[j];    list[j] = swap;  }} function flip(card) {  card.textContent = card.dataset.emoji;  card.classList.add("flipped");  card.setAttribute("aria-label", "Card " + card.dataset.number + ", " + card.dataset.emoji);} const cards = emoji.concat(emoji);shuffle(cards); for (let i = 0; i < cards.length; i++) {  const card = document.createElement("button");  card.className = "card";  card.dataset.emoji = cards[i];  card.dataset.number = i + 1;  card.textContent = "?";  card.setAttribute("aria-label", "Card " + (i + 1) + ", face down");  card.addEventListener("click", function () {    flip(card);  });  board.appendChild(card);} 
    pair-up/index.html
    Click any card to turn it over.
  5. Step 5: Find the pairs

    first and second remember the two cards turned over. When the second is turned, compare them. A match stays face up and turns green. Otherwise setTimeout waits 900 milliseconds, so you can see both, then calls hide to turn them back. busy stops you turning a third card while you wait.

    New: lines 4 to 6, 19 to 21 and 25 to 50.

    script.jsJavaScript
    const emoji = ["๐Ÿ™", "๐ŸฆŠ", "๐Ÿข", "๐Ÿฆ„", "๐Ÿ•", "๐Ÿš€", "โšฝ", "๐ŸŽธ"];const board = document.getElementById("board");const message = document.getElementById("message");let first = null;let second = null;let busy = false; // shuffle a list: swap each item with a random one at or before itfunction shuffle(list) {  for (let i = list.length - 1; i > 0; i--) {    const j = Math.floor(Math.random() * (i + 1));    const swap = list[i];    list[i] = list[j];    list[j] = swap;  }} function flip(card) {  if (busy || card === first || card.classList.contains("matched")) {    return;  }  card.textContent = card.dataset.emoji;  card.classList.add("flipped");  card.setAttribute("aria-label", "Card " + card.dataset.number + ", " + card.dataset.emoji);  if (first === null) {    first = card;    return;  }  second = card;  if (first.dataset.emoji === second.dataset.emoji) {    first.classList.add("matched");    second.classList.add("matched");    first = null;    second = null;  } else {    busy = true;    setTimeout(hide, 900);  }} // turn the two cards face down againfunction hide() {  for (const card of [first, second]) {    card.textContent = "?";    card.classList.remove("flipped");    card.setAttribute("aria-label", "Card " + card.dataset.number + ", face down");  }  first = null;  second = null;  busy = false;} const cards = emoji.concat(emoji);shuffle(cards); for (let i = 0; i < cards.length; i++) {  const card = document.createElement("button");  card.className = "card";  card.dataset.emoji = cards[i];  card.dataset.number = i + 1;  card.textContent = "?";  card.setAttribute("aria-label", "Card " + (i + 1) + ", face down");  card.addEventListener("click", function () {    flip(card);  });  board.appendChild(card);} 
    pair-up/index.html
    Turn over two cards: a pair stays, anything else turns back.
    Tip null means nothing: no card has been turned over yet.
  6. Step 6: Moves, and a winner

    Count every two cards as one move, and count the pairs. When all eight pairs are found, the message says how many moves it took. The cards are now made by a function, deal, so the Play again button can deal a fresh shuffled board.

    New: line 12.

    index.htmlHTML
    <!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>Pair Up</title>    <link rel="stylesheet" href="style.css">  </head>  <body>    <h1>Pair Up</h1>    <p id="message">Find all eight pairs.</p>    <div id="board"></div>    <button id="again">Play again</button>    <script src="script.js"></script>  </body></html>

    New: lines 35 to 43.

    style.cssCSS
    body {  font-family: Arial, sans-serif;  text-align: center;  background: #fff4e6;} #board {  display: grid;  grid-template-columns: repeat(4, 68px);  gap: 8px;  justify-content: center;  margin: 20px auto;} .card {  width: 68px;  height: 68px;  font-size: 34px;  border: none;  border-radius: 12px;  background: #6a4c93;  color: white;  cursor: pointer;} .card.flipped {  background: white;  box-shadow: inset 0 0 0 4px #6a4c93;} .card.matched {  background: #b9fbc0;  box-shadow: none;} #again {  font-size: 18px;  padding: 8px 20px;  border: 2px solid #6a4c93;  border-radius: 20px;  background: white;  cursor: pointer;}

    New: lines 7, 8, 32, 38 to 43, 46, 63 to 88, 91 and 92.

    script.jsJavaScript
    const emoji = ["๐Ÿ™", "๐ŸฆŠ", "๐Ÿข", "๐Ÿฆ„", "๐Ÿ•", "๐Ÿš€", "โšฝ", "๐ŸŽธ"];const board = document.getElementById("board");const message = document.getElementById("message");let first = null;let second = null;let busy = false;let moves = 0;let pairs = 0; // shuffle a list: swap each item with a random one at or before itfunction shuffle(list) {  for (let i = list.length - 1; i > 0; i--) {    const j = Math.floor(Math.random() * (i + 1));    const swap = list[i];    list[i] = list[j];    list[j] = swap;  }} function flip(card) {  if (busy || card === first || card.classList.contains("matched")) {    return;  }  card.textContent = card.dataset.emoji;  card.classList.add("flipped");  card.setAttribute("aria-label", "Card " + card.dataset.number + ", " + card.dataset.emoji);  if (first === null) {    first = card;    return;  }  second = card;  moves = moves + 1;  if (first.dataset.emoji === second.dataset.emoji) {    first.classList.add("matched");    second.classList.add("matched");    first = null;    second = null;    pairs = pairs + 1;    if (pairs === emoji.length) {      message.textContent = "You found every pair in " + moves + " moves!";    } else {      message.textContent = "A pair! Moves: " + moves;    }  } else {    busy = true;    message.textContent = "Not a pair. Moves: " + moves;    setTimeout(hide, 900);  }} // turn the two cards face down againfunction hide() {  for (const card of [first, second]) {    card.textContent = "?";    card.classList.remove("flipped");    card.setAttribute("aria-label", "Card " + card.dataset.number + ", face down");  }  first = null;  second = null;  busy = false;} function deal() {  // wait while two cards are showing  if (busy) {    return;  }  board.innerHTML = "";  first = null;  second = null;  busy = false;  moves = 0;  pairs = 0;  message.textContent = "Find all eight pairs.";  const cards = emoji.concat(emoji);  shuffle(cards);  for (let i = 0; i < cards.length; i++) {    const card = document.createElement("button");    card.className = "card";    card.dataset.emoji = cards[i];    card.dataset.number = i + 1;    card.textContent = "?";    card.setAttribute("aria-label", "Card " + (i + 1) + ", face down");    card.addEventListener("click", function () {      flip(card);    });    board.appendChild(card);  }} document.getElementById("again").addEventListener("click", deal);deal();
    pair-up/index.html
    The finished Pair Up. Can you do it in 12 moves?

Test it

Tick each one when it works. If one does not, look back at the step it comes from.

Stretch challenges

Finished early? Try these. Each one has a hint if you get stuck.

  1. Bigger board

    Make a board of 24 cards, twelve pairs, in six columns.

    Show a hint

    Add four more emoji to the list, and change the grid to repeat(6, 68px) in the CSS.

  2. Against the clock

    Show how many seconds the game takes.

    Show a hint

    Remember Date.now() when the cards are dealt. When the last pair is found, take that from Date.now() again and divide by 1000 for seconds.

  3. Best score

    Remember the fewest moves ever, even after the page is closed.

    Show a hint

    localStorage.setItem("best", moves) saves a value in the browser, and localStorage.getItem("best") reads it back. It only works when the game is opened from a file or a website, not inside the step's preview.

The finished code

Show the whole game
index.htmlHTML
<!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>Pair Up</title>    <link rel="stylesheet" href="style.css">  </head>  <body>    <h1>Pair Up</h1>    <p id="message">Find all eight pairs.</p>    <div id="board"></div>    <button id="again">Play again</button>    <script src="script.js"></script>  </body></html>
style.cssCSS
body {  font-family: Arial, sans-serif;  text-align: center;  background: #fff4e6;} #board {  display: grid;  grid-template-columns: repeat(4, 68px);  gap: 8px;  justify-content: center;  margin: 20px auto;} .card {  width: 68px;  height: 68px;  font-size: 34px;  border: none;  border-radius: 12px;  background: #6a4c93;  color: white;  cursor: pointer;} .card.flipped {  background: white;  box-shadow: inset 0 0 0 4px #6a4c93;} .card.matched {  background: #b9fbc0;  box-shadow: none;} #again {  font-size: 18px;  padding: 8px 20px;  border: 2px solid #6a4c93;  border-radius: 20px;  background: white;  cursor: pointer;}
script.jsJavaScript
const emoji = ["๐Ÿ™", "๐ŸฆŠ", "๐Ÿข", "๐Ÿฆ„", "๐Ÿ•", "๐Ÿš€", "โšฝ", "๐ŸŽธ"];const board = document.getElementById("board");const message = document.getElementById("message");let first = null;let second = null;let busy = false;let moves = 0;let pairs = 0; // shuffle a list: swap each item with a random one at or before itfunction shuffle(list) {  for (let i = list.length - 1; i > 0; i--) {    const j = Math.floor(Math.random() * (i + 1));    const swap = list[i];    list[i] = list[j];    list[j] = swap;  }} function flip(card) {  if (busy || card === first || card.classList.contains("matched")) {    return;  }  card.textContent = card.dataset.emoji;  card.classList.add("flipped");  card.setAttribute("aria-label", "Card " + card.dataset.number + ", " + card.dataset.emoji);  if (first === null) {    first = card;    return;  }  second = card;  moves = moves + 1;  if (first.dataset.emoji === second.dataset.emoji) {    first.classList.add("matched");    second.classList.add("matched");    first = null;    second = null;    pairs = pairs + 1;    if (pairs === emoji.length) {      message.textContent = "You found every pair in " + moves + " moves!";    } else {      message.textContent = "A pair! Moves: " + moves;    }  } else {    busy = true;    message.textContent = "Not a pair. Moves: " + moves;    setTimeout(hide, 900);  }} // turn the two cards face down againfunction hide() {  for (const card of [first, second]) {    card.textContent = "?";    card.classList.remove("flipped");    card.setAttribute("aria-label", "Card " + card.dataset.number + ", face down");  }  first = null;  second = null;  busy = false;} function deal() {  // wait while two cards are showing  if (busy) {    return;  }  board.innerHTML = "";  first = null;  second = null;  busy = false;  moves = 0;  pairs = 0;  message.textContent = "Find all eight pairs.";  const cards = emoji.concat(emoji);  shuffle(cards);  for (let i = 0; i < cards.length; i++) {    const card = document.createElement("button");    card.className = "card";    card.dataset.emoji = cards[i];    card.dataset.number = i + 1;    card.textContent = "?";    card.setAttribute("aria-label", "Card " + (i + 1) + ", face down");    card.addEventListener("click", function () {      flip(card);    });    board.appendChild(card);  }} document.getElementById("again").addEventListener("click", deal);deal();
Notes for the teacher

Timing

  1. 10 minutes: steps 1 and 2.
  2. 15 minutes: step 3. Act out the shuffle with real cards: it is a lovely algorithm to see.
  3. 25 minutes: steps 4 to 6.

Mistakes to look out for

  1. Clicking the same card twice counts as a pair: the check card === first stops this.
  2. Clicking very fast turns over three cards: the busy flag stops this.
  3. setTimeout(hide(), 900) with brackets runs hide at once instead of after 900 milliseconds.
  4. Emoji showing as empty boxes: an old computer's fonts may lack them. Letters or numbers work just as well.

Going further

This is a state machine: the game is always in one of a few states (no card turned, one card turned, two cards turned and waiting) and each click moves it to the next. Drawing the states as a flowchart is a great extension.