JavaScript 21 · Separate the game rules from the screen

JavaScript lesson 21 of 50 · Intermediate · About 30 minutes

Give Pip a game engine that works before any buttons or pictures are connected.

At the workshop, Pip reaches toward a glowing crystal battery beside a copper coil, a gear and a map of the floating islands.
Mission Write a rule that checks an exit and gives back a new rover state.

Get ready

New chapter. Organise the game engine, save progress and test your rules. Start with this complete version of Pip’s mission, then compare it with the last chapter’s project.

Open Complete checkpoint below. Paste the JavaScript into a blank JavaScript editor and run it.

Read the room. Look up the exits for Pip’s current location. → Check the rules. A valid exit and one energy allow travel. → Return the result. A successful move creates a new state.
Read the room → Check the rules → Return the result

Understand the JavaScript in this lesson

Language to look for Pure functions, State objects, Guard clauses, Functions and display.

1. Read the map as data

MAP is a dictionary in the form of an object. Each key is a place. Each value is an array of places you may reach in one move. MAP[state.room] uses the current room name as a key and retrieves the matching exits. Square brackets choose the key using a value, so the same instruction works in every room.

const exits = MAP[state.room];

2. Check the move before spending energy

A guard is a check that deals with a situation early. includes asks whether the destination appears in the exit array. ! flips true to false and false to true. || means either condition is enough to block the move. The early return sends the original state back without doing the later instructions.

if (!exits.includes(destination) || state.energy < 1) {
    return state;
  }

3. Calculate and display in separate places

The final return builds a fresh object with the destination and one less energy. It carries the bag and rescue flag forward. The rule only reads the state and destination it receives and gives back a result. The display task happens separately when console.log prints a chosen value. Later, a button can call this same rule without rewriting it.

room: destination,
    energy: state.energy - 1,
Follow what happens step by step
  1. Start at Hub
    Pip has five energy.Why makeState supplies the starting values.
  2. Try Workshop
    A new Workshop state has four energy.Why Workshop is in the Hub exits, so one unit is spent.
  3. Try Beacon directly from the original Hub state
    The original object is returned.Why Beacon is not one of Hub’s direct exits.

Predict before you run If you test both moves, why does the original still have five energy?

Reveal the answer

A valid move creates a new object. The blocked move returns the original and never reaches the subtraction.

Complete checkpoint

JavaScript · the instructions

const MAP = {
  Hub: ["Workshop", "Garden"],
  Workshop: ["Hub", "Garden"],
  Garden: ["Hub", "Workshop", "Beacon"],
  Beacon: ["Garden"]
};
const PARTS = { Workshop: "coil", Garden: "cell" };

function makeState() {
  return { room: "Hub", energy: 5, bag: [], rescued: false };
}
function move(state, destination) {
  const exits = MAP[state.room];
  if (!exits.includes(destination) || state.energy < 1) {
    return state;
  }
  return {
    room: destination,
    energy: state.energy - 1,
    bag: state.bag,
    rescued: state.rescued
  };
}
const first = makeState();
const moved = move(first, "Workshop");
const refused = move(first, "Beacon");
console.log("After move:", moved.room, moved.energy);
console.log("Original:", first.room, first.energy);
console.log("Blocked:", refused === first);

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–26
Lines 1–6 const MAP = { Hub: ["Workshop", "Garden"], Workshop: ["Hub", "Garden"], Garden: ["Hub", "Workshop", "Beacon"], Beacon: ["Garden"] };
Set up MAP. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values. Square brackets create an ordered array. Its first position is 0.
Line 7 const PARTS = { Workshop: "coil", Garden: "cell" };
Set up PARTS. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Line 9 function makeState() {
Define makeState. The body runs when the function is called.
Line 10 return { room: "Hub", energy: 5, bag: [], rescued: false };
Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Square brackets create an ordered array. Its first position is 0.
Line 12 function move(state, destination) {
Define move. The body runs when the function is called, with inputs named state, destination.
Line 13 const exits = MAP[state.room];
Set up exits. 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 14 if (!exits.includes(destination) || state.energy < 1) {
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 15 return state;
Leave this function and send the value back to the caller.
Lines 17–22 return { room: destination, energy: state.energy - 1, bag: state.bag, rescued: state.rescued };
Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Minus subtracts the right value.
Line 24 const first = makeState();
Set up first. Keep this name attached to the same value. Call makeState with the values inside the parentheses.
Line 25 const moved = move(first, "Workshop");
Set up moved. Keep this name attached to the same value. Call move with the values inside the parentheses.
Line 26 const refused = move(first, "Beacon");
Set up refused. Keep this name attached to the same value. Call move with the values inside the parentheses.
Lines 27–29
Line 27 console.log("After move:", moved.room, moved.energy);
Show a message or value in the output. Use it to watch the game work.
Line 28 console.log("Original:", first.room, first.energy);
Show a message or value in the output. Use it to watch the game work.
Line 29 console.log("Blocked:", refused === first);
Show a message or value in the output. Use it to watch the game work.

Mission challenge

Pass the Workshop result into a move to Garden. Print all three states and compare their energy.

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