JavaScript 49 · Check a Custom Mission Before Launch

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

Let players choose mission codes and battery settings while checking that a rescue is possible.

Pip watches six little cloud creatures gather safely in the glow of the restored wind beacon at dawn.
Mission Read and validate a form, then use the planner to screen a proposed mission.

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.

Form. Read a seed and energy capacity. → Audit. Search for a path to rescue. → Launch. Replace the current run only when a path exists.
Form → Audit → Launch

Understand the JavaScript in this lesson

Language to look for Number input, valueAsNumber, Number conversion, Form submit, Range checks.

1. Read numbers from the controls

The form collects the mission code and battery capacity. For an HTML number input, valueAsNumber gives a number or NaN when no number can be read. A select element's value is a string. Number converts the selected capacity into a number so step can subtract one from it and compare it with energy values consistently.

const capacity = Number(powerInput.value);

2. Keep input within the mission format

The form's range and required attributes help players catch an invalid entry in the browser. JavaScript checks the range again before creating a mission. Number.isInteger rejects fractions and NaN. The maximum literal 0xffffffff is the largest unsigned 32-bit number, so the planner and the seed function agree on what codes are valid.

if (!Number.isInteger(seed) || seed < 0 || seed > 0xffffffff) {

3. Audit reachability before replacing the run

The submit handler uses event.preventDefault() to keep the page from navigating. It prepares a candidate mission and asks planRoute to search from a fresh snapshot. When planRoute returns null, it reports the lack of a route and returns before touching the current run. A number in the allowed range can still create a game that is impossible to complete. The planner checks that separate rule.

if (planRoute(newRun(candidate), candidate) === null) {

4. Compare two difficulty settings

Start a six-energy mission and take East, South, West, East to see a finish. At three energy, that route depletes the battery before its fourth move. A trip via the Sky Dock can restore enough energy for the last part of the rescue. The shortest route still has four moves, so planRoute can help players discover an order their battery can support.

startRun(candidate);
Follow what happens step by step
  1. Seed 1000, start with 3 energy
    Mission 1000 ready. Energy 3.Why The planner finds a route using a recharge.
  2. East, West, South, East
    Beacon, 1 energy, both parts, rescue completeWhy Returning to the Dock restores all 3 energy before the final two moves.

Predict before you run If you temporarily add a one-energy option, why does the launcher refuse it?

Reveal the answer

Each one-move exit from the Dock leaves Pip at zero energy with only one part. The rules stop movement there, so the search cannot reach a rescue.

Complete checkpoint

HTML · the page and controls

<section id="board" tabindex="0" role="region" aria-label="Pip's rover controls" aria-describedby="how">
  <p id="how">Use the direction buttons.</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>
<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 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.";
});
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–72
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 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 67 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 68 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 69 let state;
Set up state. Give this name a starting value that later code can change.
Line 70 let moves;
Set up moves. Give this name a starting value that later code can change.
Line 71 function render() {
Define render. The body runs when the function is called.
Line 72 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.
Lines 74–87
Line 74 function startRun(nextMission) {
Define startRun. The body runs when the function is called, with inputs named nextMission.
Line 75 mission = nextMission;
Store the result in the name or property to the left.
Line 76 state = newRun(mission);
Call newRun with the values inside the parentheses. Store the result in the name or property to the left.
Line 77 moves = [];
Square brackets create an ordered array. Its first position is 0. Store the result in the name or property to the left.
Line 78 log.textContent = "";
Replace the element’s displayed text. The browser treats the value as text.
Line 79 render();
Call render with the values inside the parentheses.
Line 81 function move(command) {
Define move. The body runs when the function is called, with inputs named command.
Line 82 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 83 if (next === state) {
Run this part when the test is truthy. The triple equals compares without converting the value’s type.
Line 84 log.textContent = "Pip stays put.";
Replace the element’s displayed text. The browser treats the value as text.
Line 85 return;
Leave this function immediately.
Line 87 moves.push(command);
Add entries to the end of the array and return its new length.
Lines 88–104
Line 88 state = next;
Store the result in the name or property to the left.
Line 89 log.textContent = "";
Replace the element’s displayed text. The browser treats the value as text.
Line 90 render();
Call render with the values inside the parentheses.
Line 92 for (const button of document.querySelectorAll("[data-move]")) {
Take one value at a time from this sequence and run the body with it.
Line 93 button.addEventListener("click", () => move(button.dataset.move));
Register a function the browser should call when the named event happens.
Line 95 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 96 startRun(mission);
Call startRun with the values inside the parentheses.
Line 97 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 98 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 99–101 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 103 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 104 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.
Lines 105–118
Line 105 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 106 event.preventDefault();
Stop the browser’s usual response to this event where permitted.
Line 107 const seed = seedInput.valueAsNumber;
Set up seed. Keep this name attached to the same value.
Line 108 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 109 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 110 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 111 return;
Leave this function immediately.
Line 113 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 114 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 115 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 116 return;
Leave this function immediately.
Line 118 startRun(candidate);
Call startRun with the values inside the parentheses.
Lines 119–119
Line 119 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

Add the one-energy option on a copy and verify that the rejection leaves an in-progress mission exactly where you left it.

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