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.
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
firstandbusy. - 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
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.1<!DOCTYPE html>2<html>3 <head>4 <meta charset="utf-8">5 <title>Pair Up</title>6 <link rel="stylesheet" href="style.css">7 </head>8 <body>9 <h1>Pair Up</h1>10 <p id="message">Find all eight pairs.</p>11 <div id="board"></div>12 <script src="script.js"></script>13 </body>14</html>1body {2 font-family: Arial, sans-serif;3 text-align: center;4 background: #fff4e6;5}6 7#board {8 display: grid;9 grid-template-columns: repeat(4, 68px);10 gap: 8px;11 justify-content: center;12 margin: 20px auto;13}14 15.card {16 width: 68px;17 height: 68px;18 font-size: 34px;19 border: none;20 border-radius: 12px;21 background: #6a4c93;22 color: white;23 cursor: pointer;24}25 26.card.flipped {27 background: white;28 box-shadow: inset 0 0 0 4px #6a4c93;29}30 31.card.matched {32 background: #b9fbc0;33 box-shadow: none;34}1const emoji = ["๐", "๐ฆ", "๐ข", "๐ฆ", "๐", "๐", "โฝ", "๐ธ"];2const board = document.getElementById("board");3const message = document.getElementById("message");4An empty board, waiting for its cards. Step 2: Make the cards
emoji.concat(emoji)joins the list to a copy of itself: sixteen cards, two of each. A loop makes abuttonfor each withcreateElement, gives it the classcardand its emoji, and adds it to the board withappendChild. They are face up for now, so you can see them.New: lines 5 to 12.
1const emoji = ["๐", "๐ฆ", "๐ข", "๐ฆ", "๐", "๐", "โฝ", "๐ธ"];2const board = document.getElementById("board");3const message = document.getElementById("message");4 5const cards = emoji.concat(emoji);6 7for (let i = 0; i < cards.length; i++) {8 const card = document.createElement("button");9 card.className = "card";10 card.textContent = cards[i];11 board.appendChild(card);12}Sixteen cards, face up and in order. 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.
1const emoji = ["๐", "๐ฆ", "๐ข", "๐ฆ", "๐", "๐", "โฝ", "๐ธ"];2const board = document.getElementById("board");3const message = document.getElementById("message");4 5// shuffle a list: swap each item with a random one at or before it6function shuffle(list) {7 for (let i = list.length - 1; i > 0; i--) {8 const j = Math.floor(Math.random() * (i + 1));9 const swap = list[i];10 list[i] = list[j];11 list[j] = swap;12 }13}14 15const cards = emoji.concat(emoji);16shuffle(cards);17 18for (let i = 0; i < cards.length; i++) {19 const card = document.createElement("button");20 card.className = "card";21 card.textContent = cards[i];22 board.appendChild(card);23}The same cards, shuffled. Run it again for a new order. Step 4: Face down, and flip
Now each card shows
?, and keeps its emoji hidden incard.dataset.emoji, information stored on the button itself. Clicking a card callsflip, which shows the emoji.aria-labeltells a screen reader what each card is.New: lines 15 to 20, 27 to 33 and 36.
1const emoji = ["๐", "๐ฆ", "๐ข", "๐ฆ", "๐", "๐", "โฝ", "๐ธ"];2const board = document.getElementById("board");3const message = document.getElementById("message");4 5// shuffle a list: swap each item with a random one at or before it6function shuffle(list) {7 for (let i = list.length - 1; i > 0; i--) {8 const j = Math.floor(Math.random() * (i + 1));9 const swap = list[i];10 list[i] = list[j];11 list[j] = swap;12 }13}14 15function flip(card) {16 card.textContent = card.dataset.emoji;17 card.classList.add("flipped");18 card.setAttribute("aria-label", "Card " + card.dataset.number + ", " + card.dataset.emoji);19}20 21const cards = emoji.concat(emoji);22shuffle(cards);23 24for (let i = 0; i < cards.length; i++) {25 const card = document.createElement("button");26 card.className = "card";27 card.dataset.emoji = cards[i];28 card.dataset.number = i + 1;29 card.textContent = "?";30 card.setAttribute("aria-label", "Card " + (i + 1) + ", face down");31 card.addEventListener("click", function () {32 flip(card);33 });34 board.appendChild(card);35}36Click any card to turn it over. Step 5: Find the pairs
firstandsecondremember the two cards turned over. When the second is turned, compare them. A match stays face up and turns green. OtherwisesetTimeoutwaits 900 milliseconds, so you can see both, then callshideto turn them back.busystops you turning a third card while you wait.New: lines 4 to 6, 19 to 21 and 25 to 50.
1const emoji = ["๐", "๐ฆ", "๐ข", "๐ฆ", "๐", "๐", "โฝ", "๐ธ"];2const board = document.getElementById("board");3const message = document.getElementById("message");4let first = null;5let second = null;6let busy = false;7 8// shuffle a list: swap each item with a random one at or before it9function shuffle(list) {10 for (let i = list.length - 1; i > 0; i--) {11 const j = Math.floor(Math.random() * (i + 1));12 const swap = list[i];13 list[i] = list[j];14 list[j] = swap;15 }16}17 18function flip(card) {19 if (busy || card === first || card.classList.contains("matched")) {20 return;21 }22 card.textContent = card.dataset.emoji;23 card.classList.add("flipped");24 card.setAttribute("aria-label", "Card " + card.dataset.number + ", " + card.dataset.emoji);25 if (first === null) {26 first = card;27 return;28 }29 second = card;30 if (first.dataset.emoji === second.dataset.emoji) {31 first.classList.add("matched");32 second.classList.add("matched");33 first = null;34 second = null;35 } else {36 busy = true;37 setTimeout(hide, 900);38 }39}40 41// turn the two cards face down again42function hide() {43 for (const card of [first, second]) {44 card.textContent = "?";45 card.classList.remove("flipped");46 card.setAttribute("aria-label", "Card " + card.dataset.number + ", face down");47 }48 first = null;49 second = null;50 busy = false;51}52 53const cards = emoji.concat(emoji);54shuffle(cards);55 56for (let i = 0; i < cards.length; i++) {57 const card = document.createElement("button");58 card.className = "card";59 card.dataset.emoji = cards[i];60 card.dataset.number = i + 1;61 card.textContent = "?";62 card.setAttribute("aria-label", "Card " + (i + 1) + ", face down");63 card.addEventListener("click", function () {64 flip(card);65 });66 board.appendChild(card);67}68Turn over two cards: a pair stays, anything else turns back. Tipnullmeans nothing: no card has been turned over yet.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.
1<!DOCTYPE html>2<html>3 <head>4 <meta charset="utf-8">5 <title>Pair Up</title>6 <link rel="stylesheet" href="style.css">7 </head>8 <body>9 <h1>Pair Up</h1>10 <p id="message">Find all eight pairs.</p>11 <div id="board"></div>12 <button id="again">Play again</button>13 <script src="script.js"></script>14 </body>15</html>New: lines 35 to 43.
1body {2 font-family: Arial, sans-serif;3 text-align: center;4 background: #fff4e6;5}6 7#board {8 display: grid;9 grid-template-columns: repeat(4, 68px);10 gap: 8px;11 justify-content: center;12 margin: 20px auto;13}14 15.card {16 width: 68px;17 height: 68px;18 font-size: 34px;19 border: none;20 border-radius: 12px;21 background: #6a4c93;22 color: white;23 cursor: pointer;24}25 26.card.flipped {27 background: white;28 box-shadow: inset 0 0 0 4px #6a4c93;29}30 31.card.matched {32 background: #b9fbc0;33 box-shadow: none;34}35 36#again {37 font-size: 18px;38 padding: 8px 20px;39 border: 2px solid #6a4c93;40 border-radius: 20px;41 background: white;42 cursor: pointer;43}New: lines 7, 8, 32, 38 to 43, 46, 63 to 88, 91 and 92.
1const emoji = ["๐", "๐ฆ", "๐ข", "๐ฆ", "๐", "๐", "โฝ", "๐ธ"];2const board = document.getElementById("board");3const message = document.getElementById("message");4let first = null;5let second = null;6let busy = false;7let moves = 0;8let pairs = 0;9 10// shuffle a list: swap each item with a random one at or before it11function shuffle(list) {12 for (let i = list.length - 1; i > 0; i--) {13 const j = Math.floor(Math.random() * (i + 1));14 const swap = list[i];15 list[i] = list[j];16 list[j] = swap;17 }18}19 20function flip(card) {21 if (busy || card === first || card.classList.contains("matched")) {22 return;23 }24 card.textContent = card.dataset.emoji;25 card.classList.add("flipped");26 card.setAttribute("aria-label", "Card " + card.dataset.number + ", " + card.dataset.emoji);27 if (first === null) {28 first = card;29 return;30 }31 second = card;32 moves = moves + 1;33 if (first.dataset.emoji === second.dataset.emoji) {34 first.classList.add("matched");35 second.classList.add("matched");36 first = null;37 second = null;38 pairs = pairs + 1;39 if (pairs === emoji.length) {40 message.textContent = "You found every pair in " + moves + " moves!";41 } else {42 message.textContent = "A pair! Moves: " + moves;43 }44 } else {45 busy = true;46 message.textContent = "Not a pair. Moves: " + moves;47 setTimeout(hide, 900);48 }49}50 51// turn the two cards face down again52function hide() {53 for (const card of [first, second]) {54 card.textContent = "?";55 card.classList.remove("flipped");56 card.setAttribute("aria-label", "Card " + card.dataset.number + ", face down");57 }58 first = null;59 second = null;60 busy = false;61}62 63function deal() {64 // wait while two cards are showing65 if (busy) {66 return;67 }68 board.innerHTML = "";69 first = null;70 second = null;71 busy = false;72 moves = 0;73 pairs = 0;74 message.textContent = "Find all eight pairs.";75 const cards = emoji.concat(emoji);76 shuffle(cards);77 for (let i = 0; i < cards.length; i++) {78 const card = document.createElement("button");79 card.className = "card";80 card.dataset.emoji = cards[i];81 card.dataset.number = i + 1;82 card.textContent = "?";83 card.setAttribute("aria-label", "Card " + (i + 1) + ", face down");84 card.addEventListener("click", function () {85 flip(card);86 });87 board.appendChild(card);88 }89}90 91document.getElementById("again").addEventListener("click", deal);92deal();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.
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.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 fromDate.now()again and divide by 1000 for seconds.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, andlocalStorage.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
1<!DOCTYPE html>2<html>3 <head>4 <meta charset="utf-8">5 <title>Pair Up</title>6 <link rel="stylesheet" href="style.css">7 </head>8 <body>9 <h1>Pair Up</h1>10 <p id="message">Find all eight pairs.</p>11 <div id="board"></div>12 <button id="again">Play again</button>13 <script src="script.js"></script>14 </body>15</html>1body {2 font-family: Arial, sans-serif;3 text-align: center;4 background: #fff4e6;5}6 7#board {8 display: grid;9 grid-template-columns: repeat(4, 68px);10 gap: 8px;11 justify-content: center;12 margin: 20px auto;13}14 15.card {16 width: 68px;17 height: 68px;18 font-size: 34px;19 border: none;20 border-radius: 12px;21 background: #6a4c93;22 color: white;23 cursor: pointer;24}25 26.card.flipped {27 background: white;28 box-shadow: inset 0 0 0 4px #6a4c93;29}30 31.card.matched {32 background: #b9fbc0;33 box-shadow: none;34}35 36#again {37 font-size: 18px;38 padding: 8px 20px;39 border: 2px solid #6a4c93;40 border-radius: 20px;41 background: white;42 cursor: pointer;43}1const emoji = ["๐", "๐ฆ", "๐ข", "๐ฆ", "๐", "๐", "โฝ", "๐ธ"];2const board = document.getElementById("board");3const message = document.getElementById("message");4let first = null;5let second = null;6let busy = false;7let moves = 0;8let pairs = 0;9 10// shuffle a list: swap each item with a random one at or before it11function shuffle(list) {12 for (let i = list.length - 1; i > 0; i--) {13 const j = Math.floor(Math.random() * (i + 1));14 const swap = list[i];15 list[i] = list[j];16 list[j] = swap;17 }18}19 20function flip(card) {21 if (busy || card === first || card.classList.contains("matched")) {22 return;23 }24 card.textContent = card.dataset.emoji;25 card.classList.add("flipped");26 card.setAttribute("aria-label", "Card " + card.dataset.number + ", " + card.dataset.emoji);27 if (first === null) {28 first = card;29 return;30 }31 second = card;32 moves = moves + 1;33 if (first.dataset.emoji === second.dataset.emoji) {34 first.classList.add("matched");35 second.classList.add("matched");36 first = null;37 second = null;38 pairs = pairs + 1;39 if (pairs === emoji.length) {40 message.textContent = "You found every pair in " + moves + " moves!";41 } else {42 message.textContent = "A pair! Moves: " + moves;43 }44 } else {45 busy = true;46 message.textContent = "Not a pair. Moves: " + moves;47 setTimeout(hide, 900);48 }49}50 51// turn the two cards face down again52function hide() {53 for (const card of [first, second]) {54 card.textContent = "?";55 card.classList.remove("flipped");56 card.setAttribute("aria-label", "Card " + card.dataset.number + ", face down");57 }58 first = null;59 second = null;60 busy = false;61}62 63function deal() {64 // wait while two cards are showing65 if (busy) {66 return;67 }68 board.innerHTML = "";69 first = null;70 second = null;71 busy = false;72 moves = 0;73 pairs = 0;74 message.textContent = "Find all eight pairs.";75 const cards = emoji.concat(emoji);76 shuffle(cards);77 for (let i = 0; i < cards.length; i++) {78 const card = document.createElement("button");79 card.className = "card";80 card.dataset.emoji = cards[i];81 card.dataset.number = i + 1;82 card.textContent = "?";83 card.setAttribute("aria-label", "Card " + (i + 1) + ", face down");84 card.addEventListener("click", function () {85 flip(card);86 });87 board.appendChild(card);88 }89}90 91document.getElementById("again").addEventListener("click", deal);92deal();Notes for the teacher
Timing
- 10 minutes: steps 1 and 2.
- 15 minutes: step 3. Act out the shuffle with real cards: it is a lovely algorithm to see.
- 25 minutes: steps 4 to 6.
Mistakes to look out for
- Clicking the same card twice counts as a pair: the check
card === firststops this. - Clicking very fast turns over three cards: the
busyflag stops this. setTimeout(hide(), 900)with brackets runshideat once instead of after 900 milliseconds.- 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.