JavaScript 50 · Launch Sky Island Rescue

JavaScript lesson 50 of 50 · Expert projects · About 50 minutes

Put the mission engine, navigator, controls, radio, and recorder together in a complete browser game.

Pip watches six little cloud creatures gather safely in the glow of the restored wind beacon at dawn.
Mission Run, win, restart, and verify an original JavaScript game in a local browser.

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.

Controls. Send a button or arrow command. → Engine. Update the room, battery, flags, and win condition. → Game view. Show the state and let the player verify the run.
Controls → Engine → Game view

Understand the JavaScript in this lesson

Language to look for Feature integration, Playtesting, State and rendering, Reproducible bug reports, Capstone.

1. Assemble and boot the game

Create an HTML file using the supplied page markup and run the JavaScript after it. For a single file, wrap the JavaScript in a script element below the markup. Opening that file in a browser starts mission 1. startRun creates a new state and an empty move list, and render describes Pip's position. The map gives you a way to connect the names to places before you start moving.

startRun(mission);

2. Follow one input through the whole game

Use the arrows on the focused board or click the direction buttons. Each path calls move with a compass command. step applies the rules to the current state. move records the command only when the returned object differs from the old one, then the view redraws. The rescue expression uses && because landing at the Beacon and holding both parts must be true at the same time.

rescued: room === "beacon" && parts === 3

3. Try the parts together

Choose seed 1000 and three energy. Ask for a hint, then take East and West to collect one part and recharge. Save the run if browser storage is available. Take South and then East for a win. Open the recorder and check that every accepted move has a row. Restart and use Load when available to repeat the last two moves from the saved state.

state = replay(mission, moves).at(-1).state;

4. Playtest and verify a change

Run the simulator checks, then request a briefing and restart while it is pending. Try all actions with the keyboard as well. A useful bug report records the seed, energy setting, exact commands, expected result, and actual result. Change something you can test, such as the opening radio text in getBriefing. Play the same mission before and after so you can pinpoint the change.

log.textContent = runChecks();
Follow what happens step by step
  1. Seed 1000, 3 energy, East
    Workshop, 2 energy, LensWhy The seeded layout puts flag 2 in the Workshop.
  2. West, South, East
    Beacon, 1 energy, Cog + Lens, clouds rescuedWhy Recharging makes room for the final two moves.
  3. Restart
    Sky Dock, 3 energy, no partsWhy The seed and capacity carry forward into a fresh run.

Predict before you run What happens if you try to keep moving after the rescue?

Reveal the answer

The engine returns the completed state unchanged, so extra commands leave the win state and flight recorder alone until you start another run.

Complete checkpoint

HTML · the page and controls

<figure>
  <svg viewBox="0 0 360 235" width="360" style="max-width:100%;height:auto" role="img" aria-label="Sky Dock and Workshop on the top row, Garden and Beacon on the bottom row, joined by four paths">
    <rect x="0" y="0" width="360" height="235" rx="21" fill="#14294a"/>
    <path d="M85 66H275V169H85Z" fill="none" stroke="#7fcbd9" stroke-width="5" stroke-dasharray="8 6"/>
    <g fill="#edf5ff" stroke="#495e8d" stroke-width="2">
      <rect x="25" y="40" width="120" height="52" rx="14"/>
      <rect x="215" y="40" width="120" height="52" rx="14"/>
      <rect x="25" y="143" width="120" height="52" rx="14"/>
      <rect x="215" y="143" width="120" height="52" rx="14"/>
    </g>
    <g fill="#14294a" text-anchor="middle" font-family="sans-serif" font-weight="bold">
      <text x="85" y="72">Sky Dock</text><text x="275" y="72">Workshop</text>
      <text x="85" y="175">Garden</text><text x="275" y="175">Beacon</text>
    </g>
  </svg>
  <figcaption>The Sky Dock recharges Pip. The two parts can trade places between missions.</figcaption>
</figure>
<section id="board" tabindex="0" role="region" aria-label="Pip's rover controls" aria-describedby="how">
  <p id="how">Use the direction buttons. Tab to this panel to use arrow keys.</p>
  <p id="status" role="status" aria-atomic="true"></p>
  <button type="button" data-move="north">North</button>
  <button type="button" data-move="east">East</button>
  <button type="button" data-move="south">South</button>
  <button type="button" data-move="west">West</button>
