JavaScript 39 · Replay Pip’s flight in words

JavaScript lesson 39 of 50 · Advanced · About 5 minutes

Save successful moves and reconstruct their result without moving the live player.

Three cloud creatures follow Pip across lighted floating platforms toward the wind beacon in a rainstorm.
Mission Save successful moves and reconstruct their result without moving the live player.

Get ready

Open Complete checkpoint below. For a browser preview, put the HTML in your editor’s HTML panel and the JavaScript in its JavaScript panel. For a local file, put the HTML first in a new .html file, then put the JavaScript between <script> and </script> at the end. Save the file and open it in a browser.

Match the HTML to the JavaScript. HTML tags create the game’s controls and text. An id names one element. The code uses that name to find the element. A class groups elements for styling, while a data- attribute can carry a game value. A status area with aria-live lets compatible screen readers announce updates.

Log. Save each legal direction. → Rebuild. Apply the same rules from a new Hub state. → Report. Read the rebuilt flight's final square.
Log → Rebuild → Report

Understand the JavaScript in this lesson

Language to look for array push, reduce, accumulator, determinism.

1. Record the moves that happened

Declare moves as an empty array with const. The name keeps pointing at that array, while push adds a new value to it. Dispatch reaches moves.push after the rules approve the move, so an arrow press against the edge leaves the log unchanged.

moves.push(key);

2. Replay the rules in order

The reduce method takes a callback and a starting value. Here the starting value comes from freshState. For each saved direction, the result parameter holds the state from the previous move, key holds the next direction, and the callback returns the next state. At the end, reduce gives you the last state.

return keys.reduce((result, key) => nextState(result, key), freshState());

3. Describe the finish

The button calls replayFlight and places the returned coordinates in a sentence. moves.length counts the successful moves. Add one to coordinates for the human-readable location. This report uses the replay result without assigning it to the live state, so it can be read while Pip stays where the player left off.

const result = replayFlight(moves);

4. Compare both flights

Play three legal moves and note the last position. Read the replay and compare the two. The rules always give the same output for the same state and direction. That property is called determinism, and it makes it possible to reproduce a flight or troubleshoot an unexpected move.

