JavaScript 41 · Separate the Mission Rules from the Screen

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

Make Pip's game rules work independently of its buttons.

Pip watches six little cloud creatures gather safely in the glow of the restored wind beacon at dawn.
Mission Move Pip with a function you can test without touching the page.

Get ready

New chapter. Release a complete, replayable rescue game. Start with this complete version of Pip’s mission, then compare it with the last chapter’s project.

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.

Command. The browser supplies a move. → Rule. The engine calculates the next snapshot. → View. The page displays that snapshot.
Command → Rule → View

Understand the JavaScript in this lesson

Language to look for Pure functions, Object lookup, Bit flags, Nullish coalescing.

1. Describe the island in data

The links object is a map of maps. At the Sky Dock, links.dock has two entries. Looking up a variable key takes square brackets, so links[state.room][command] means first get the current room's paths, then get the destination for the requested direction. An absent path gives undefined, so the guard returns before it spends energy.

const room = links[state.room][command];

2. Represent two pickups with two bits

Cog is represented by 1, Lens by 2. In binary those are 01 and 10. The bitwise OR operator | sets bits that appear on either side. Combining both creates 11, which is decimal 3. The ?? operator supplies zero only when a room lookup gives null or undefined. Gathering a part twice keeps the same bits turned on.

const parts = state.parts | (mission.pickup[room] ?? 0);

3. Write a pure game rule

A pure function produces the same output for the same inputs and leaves the inputs alone. The object after return is a fresh snapshot. The room and parts properties use shorthand because they share their variables' names. The conditional expression uses ? for the Dock case and : for the ordinary one-energy cost. The engine only calculates values, so a simulator can use it without a page.

energy: room === "dock" ? mission.capacity : state.energy - 1,

4. Connect rule and view

The button's dataset.move reads the HTML data-move attribute. The page sends that string to move, which asks step for the next state and only then redraws the status. The identity check next === state spots the exact same object returned by a blocked command. Press East and West to see the battery refill.

if (next === state) {
Follow what happens step by step
  1. East from Sky Dock
    Workshop, 5 energy, CogWhy A fresh snapshot adds bit 1 and spends one energy.
  2. West from Workshop
    Sky Dock, 6 energy, CogWhy The Dock substitutes the mission's full capacity.

Predict before you run If Pip enters the Workshop twice, can that add a Lens?

Reveal the answer

No. The Cog flag OR itself still describes one Cog.

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>

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;
}

const status = document.querySelector("#status");
const log = document.querySelector("#log");
let mission = standard;
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);

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–40
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 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 37 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 38 let mission = standard;
Set up mission. Give this name a starting value that later code can change.
Line 39 let state;
Set up state. Give this name a starting value that later code can change.
Line 40 let moves;
Set up moves. Give this name a starting value that later code can change.
Lines 41–54
Line 41 function render() {
Define render. The body runs when the function is called.
Line 42 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 44 function startRun(nextMission) {
Define startRun. The body runs when the function is called, with inputs named nextMission.
Line 45 mission = nextMission;
Store the result in the name or property to the left.
Line 46 state = newRun(mission);
Call newRun with the values inside the parentheses. Store the result in the name or property to the left.
Line 47 moves = [];
Square brackets create an ordered array. Its first position is 0. Store the result in the name or property to the left.
Line 48 log.textContent = "";
Replace the element’s displayed text. The browser treats the value as text.
Line 49 render();
Call render with the values inside the parentheses.
Line 51 function move(command) {
Define move. The body runs when the function is called, with inputs named command.
Line 52 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 53 if (next === state) {
Run this part when the test is truthy. The triple equals compares without converting the value’s type.
Line 54 log.textContent = "Pip stays put.";
Replace the element’s displayed text. The browser treats the value as text.
Lines 55–66
Line 55 return;
Leave this function immediately.
Line 57 moves.push(command);
Add entries to the end of the array and return its new length.
Line 58 state = next;
Store the result in the name or property to the left.
Line 59 log.textContent = "";
Replace the element’s displayed text. The browser treats the value as text.
Line 60 render();
Call render with the values inside the parentheses.
Line 62 for (const button of document.querySelectorAll("[data-move]")) {
Take one value at a time from this sequence and run the body with it.
Line 63 button.addEventListener("click", () => move(button.dataset.move));
Register a function the browser should call when the named event happens.
Line 65 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 66 startRun(mission);
Call startRun with the values inside the parentheses.

Mission challenge

Add a Sky Dock exit name to a copy of the mission map and predict which command validation must accept it.

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