</section>
<p id="log" role="status" aria-atomic="true"></p>
<button type="button" id="restart">Restart mission</button>
<button type="button" id="hint">Show a route hint</button>
<button type="button" id="save">Save mission</button>
<button type="button" id="load">Load mission</button>
<button type="button" id="replay">Show flight recorder</button>
<button type="button" id="test">Run simulator checks</button>
<button type="button" id="brief">Listen to the briefing</button>
<h3>Flight recorder</h3>
<pre id="records"></pre>
<form id="mission-form">
  <label for="seed">Mission code</label>
  <input id="seed" type="number" min="0" max="4294967295" step="1" required value="1">
  <label for="power">Battery capacity</label>
  <select id="power">
    <option value="6">6 energy</option>
    <option value="4">4 energy</option>
    <option value="3">3 energy</option>
  </select>
  <button type="submit">Start selected mission</button>
</form>

JavaScript · the instructions

const links = {
  dock: { east: "workshop", south: "garden" },
  workshop: { west: "dock", south: "beacon" },
  garden: { north: "dock", east: "beacon" },
  beacon: { north: "workshop", west: "garden" }
};
const directions = ["north", "east", "south", "west"];
const standard = {
  seed: 1, capacity: 6,
  pickup: { workshop: 1, garden: 2 }
};
const newRun = mission => ({
  room: "dock", energy: mission.capacity, parts: 0, rescued: false
});
function step(state, command, mission) {
  if (state.rescued || state.energy === 0) return state;
  if (!directions.includes(command)) return state;
  const room = links[state.room][command];
  if (!room) return state;
  const parts = state.parts | (mission.pickup[room] ?? 0);
  return {
    room, parts,
    energy: room === "dock" ? mission.capacity : state.energy - 1,
    rescued: room === "beacon" && parts === 3
  };
}
function describe(state) {
  const names = { dock: "Sky Dock", workshop: "Workshop", garden: "Garden", beacon: "Beacon" };
  const pieces = ["none", "Cog", "Lens", "Cog + Lens"];
  const result = state.rescued ? " Cloud creatures rescued!" :
    state.energy === 0 ? " Battery empty. Restart to try again." : "";
  return names[state.room] + " | Energy " + state.energy +
    " | Parts: " + pieces[state.parts] + "." + result;
}

function makeMission(seed, capacity = 6) {
  const cleanSeed = seed >>> 0;
  const draw = (Math.imul(cleanSeed, 1664525) + 1013904223) >>> 0;
  const swap = draw >= 0x80000000;
  return {
    seed: cleanSeed, capacity,
    pickup: { workshop: swap ? 2 : 1, garden: swap ? 1 : 2 }
  };
}

function signature(state) {
  return [state.room, state.energy, state.parts, state.rescued].join("|");
}
function planRoute(start, mission) {
  const queue = [{ state: start, route: [] }];
  const seen = new Set([signature(start)]);
  for (let head = 0; head < queue.length; head += 1) {
    const { state, route } = queue[head];
    if (state.rescued) return route;
    for (const command of directions) {
      const next = step(state, command, mission);
      const key = signature(next);
      if (seen.has(key)) continue;
      seen.add(key);
      queue.push({ state: next, route: [...route, command] });
    }
  }
  return null;
}

const slot = "quesbo-sky-island-v1";
function decodeSave(text) {
  try {
    const data = JSON.parse(text);
    if (data?.version !== 1 ||
        !Number.isInteger(data.seed) || data.seed < 0 ||
        data.seed > 0xffffffff ||
        ![3, 4, 6].includes(data.capacity) ||
        !Array.isArray(data.moves) || data.moves.length > 1000 ||
        !data.moves.every(move => directions.includes(move))) return null;
    return data;
  } catch {
    return null;
  }
}
function readSave() {
  try {
    return decodeSave(localStorage.getItem(slot));
  } catch {
    return null;
  }
}
function writeSave(mission, moves) {
  try {
    if (moves.length > 1000) return false;
    localStorage.setItem(slot, JSON.stringify({
      version: 1, seed: mission.seed, capacity: mission.capacity, moves
    }));
    return true;
  } catch {
    return false;
  }
}