function replayFlight(keys) {
Follow what happens step by step
  1. Try Up at the Hub, then click Right
    One move enters the log.Why The edge blocks the Up input.
  2. Click Replay in words
    The report says one move, column 2, row 1.Why The replay reduced the log from the Hub.

Predict before you run What does reduce return when the command list is empty?

Reveal the answer

It returns its starting value, which here is the fresh Hub state.

Complete checkpoint

HTML · the page and controls

<main id="sky" tabindex="0" aria-label="Sky Island Rescue board">
  <h2>Sky Island Rescue</h2>
  <p id="legend">P = Pip, H = Hub, W = Workshop, G = Garden, B = Beacon, # = rock, . = open sky.</p>
  <pre id="board" aria-hidden="true"></pre>
  <p id="status" role="status"></p>
  <div aria-label="Move Pip">
    <button type="button" data-move="ArrowUp">Up</button>
    <button type="button" data-move="ArrowLeft">Left</button>
    <button type="button" data-move="ArrowDown">Down</button>
    <button type="button" data-move="ArrowRight">Right</button>
  </div>
  <p>Use the move buttons or focus the board and press an arrow key.</p>
  <button id="hint" type="button">Get a route hint</button>
  <p id="time">Flight time: 0s.</p>
  <button id="pause" type="button">Pause</button>
  <button id="replay" type="button">Replay in words</button>
</main>

JavaScript · the instructions

const stage = document.querySelector("#sky");
const board = document.querySelector("#board");
const status = document.querySelector("#status");
const columns = 5;
const rows = 4;
const landmarks = {
  "0,0": "H", "4,0": "W", "0,3": "G", "4,3": "B"
};
const directions = new Map([
  ["ArrowUp", { x: 0, y: -1 }],
  ["ArrowDown", { x: 0, y: 1 }],
  ["ArrowLeft", { x: -1, y: 0 }],
  ["ArrowRight", { x: 1, y: 0 }]
]);
const rocks = new Set(["2,1", "2,2"]);
const tileKey = ({ x, y }) => `${x},${y}`;
function freshState() {
  return { x: 0, y: 0, coil: false, cell: false, lit: false };
}
let state = freshState();
function render() {
  const lines = [];
  for (let y = 0; y < rows; y += 1) {
    const line = [];
    for (let x = 0; x < columns; x += 1) {
      const label = tileKey({ x, y });
      const hasPip = x === state.x && y === state.y;
      line.push(hasPip ? "P" : (rocks.has(label) ? "#" : landmarks[label] ?? "."));
    }
    lines.push(line.join(" "));
  }
  board.textContent = lines.join("\n");
  const position = `Pip is at column ${state.x + 1}, row ${state.y + 1}.`;
  const parts = Number(state.coil) + Number(state.cell);
  const mission = state.lit ? "Beacon lit! Cloud creatures rescued." : `Beacon parts: ${parts} of 2.`;
  status.textContent = `${position} ${mission}` + (paused ? " Flight paused." : "");
}
function inside({ x, y }) {
  return x >= 0 && y >= 0 && x < columns && y < rows;
}
function nextState(current, key) {
  const step = directions.get(key);
  if (!step || current.lit) return current;
  const next = { x: current.x + step.x, y: current.y + step.y };
  const tile = tileKey(next);
  if (!inside(next) || rocks.has(tile)) return current;
  const coil = current.coil || tile === "4,0";
  const cell = current.cell || tile === "0,3";
  const lit = coil && cell && tile === "4,3";
  return { ...next, coil, cell, lit };
}
function findRoute(start, goal) {
  const queue = [{ point: start, path: [] }];
  const seen = new Set([tileKey(start)]);
  for (let head = 0; head < queue.length; head += 1) {
    const { point, path } = queue[head];
    if (tileKey(point) === tileKey(goal)) return path;
    for (const [key, step] of directions) {
      const next = { x: point.x + step.x, y: point.y + step.y };
      const label = tileKey(next);
      if (!inside(next) || rocks.has(label) || seen.has(label)) continue;
      seen.add(label);
      queue.push({ point: next, path: [...path, key] });
    }
  }
  return null;
}
const time = document.querySelector("#time");
let elapsed = 0;
let previous = null;
let lastSecond = -1;
let frame = null;
function tick(now) {
  if (previous !== null) elapsed += now - previous;
  previous = now;
  const seconds = Math.floor(elapsed / 1000);
  if (seconds !== lastSecond) {
    time.textContent = `Flight time: ${seconds}s.`;
    lastSecond = seconds;
  }
  frame = requestAnimationFrame(tick);
}
const pauseButton = document.querySelector("#pause");
let paused = false;
function stopClock() {
  cancelAnimationFrame(frame);
  frame = null;
  previous = null;
}
function resumeClock() {
  if (frame === null && !state.lit) frame = requestAnimationFrame(tick);
}
pauseButton.addEventListener("click", () => {
  if (state.lit) return;
  paused = !paused;
  pauseButton.textContent = paused ? "Resume" : "Pause";
  if (paused) stopClock();
  else resumeClock();
  render();
});
const moves = [];
function replayFlight(keys) {
  return keys.reduce((result, key) => nextState(result, key), freshState());
}
document.querySelector("#replay").addEventListener("click", () => {
  const result = replayFlight(moves);
  status.textContent = `Replayed ${moves.length} moves. Pip ends at column ${result.x + 1}, row ${result.y + 1}.`;
});
function dispatch(key) {
  if (paused) return;
  const result = nextState(state, key);
  if (result === state) return;
  state = result;
  moves.push(key);
  render();
  if (state.lit) stopClock();
}
stage.addEventListener("keydown", (event) => {
  if (event.target !== stage || !directions.has(event.key)) return;
  event.preventDefault();
  dispatch(event.key);
});
for (const button of stage.querySelectorAll("[data-move]")) {
  button.addEventListener("click", () => dispatch(button.dataset.move));
}
document.querySelector("#hint").addEventListener("click", () => {
  if (state.lit) return;
  const goal = !state.coil ? { x: 4, y: 0 } : !state.cell ? { x: 0, y: 3 } : { x: 4, y: 3 };
  const path = findRoute(state, goal);
  status.textContent = path && path.length
    ? `Suggested next move: ${path[0].slice(5)}. Route length: ${path.length}.`
    : "No move suggested.";
});
render();
resumeClock();

Read the JavaScript line by line

Open a small group of lines while you read the complete checkpoint. Blank lines separate ideas. Closing braces mark the end of a block. An ellipsis here means you can read the rest in the full program.

Lines 1–20
Line 1 const stage = document.querySelector("#sky");
Set up stage. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 2 const board = document.querySelector("#board");
Set up board. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 3 const status = document.querySelector("#status");
Set up status. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 4 const columns = 5;
Set up columns. Keep this name attached to the same value.
Line 5 const rows = 4;
Set up rows. Keep this name attached to the same value.
Lines 6–8 const landmarks = { "0,0": "H", "4,0": "W", "0,3": "G", "4,3": "B" };
Set up landmarks. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Lines 9–14 const directions = new Map([ ["ArrowUp", { x: 0, y: -1 }], ["ArrowDown", { x: 0, y: 1 }], ["ArrowLeft", { x: -1, y: 0 }], ["ArrowRight", { x: 1, y: 0 }] ]);
Set up directions. Keep this name attached to the same value. Use new to create a fresh Map object.
Line 15 const rocks = new Set(["2,1", "2,2"]);
Set up rocks. Keep this name attached to the same value. Use new to create a fresh Set object.
Line 16 const tileKey = ({ x, y }) => `${x},${y}`;
Set up tileKey. Keep this name attached to the same value. The arrow defines a function that this line can pass or save for later.
Line 17 function freshState() {
Define freshState. The body runs when the function is called.
Line 18 return { x: 0, y: 0, coil: false, cell: false, lit: false };
Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values.
Line 20 let state = freshState();
Set up state. Give this name a starting value that later code can change. Call freshState with the values inside the parentheses.
Lines 21–34
Line 21 function render() {
Define render. The body runs when the function is called.
Line 22 const lines = [];
Set up lines. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
Line 23 for (let y = 0; y < rows; y += 1) {
Set up the counter, check the condition and run the body. Update the counter after each pass.
Line 24 const line = [];
Set up line. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
Line 25 for (let x = 0; x < columns; x += 1) {
Set up the counter, check the condition and run the body. Update the counter after each pass.
Line 26 const label = tileKey({ x, y });
Set up label. Keep this name attached to the same value. Call tileKey with the values inside the parentheses.
Line 27 const hasPip = x === state.x && y === state.y;
Set up hasPip. Keep this name attached to the same value. JavaScript evaluates the right side only when the left side is truthy. The triple equals compares without converting the value’s type.
Line 28 line.push(hasPip ? "P" : (rocks.has(label) ? "#" : landmarks[label] ?? "."));
Add entries to the end of the array and return its new length.
Line 30 lines.push(line.join(" "));
Add entries to the end of the array and return its new length.
Line 32 board.textContent = lines.join("\n");
Combine array entries into a string, with the chosen separator between entries. Replace the element’s displayed text. The browser treats the value as text.
Line 33 const position = `Pip is at column ${state.x + 1}, row ${state.y + 1}.`;
Set up position. Keep this name attached to the same value. The backticks keep the text together. JavaScript fills each ${…} gap with a value.
Line 34 const parts = Number(state.coil) + Number(state.cell);
Set up parts. Keep this name attached to the same value. Plus adds numbers or joins text, depending on its values. Convert the input to a number when possible.
Lines 35–46
Line 35 const mission = state.lit ? "Beacon lit! Cloud creatures rescued." : `Beacon parts: ${parts} of 2.`;
Set up mission. Keep this name attached to the same value. Before the question mark comes a test. Choose the value after ? when true, or the value after : when false.
Line 36 status.textContent = `${position} ${mission}` + (paused ? " Flight paused." : "");
Plus adds numbers or joins text, depending on its values. The backticks keep the text together. JavaScript fills each ${…} gap with a value.
Line 38 function inside({ x, y }) {
Define inside. The body runs when the function is called, with inputs named { x, y }.
Line 39 return x >= 0 && y >= 0 && x < columns && y < rows;
Leave this function and send the value back to the caller. JavaScript evaluates the right side only when the left side is truthy. Check whether the first is greater than or equal to the second.
Line 41 function nextState(current, key) {
Define nextState. The body runs when the function is called, with inputs named current, key.
Line 42 const step = directions.get(key);
Set up step. Keep this name attached to the same value. Read the matching value from the collection.
Line 43 if (!step || current.lit)
Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy. The exclamation mark reverses a true-or-false test.
Line 43 return current;
Leave this function and send the value back to the caller.
Line 44 const next = { x: current.x + step.x, y: current.y + step.y };
Set up next. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values. Plus adds numbers or joins text, depending on its values.
Line 45 const tile = tileKey(next);
Set up tile. Keep this name attached to the same value. Call tileKey with the values inside the parentheses.
Line 46 if (!inside(next) || rocks.has(tile))
Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy. The exclamation mark reverses a true-or-false test.
Line 46 return current;
Leave this function and send the value back to the caller.
Lines 47–58
Line 47 const coil = current.coil || tile === "4,0";
Set up coil. Keep this name attached to the same value. JavaScript tries the right side only when the left side is falsy. The triple equals compares without converting the value’s type.
Line 48 const cell = current.cell || tile === "0,3";
Set up cell. Keep this name attached to the same value. JavaScript tries the right side only when the left side is falsy. The triple equals compares without converting the value’s type.
Line 49 const lit = coil && cell && tile === "4,3";
Set up lit. Keep this name attached to the same value. JavaScript evaluates the right side only when the left side is truthy. The triple equals compares without converting the value’s type.
Line 50 return { ...next, coil, cell, lit };
Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Three dots unpack the existing entries here.
Line 52 function findRoute(start, goal) {
Define findRoute. The body runs when the function is called, with inputs named start, goal.
Line 53 const queue = [{ point: start, path: [] }];
Set up queue. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0. Braces create an object. Properties give names to the stored values.
Line 54 const seen = new Set([tileKey(start)]);
Set up seen. Keep this name attached to the same value. Use new to create a fresh Set object.
Line 55 for (let head = 0; head < queue.length; head += 1) {
Set up the counter, check the condition and run the body. Update the counter after each pass.
Line 56 const { point, path } = queue[head];
Set up { point, path }. Keep this name attached to the same value. Work out what is inside the brackets first, then use it as the key or index.
Line 57 if (tileKey(point) === tileKey(goal))
Run this part when the test is truthy. The triple equals compares without converting the value’s type. Call tileKey with the values inside the parentheses.
Line 57 return path;
Leave this function and send the value back to the caller.
Line 58 for (const [key, step] of directions) {
Take one value at a time from this sequence and run the body with it.
Lines 59–72
Line 59 const next = { x: point.x + step.x, y: point.y + step.y };
Set up next. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values. Plus adds numbers or joins text, depending on its values.
Line 60 const label = tileKey(next);
Set up label. Keep this name attached to the same value. Call tileKey with the values inside the parentheses.
Line 61 if (!inside(next) || rocks.has(label) || seen.has(label))
Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy. The exclamation mark reverses a true-or-false test.
Line 61 continue;
Skip the rest of this pass and continue with the next loop check.
Line 62 seen.add(label);
Add the value. A Set keeps at most one copy.
Line 63 queue.push({ point: next, path: [...path, key] });
Add entries to the end of the array and return its new length.
Line 66 return null;
Leave this function and send the value back to the caller.
Line 68 const time = document.querySelector("#time");
Set up time. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 69 let elapsed = 0;
Set up elapsed. Give this name a starting value that later code can change.
Line 70 let previous = null;
Set up previous. Give this name a starting value that later code can change.
Line 71 let lastSecond = -1;
Set up lastSecond. Give this name a starting value that later code can change.
Line 72 let frame = null;
Set up frame. Give this name a starting value that later code can change.
Lines 73–85
Line 73 function tick(now) {
Define tick. The body runs when the function is called, with inputs named now.
Line 74 if (previous !== null)
Run this part when the test is truthy. The exclamation and two equals signs check whether values differ without type conversion.
Line 74 elapsed += now - previous;
Minus subtracts the right value. Update the existing value with the operation shown.
Line 75 previous = now;
Store the result in the name or property to the left.
Line 76 const seconds = Math.floor(elapsed / 1000);
Set up seconds. Keep this name attached to the same value. Round down to a whole number.
Line 77 if (seconds !== lastSecond) {
Run this part when the test is truthy. The exclamation and two equals signs check whether values differ without type conversion.
Line 78 time.textContent = `Flight time: ${seconds}s.`;
The backticks keep the text together. JavaScript fills each ${…} gap with a value. Replace the element’s displayed text. The browser treats the value as text.
Line 79 lastSecond = seconds;
Store the result in the name or property to the left.
Line 81 frame = requestAnimationFrame(tick);
Ask the browser to run the callback before a later repaint. Store the result in the name or property to the left.
Line 83 const pauseButton = document.querySelector("#pause");
Set up pauseButton. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 84 let paused = false;
Set up paused. Give this name a starting value that later code can change.
Line 85 function stopClock() {
Define stopClock. The body runs when the function is called.
Lines 86–97
Line 86 cancelAnimationFrame(frame);
Cancel the requested animation callback if it has not run.
Line 87 frame = null;
Store the result in the name or property to the left.
Line 88 previous = null;
Store the result in the name or property to the left.
Line 90 function resumeClock() {
Define resumeClock. The body runs when the function is called.
Line 91 if (frame === null && !state.lit)
Run this part when the test is truthy. JavaScript evaluates the right side only when the left side is truthy. The triple equals compares without converting the value’s type.
Line 91 frame = requestAnimationFrame(tick);
Ask the browser to run the callback before a later repaint. Store the result in the name or property to the left.
Line 93 pauseButton.addEventListener("click", () => {
This function body is passed as an input. Register a function the browser should call when the named event happens.
Line 94 if (state.lit)
Run this part when the test is truthy.
Line 94 return;
Leave this function immediately.
Line 95 paused = !paused;
The exclamation mark reverses a true-or-false test. Store the result in the name or property to the left.
Line 96 pauseButton.textContent = paused ? "Resume" : "Pause";
Before the question mark comes a test. Choose the value after ? when true, or the value after : when false. Replace the element’s displayed text. The browser treats the value as text.
Line 97 if (paused)
Run this part when the test is truthy.
Lines 97–110
Line 97 stopClock();
Call stopClock with the values inside the parentheses.
Line 98 else
Use this alternative when the earlier test did not pass.
Line 98 resumeClock();
Call resumeClock with the values inside the parentheses.
Line 99 render();
Call render with the values inside the parentheses.
Line 101 const moves = [];
Set up moves. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
Line 102 function replayFlight(keys) {
Define replayFlight. The body runs when the function is called, with inputs named keys.
Line 103 return keys.reduce((result, key) => nextState(result, key), freshState());
Leave this function and send the value back to the caller. Combine the entries into a single result, one entry at a time.
Line 105 document.querySelector("#replay").addEventListener("click", () => {
This function body is passed as an input. Find the first element matching the CSS selector. A missing match gives null. Register a function the browser should call when the named event happens.
Line 106 const result = replayFlight(moves);
Set up result. Keep this name attached to the same value. Call replayFlight with the values inside the parentheses.
Line 107 status.textContent = `Replayed ${moves.length} moves. Pip ends at column ${result.x + 1}, row ${result.y + 1}.`;
The backticks keep the text together. JavaScript fills each ${…} gap with a value. Replace the element’s displayed text. The browser treats the value as text.
Line 109 function dispatch(key) {
Define dispatch. The body runs when the function is called, with inputs named key.
Line 110 if (paused)
Run this part when the test is truthy.
Lines 110–119
Line 110 return;
Leave this function immediately.
Line 111 const result = nextState(state, key);
Set up result. Keep this name attached to the same value. Call nextState with the values inside the parentheses.
Line 112 if (result === state)
Run this part when the test is truthy. The triple equals compares without converting the value’s type.
Line 112 return;
Leave this function immediately.
Line 113 state = result;
Store the result in the name or property to the left.
Line 114 moves.push(key);
Add entries to the end of the array and return its new length.
Line 115 render();
Call render with the values inside the parentheses.
Line 116 if (state.lit)
Run this part when the test is truthy.
Line 116 stopClock();
Call stopClock with the values inside the parentheses.
Line 118 stage.addEventListener("keydown", (event) => {
This function body is passed as an input. Register a function the browser should call when the named event happens.
Line 119 if (event.target !== stage || !directions.has(event.key))
Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy. The exclamation and two equals signs check whether values differ without type conversion.
Line 119 return;
Leave this function immediately.
Lines 120–135
Line 120 event.preventDefault();
Stop the browser’s usual response to this event where permitted.
Line 121 dispatch(event.key);
Call dispatch with the values inside the parentheses.
Line 123 for (const button of stage.querySelectorAll("[data-move]")) {
Take one value at a time from this sequence and run the body with it.
Line 124 button.addEventListener("click", () => dispatch(button.dataset.move));
Register a function the browser should call when the named event happens.
Line 126 document.querySelector("#hint").addEventListener("click", () => {
This function body is passed as an input. Find the first element matching the CSS selector. A missing match gives null. Register a function the browser should call when the named event happens.
Line 127 if (state.lit)
Run this part when the test is truthy.
Line 127 return;
Leave this function immediately.
Line 128 const goal = !state.coil ? { x: 4, y: 0 } : !state.cell ? { x: 0, y: 3 } : { x: 4, y: 3 };
Set up goal. Keep this name attached to the same value. Before the question mark comes a test. Choose the value after ? when true, or the value after : when false.
Line 129 const path = findRoute(state, goal);
Set up path. Keep this name attached to the same value. Call findRoute with the values inside the parentheses.
Lines 130–132 status.textContent = path && path.length ? `Suggested next move: ${path[0].slice(5)}. Route length: ${path.length}.` : "No move suggested.";
Before the question mark comes a test. Choose the value after ? when true, or the value after : when false. Replace the element’s displayed text. The browser treats the value as text.
Line 134 render();
Call render with the values inside the parentheses.
Line 135 resumeClock();
Call resumeClock with the values inside the parentheses.

Mission challenge

Record a route that tries to pass through a rock. Compare the number of button presses with the number of moves in the replay.

Change one piece at a time. Run the checkpoint again and compare what you expected with what actually happened.