function replay(mission, moves) {
  return moves.reduce((frames, command) => {
    const previous = frames.at(-1).state;
    const state = step(previous, command, mission);
    frames.push({ command, state, changed: state !== previous });
    return frames;
  }, [{ command: "start", state: newRun(mission), changed: false }]);
}

function runChecks() {
  let passed = 0;
  function expect(condition, title) {
    if (!condition) throw new Error(title);
    passed += 1;
  }
  const mission = makeMission(1);
  const start = Object.freeze(newRun(mission));
  const workshop = step(start, "east", mission);
  expect(start.room === "dock" && workshop.room === "workshop", "Move keeps old state");
  expect(step(start, "north", mission) === start, "Blocked move keeps state");
  expect(step(workshop, "west", mission).energy === 6, "Dock recharges");
  const route = planRoute(start, mission);
  expect(route !== null && route.length === 4, "Shortest rescue has four moves");
  const final = replay(mission, route).at(-1).state;
  expect(final.rescued && final.parts === 3, "Replay reaches rescue");
  expect(step(final, "west", mission) === final, "Rescue ends movement");
  expect(planRoute(newRun(makeMission(1, 1)), makeMission(1, 1)) === null, "Empty routes terminate");
  expect(decodeSave('{"version":2}') === null, "Unknown save version is rejected");
  expect(decodeSave('{"version":1,"seed":0,"capacity":6,"moves":["jump"]}') === null,
    "Unknown commands are rejected");
  expect(makeMission(1).pickup.workshop !== makeMission(1000).pickup.workshop,
    "Different seeds can swap the parts");
  return passed + " checks passed.";
}

const status = document.querySelector("#status");
const log = document.querySelector("#log");
let mission = makeMission(1);
let state;
let moves;
function render() {
  status.textContent = describe(state);
}
function startRun(nextMission) {
  mission = nextMission;
  state = newRun(mission);
  moves = [];
  log.textContent = "";
  render();
}
function move(command) {
  const next = step(state, command, mission);
  if (next === state) {
    log.textContent = "Pip stays put.";
    return;
  }
  moves.push(command);
  state = next;
  log.textContent = "";
  render();
}
for (const button of document.querySelectorAll("[data-move]")) {
  button.addEventListener("click", () => move(button.dataset.move));
}
document.querySelector("#restart").addEventListener("click", () => startRun({ ...mission }));
startRun(mission);
document.querySelector("#hint").addEventListener("click", () => {
  const route = planRoute(state, mission);
  log.textContent = route === null ? "No rescue route from here." :
    route.length === 0 ? "Rescue complete." :
    "Try " + route[0] + ". A shortest route takes " + route.length + " moves.";
});
document.querySelector("#save").addEventListener("click", () => {
  log.textContent = writeSave(mission, moves) ? "Mission saved." : "Saving is unavailable.";
});
document.querySelector("#load").addEventListener("click", () => {
  const data = readSave();
  if (!data) {
    log.textContent = "No compatible save is available.";
    return;
  }
  startRun(makeMission(data.seed, data.capacity));
  moves = [...data.moves];
  state = replay(mission, moves).at(-1).state;
  render();
  log.textContent = "Saved mission loaded.";
});
document.querySelector("#replay").addEventListener("click", () => {
  const frames = replay(mission, moves);
  const lines = frames.map(({ command, state }, index) =>
    (index + 1) + ". " + command + " → " + describe(state));
  document.querySelector("#records").textContent = lines.join("\n");
  log.textContent = frames.length + " positions recorded.";
});
document.querySelector("#test").addEventListener("click", () => {
  try {
    log.textContent = runChecks();
  } catch (error) {
    log.textContent = "Check failed: " + error.message;
  }
});
const arrow = new Map([
  ["ArrowUp", "north"], ["ArrowRight", "east"],
  ["ArrowDown", "south"], ["ArrowLeft", "west"]
]);
const board = document.querySelector("#board");
board.addEventListener("keydown", event => {
  const command = arrow.get(event.key);
  if (event.target !== board || event.altKey || event.ctrlKey ||
      event.metaKey || event.shiftKey || !command) return;
  event.preventDefault();
  if (!event.repeat) move(command);
});

function getBriefing(mission) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("Mission " + mission.seed + ": Find the Cog and Lens, then reach the Beacon.");
    }, 450);
  });
}
document.querySelector("#brief").addEventListener("click", async event => {
  const button = event.currentTarget;
  const requestedMission = mission;
  button.disabled = true;
  log.textContent = "Waiting for the radio briefing…";
  try {
    const message = await getBriefing(requestedMission);
    if (requestedMission === mission) log.textContent = message;
  } catch (error) {
    if (requestedMission === mission) log.textContent = "Radio unavailable: " + error.message;
  } finally {
    button.disabled = false;
  }
});

const seedInput = document.querySelector("#seed");
const powerInput = document.querySelector("#power");
document.querySelector("#mission-form").addEventListener("submit", event => {
  event.preventDefault();
  const seed = seedInput.valueAsNumber;
  const capacity = Number(powerInput.value);
  if (!Number.isInteger(seed) || seed < 0 || seed > 0xffffffff) {
    log.textContent = "Enter a whole mission code from 0 to 4294967295.";
    return;
  }
  const candidate = makeMission(seed, capacity);
  if (planRoute(newRun(candidate), candidate) === null) {
    log.textContent = "This battery cannot reach a rescue. Try a larger one.";
    return;
  }
  startRun(candidate);
  log.textContent = "Mission " + seed + " ready. Energy " + capacity + ".";
});

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–19
Lines 1–6 const links = { dock: { east: "workshop", south: "garden" }, workshop: { west: "dock", south: "beacon" }, garden: { north: "dock", east: "beacon" }, beacon: { north: "workshop", west: "garden" } };
Set up links. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Line 7 const directions = ["north", "east", "south", "west"];
Set up directions. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
Lines 8–11 const standard = { seed: 1, capacity: 6, pickup: { workshop: 1, garden: 2 } };
Set up standard. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Lines 12–14 const newRun = mission => ({ room: "dock", energy: mission.capacity, parts: 0, rescued: false });
Set up newRun. Keep this name attached to the same value. The arrow defines a function that this line can pass or save for later.
Line 15 function step(state, command, mission) {
Define step. The body runs when the function is called, with inputs named state, command, mission.
Line 16 if (state.rescued || state.energy === 0)
Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy. The triple equals compares without converting the value’s type.
Line 16 return state;
Leave this function and send the value back to the caller.
Line 17 if (!directions.includes(command))
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test. Check whether the collection contains the supplied item or text.
Line 17 return state;
Leave this function and send the value back to the caller.
Line 18 const room = links[state.room][command];
Set up room. 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 19 if (!room)
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
Line 19 return state;
Leave this function and send the value back to the caller.
Lines 20–43
Line 20 const parts = state.parts | (mission.pickup[room] ?? 0);
Set up parts. Keep this name attached to the same value. Use the right side only when the left side is null or undefined. Work out what is inside the brackets first, then use it as the key or index.
Lines 21–25 return { room, parts, energy: room === "dock" ? mission.capacity : state.energy - 1, rescued: room === "beacon" && parts === 3 };
Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Before the question mark comes a test. Choose the value after ? when true, or the value after : when false.
Line 27 function describe(state) {
Define describe. The body runs when the function is called, with inputs named state.
Line 28 const names = { dock: "Sky Dock", workshop: "Workshop", garden: "Garden", beacon: "Beacon" };
Set up names. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Line 29 const pieces = ["none", "Cog", "Lens", "Cog + Lens"];
Set up pieces. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
Lines 30–31 const result = state.rescued ? " Cloud creatures rescued!" : state.energy === 0 ? " Battery empty. Restart to try again." : "";
Set up result. 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.
Lines 32–33 return names[state.room] + " | Energy " + state.energy + " | Parts: " + pieces[state.parts] + "." + result;
Leave this function and send the value back to the caller. Plus adds numbers or joins text, depending on its values. Work out what is inside the brackets first, then use it as the key or index.
Line 36 function makeMission(seed, capacity = 6) {
Define makeMission. The body runs when the function is called, with inputs named seed, capacity = 6.
Line 37 const cleanSeed = seed >>> 0;
Set up cleanSeed. Keep this name attached to the same value. Shift the bits right and fill the spaces on the left with zeros.
Line 38 const draw = (Math.imul(cleanSeed, 1664525) + 1013904223) >>> 0;
Set up draw. Keep this name attached to the same value. Shift the bits right and fill the spaces on the left with zeros. Plus adds numbers or joins text, depending on its values.
Line 39 const swap = draw >= 0x80000000;
Set up swap. Keep this name attached to the same value. Check whether the first is greater than or equal to the second.
Lines 40–43 return { seed: cleanSeed, capacity, pickup: { workshop: swap ? 2 : 1, garden: swap ? 1 : 2 } };
Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Before the question mark comes a test. Choose the value after ? when true, or the value after : when false.
Lines 46–57
Line 46 function signature(state) {
Define signature. The body runs when the function is called, with inputs named state.
Line 47 return [state.room, state.energy, state.parts, state.rescued].join("|");
Leave this function and send the value back to the caller. Square brackets create an ordered array. Its first position is 0. Combine array entries into a string, with the chosen separator between entries.
Line 49 function planRoute(start, mission) {
Define planRoute. The body runs when the function is called, with inputs named start, mission.
Line 50 const queue = [{ state: start, route: [] }];
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 51 const seen = new Set([signature(start)]);
Set up seen. Keep this name attached to the same value. Use new to create a fresh Set object.
Line 52 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 53 const { state, route } = queue[head];
Set up { state, route }. 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 54 if (state.rescued)
Run this part when the test is truthy.
Line 54 return route;
Leave this function and send the value back to the caller.
Line 55 for (const command of directions) {
Take one value at a time from this sequence and run the body with it.
Line 56 const next = step(state, command, mission);
Set up next. Keep this name attached to the same value. Call step with the values inside the parentheses.
Line 57 const key = signature(next);
Set up key. Keep this name attached to the same value. Call signature with the values inside the parentheses.
Lines 58–76
Line 58 if (seen.has(key))
Run this part when the test is truthy. Check whether this key or value is already in the collection.
Line 58 continue;
Skip the rest of this pass and continue with the next loop check.
Line 59 seen.add(key);
Add the value. A Set keeps at most one copy.
Line 60 queue.push({ state: next, route: [...route, command] });
Add entries to the end of the array and return its new length.
Line 63 return null;
Leave this function and send the value back to the caller.
Line 66 const slot = "quesbo-sky-island-v1";
Set up slot. Keep this name attached to the same value.
Line 67 function decodeSave(text) {
Define decodeSave. The body runs when the function is called, with inputs named text.
Line 68 try {
Attempt these instructions. If one throws, the catch block can handle the error.
Line 69 const data = JSON.parse(text);
Set up data. Keep this name attached to the same value. Turn JSON text into values. Invalid JSON throws an error.
Lines 70–75 if (data?.version !== 1 || !Number.isInteger(data.seed) || data.seed < 0 || data.seed > 0xffffffff || ![3, 4, 6].includes(data.capacity) || !Array.isArray(data.moves) || data.moves.length > 1000 || !data.moves.every(move => directions.includes(move)))
Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy. Check whether the first value is greater than the second.
Line 75 return null;
Leave this function and send the value back to the caller.
Line 76 return data;
Leave this function and send the value back to the caller.
Lines 77–93
Line 77 catch {
Run this block if the try block throws an error.
Line 78 return null;
Leave this function and send the value back to the caller.
Line 81 function readSave() {
Define readSave. The body runs when the function is called.
Line 82 try {
Attempt these instructions. If one throws, the catch block can handle the error.
Line 83 return decodeSave(localStorage.getItem(slot));
Leave this function and send the value back to the caller. Call decodeSave with the values inside the parentheses.
Line 84 catch {
Run this block if the try block throws an error.
Line 85 return null;
Leave this function and send the value back to the caller.
Line 88 function writeSave(mission, moves) {
Define writeSave. The body runs when the function is called, with inputs named mission, moves.
Line 89 try {
Attempt these instructions. If one throws, the catch block can handle the error.
Line 90 if (moves.length > 1000)
Run this part when the test is truthy. Check whether the first value is greater than the second. Read how many items or characters there are.
Line 90 return false;
Leave this function and send the value back to the caller.
Lines 91–93 localStorage.setItem(slot, JSON.stringify({ version: 1, seed: mission.seed, capacity: mission.capacity, moves }));
Write text under one key in this browser’s local storage.
Lines 94–115
Line 94 return true;
Leave this function and send the value back to the caller.
Line 95 catch {
Run this block if the try block throws an error.
Line 96 return false;
Leave this function and send the value back to the caller.
Line 100 function replay(mission, moves) {
Define replay. The body runs when the function is called, with inputs named mission, moves.
Lines 101–106 return moves.reduce((frames, command) => { const previous = frames.at(-1).state; const state = step(previous, command, mission); frames.push({ command, state, changed: state !== previous }); return frames; }, [{ command: "start", state: newRun(mission), changed: false }]);
Leave this function and send the value back to the caller. Combine the entries into a single result, one entry at a time.
Line 109 function runChecks() {
Define runChecks. The body runs when the function is called.
Line 110 let passed = 0;
Set up passed. Give this name a starting value that later code can change.
Line 111 function expect(condition, title) {
Define expect. The body runs when the function is called, with inputs named condition, title.
Line 112 if (!condition)
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
Line 112 throw new Error(title);
Stop this part of the program and report the problem to the caller or a matching catch block.
Line 113 passed += 1;
Update the existing value with the operation shown.
Line 115 const mission = makeMission(1);
Set up mission. Keep this name attached to the same value. Call makeMission with the values inside the parentheses.
Lines 116–127
Line 116 const start = Object.freeze(newRun(mission));
Set up start. Keep this name attached to the same value. Prevent direct edits to the properties of this object.
Line 117 const workshop = step(start, "east", mission);
Set up workshop. Keep this name attached to the same value. Call step with the values inside the parentheses.
Line 118 expect(start.room === "dock" && workshop.room === "workshop", "Move keeps old state");
Call expect with the values inside the parentheses.
Line 119 expect(step(start, "north", mission) === start, "Blocked move keeps state");
Call expect with the values inside the parentheses.
Line 120 expect(step(workshop, "west", mission).energy === 6, "Dock recharges");
Call expect with the values inside the parentheses.
Line 121 const route = planRoute(start, mission);
Set up route. Keep this name attached to the same value. Call planRoute with the values inside the parentheses.
Line 122 expect(route !== null && route.length === 4, "Shortest rescue has four moves");
Call expect with the values inside the parentheses.
Line 123 const final = replay(mission, route).at(-1).state;
Set up final. Keep this name attached to the same value. Call replay with the values inside the parentheses. Call replay(mission, route).at with the values inside the parentheses.
Line 124 expect(final.rescued && final.parts === 3, "Replay reaches rescue");
Call expect with the values inside the parentheses.
Line 125 expect(step(final, "west", mission) === final, "Rescue ends movement");
Call expect with the values inside the parentheses.
Line 126 expect(planRoute(newRun(makeMission(1, 1)), makeMission(1, 1)) === null, "Empty routes terminate");
Call expect with the values inside the parentheses.
Line 127 expect(decodeSave('{"version":2}') === null, "Unknown save version is rejected");
Call expect with the values inside the parentheses.
Lines 128–144
Lines 128–129 expect(decodeSave('{"version":1,"seed":0,"capacity":6,"moves":["jump"]}') === null, "Unknown commands are rejected");
Call expect with the values inside the parentheses.
Lines 130–131 expect(makeMission(1).pickup.workshop !== makeMission(1000).pickup.workshop, "Different seeds can swap the parts");
Call expect with the values inside the parentheses.
Line 132 return passed + " checks passed.";
Leave this function and send the value back to the caller. Plus adds numbers or joins text, depending on its values.
Line 135 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 136 const log = document.querySelector("#log");
Set up log. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 137 let mission = makeMission(1);
Set up mission. Give this name a starting value that later code can change. Call makeMission with the values inside the parentheses.
Line 138 let state;
Set up state. Give this name a starting value that later code can change.
Line 139 let moves;
Set up moves. Give this name a starting value that later code can change.
Line 140 function render() {
Define render. The body runs when the function is called.
Line 141 status.textContent = describe(state);
Call describe with the values inside the parentheses. Replace the element’s displayed text. The browser treats the value as text.
Line 143 function startRun(nextMission) {
Define startRun. The body runs when the function is called, with inputs named nextMission.
Line 144 mission = nextMission;
Store the result in the name or property to the left.
Lines 145–158
Line 145 state = newRun(mission);
Call newRun with the values inside the parentheses. Store the result in the name or property to the left.
Line 146 moves = [];
Square brackets create an ordered array. Its first position is 0. Store the result in the name or property to the left.
Line 147 log.textContent = "";
Replace the element’s displayed text. The browser treats the value as text.
Line 148 render();
Call render with the values inside the parentheses.
Line 150 function move(command) {
Define move. The body runs when the function is called, with inputs named command.
Line 151 const next = step(state, command, mission);
Set up next. Keep this name attached to the same value. Call step with the values inside the parentheses.
Line 152 if (next === state) {
Run this part when the test is truthy. The triple equals compares without converting the value’s type.
Line 153 log.textContent = "Pip stays put.";
Replace the element’s displayed text. The browser treats the value as text.
Line 154 return;
Leave this function immediately.
Line 156 moves.push(command);
Add entries to the end of the array and return its new length.
Line 157 state = next;
Store the result in the name or property to the left.
Line 158 log.textContent = "";
Replace the element’s displayed text. The browser treats the value as text.
Lines 159–176
Line 159 render();
Call render with the values inside the parentheses.
Line 161 for (const button of document.querySelectorAll("[data-move]")) {
Take one value at a time from this sequence and run the body with it.
Line 162 button.addEventListener("click", () => move(button.dataset.move));
Register a function the browser should call when the named event happens.
Line 164 document.querySelector("#restart").addEventListener("click", () => startRun({ ...mission }));
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 165 startRun(mission);
Call startRun with the values inside the parentheses.
Line 166 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 167 const route = planRoute(state, mission);
Set up route. Keep this name attached to the same value. Call planRoute with the values inside the parentheses.
Lines 168–170 log.textContent = route === null ? "No rescue route from here." : route.length === 0 ? "Rescue complete." : "Try " + route[0] + ". A shortest route takes " + route.length + " moves.";
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 172 document.querySelector("#save").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 173 log.textContent = writeSave(mission, moves) ? "Mission saved." : "Saving is unavailable.";
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 175 document.querySelector("#load").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 176 const data = readSave();
Set up data. Keep this name attached to the same value. Call readSave with the values inside the parentheses.
Lines 177–191
Line 177 if (!data) {
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
Line 178 log.textContent = "No compatible save is available.";
Replace the element’s displayed text. The browser treats the value as text.
Line 179 return;
Leave this function immediately.
Line 181 startRun(makeMission(data.seed, data.capacity));
Call startRun with the values inside the parentheses.
Line 182 moves = [...data.moves];
Square brackets create an ordered array. Its first position is 0. Three dots unpack the existing entries here.
Line 183 state = replay(mission, moves).at(-1).state;
Call replay with the values inside the parentheses. Call replay(mission, moves).at with the values inside the parentheses.
Line 184 render();
Call render with the values inside the parentheses.
Line 185 log.textContent = "Saved mission loaded.";
Replace the element’s displayed text. The browser treats the value as text.
Line 187 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 188 const frames = replay(mission, moves);
Set up frames. Keep this name attached to the same value. Call replay with the values inside the parentheses.
Lines 189–190 const lines = frames.map(({ command, state }, index) => (index + 1) + ". " + command + " → " + describe(state));
Set up lines. Keep this name attached to the same value. Make a new array with one result for each input entry.
Line 191 document.querySelector("#records").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.
Lines 192–209
Line 192 log.textContent = frames.length + " positions recorded.";
Plus adds numbers or joins text, depending on its values. Read how many items or characters there are.
Line 194 document.querySelector("#test").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 195 try {
Attempt these instructions. If one throws, the catch block can handle the error.
Line 196 log.textContent = runChecks();
Call runChecks with the values inside the parentheses. Replace the element’s displayed text. The browser treats the value as text.
Line 197 catch (error) {
Run this block if the try block throws an error.
Line 198 log.textContent = "Check failed: " + error.message;
Plus adds numbers or joins text, depending on its values. Replace the element’s displayed text. The browser treats the value as text.
Lines 201–204 const arrow = new Map([ ["ArrowUp", "north"], ["ArrowRight", "east"], ["ArrowDown", "south"], ["ArrowLeft", "west"] ]);
Set up arrow. Keep this name attached to the same value. Use new to create a fresh Map object.
Line 205 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 206 board.addEventListener("keydown", event => {
This function body is passed as an input. Register a function the browser should call when the named event happens.
Line 207 const command = arrow.get(event.key);
Set up command. Keep this name attached to the same value. Read the matching value from the collection.
Lines 208–209 if (event.target !== board || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || !command)
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 209 return;
Leave this function immediately.
Lines 210–227
Line 210 event.preventDefault();
Stop the browser’s usual response to this event where permitted.
Line 211 if (!event.repeat)
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
Line 211 move(command);
Call move with the values inside the parentheses.
Line 214 function getBriefing(mission) {
Define getBriefing. The body runs when the function is called, with inputs named mission.
Lines 215–219 return new Promise(resolve => { setTimeout(() => { resolve("Mission " + mission.seed + ": Find the Cog and Lens, then reach the Beacon."); }, 450); });
Leave this function and send the value back to the caller. Use new to create a fresh Promise object.
Line 221 document.querySelector("#brief").addEventListener("click", async event => {
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 222 const button = event.currentTarget;
Set up button. Keep this name attached to the same value.
Line 223 const requestedMission = mission;
Set up requestedMission. Keep this name attached to the same value.
Line 224 button.disabled = true;
Store the result in the name or property to the left.
Line 225 log.textContent = "Waiting for the radio briefing…";
Replace the element’s displayed text. The browser treats the value as text.
Line 226 try {
Attempt these instructions. If one throws, the catch block can handle the error.
Line 227 const message = await getBriefing(requestedMission);
Set up message. Keep this name attached to the same value. Pause this async function until the promise settles, while other work can continue. Call getBriefing with the values inside the parentheses.
Lines 228–240
Line 228 if (requestedMission === mission)
Run this part when the test is truthy. The triple equals compares without converting the value’s type.
Line 228 log.textContent = message;
Replace the element’s displayed text. The browser treats the value as text.
Line 229 catch (error) {
Run this block if the try block throws an error.
Line 230 if (requestedMission === mission)
Run this part when the test is truthy. The triple equals compares without converting the value’s type.
Line 230 log.textContent = "Radio unavailable: " + error.message;
Plus adds numbers or joins text, depending on its values. Replace the element’s displayed text. The browser treats the value as text.
Line 231 finally {
Run this last block whether the earlier code succeeded or threw an error.
Line 232 button.disabled = false;
Store the result in the name or property to the left.
Line 236 const seedInput = document.querySelector("#seed");
Set up seedInput. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 237 const powerInput = document.querySelector("#power");
Set up powerInput. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 238 document.querySelector("#mission-form").addEventListener("submit", event => {
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 239 event.preventDefault();
Stop the browser’s usual response to this event where permitted.
Line 240 const seed = seedInput.valueAsNumber;
Set up seed. Keep this name attached to the same value.
Lines 241–252
Line 241 const capacity = Number(powerInput.value);
Set up capacity. Keep this name attached to the same value. Convert the input to a number when possible.
Line 242 if (!Number.isInteger(seed) || seed < 0 || seed > 0xffffffff) {
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 243 log.textContent = "Enter a whole mission code from 0 to 4294967295.";
Replace the element’s displayed text. The browser treats the value as text.
Line 244 return;
Leave this function immediately.
Line 246 const candidate = makeMission(seed, capacity);
Set up candidate. Keep this name attached to the same value. Call makeMission with the values inside the parentheses.
Line 247 if (planRoute(newRun(candidate), candidate) === null) {
Run this part when the test is truthy. The triple equals compares without converting the value’s type. Call planRoute with the values inside the parentheses.
Line 248 log.textContent = "This battery cannot reach a rescue. Try a larger one.";
Replace the element’s displayed text. The browser treats the value as text.
Line 249 return;
Leave this function immediately.
Line 251 startRun(candidate);
Call startRun with the values inside the parentheses.
Line 252 log.textContent = "Mission " + seed + " ready. Energy " + capacity + ".";
Plus adds numbers or joins text, depending on its values. Replace the element’s displayed text. The browser treats the value as text.

Mission challenge

Design a fifth room. Update the map, the room names, both directions of any new paths, and at least one simulator check. Verify that every battery option the launcher accepts still gives Pip a route to a rescue.

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