JavaScript 18 · Activate the Beacon with a win condition

JavaScript lesson 18 of 50 · Early intermediate · About 40 minutes

Bring the gathered parts to the Beacon and complete the rescue.

Pip pauses where stone paths branch toward a crystal-roof workshop, a hanging garden and a distant beacon.
Mission Check the location and both inventory items, then record that the mission has finished.

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.

Check the location. The player must stand at the Beacon. → Check every part. Look for Cog and Lens in the inventory. → Finish the mission. Set the rescue flag and announce success.
Check the location → Check every part → Finish the mission

Understand the JavaScript in this lesson

Language to look for Boolean state, every, arrow function, success condition, disable controls.

1. Write the recipe as data

The Beacon requires Cog and Lens. Store these two items in needed. Listing them outside the function makes the rule easy to read and revise. The rescue function checks the location first so you must actually arrive at the Beacon before trying the recipe.

const needed = ["Cog", "Lens"];

2. Ask the same question about each part

The array method every visits each required item and returns true only if every check succeeds. The arrow function takes one item called part and returns the result of includes(part). An arrow with a single expression returns that expression’s result automatically.

const ready = needed.every(part => state.inventory.includes(part));

3. Block incomplete attempts

If the recipe check is false, !ready is true. The branch shows which parts are needed and returns before altering state. The player can still move around the island and look for the missing item. Compare this guard with the earlier route and battery guards.

if (!ready) {

4. Render the finished state

A successful attempt sets the Boolean flag state.rescued to true, calls render() and announces that the creatures are safe. The same flag disables the travel and action buttons, so the player can tell the mission is finished. This version can be played again by reloading the page.

state.rescued = true;
Follow what happens step by step
  1. Try activating the Beacon at Sky Dock.
    Travel to the Beacon first.Why The location guard returns without checking the parts.
  2. Collect both parts, move to Beacon and activate it.
    Beacon lit. The cloud creatures are safe!Why Both inventory checks succeed, so render disables the controls.

Predict before you run Could collecting Lens before Cog prevent a successful rescue?

Reveal the answer

The check does not compare positions. It asks whether each required part appears somewhere in the inventory.

Complete checkpoint

HTML · the page and controls

<section aria-labelledby="mission-title">
  <h2 id="mission-title">Sky Island Rescue · Island mission</h2>
  <p>Location: <span id="place"></span></p>
  <p>Energy: <span id="energy"></span></p>
  <p>Inventory: <span id="inventory"></span></p>
  <button type="button" data-destination="Sky Dock">Sky Dock</button>
  <button type="button" data-destination="Workshop">Workshop</button>
  <button type="button" data-destination="Garden">Garden</button>
  <button type="button" data-destination="Beacon">Beacon</button>
  <button id="charge" type="button">Recharge at Sky Dock</button>
  <button id="collect" type="button">Collect the local part</button>
  <button id="rescue" type="button">Activate the Beacon</button>
  <p id="report" role="status">Choose a connected destination.</p>
</section>

JavaScript · the instructions

const routes = {
  "Sky Dock": ["Workshop", "Garden"],
  Workshop: ["Sky Dock", "Beacon"],
  Garden: ["Sky Dock", "Beacon"],
  Beacon: ["Workshop", "Garden"]
};

const MAX_ENERGY = 6;

const partsAt = { Workshop: "Cog", Garden: "Lens" };

const needed = ["Cog", "Lens"];

const state = { place: "Sky Dock", energy: MAX_ENERGY, inventory: [], rescued: false };

const moveButtons = [...document.querySelectorAll("[data-destination]")];

function showMessage(message) {
  document.querySelector("#report").textContent = message;
}

function render() {
  document.querySelector("#place").textContent = state.place;
  document.querySelector("#energy").textContent = state.energy;
  document.querySelector("#inventory").textContent = state.inventory.join(", ") || "Empty";
  for (const button of moveButtons) button.disabled = state.rescued;
  document.querySelector("#charge").disabled = state.rescued;
  document.querySelector("#collect").disabled = state.rescued;
  document.querySelector("#rescue").disabled = state.rescued;
}

function travel(event) {
  const destination = event.currentTarget.dataset.destination;
  if (state.rescued) return;
  if (!routes[state.place].includes(destination)) {
    showMessage("No route from " + state.place + " to " + destination + ".");
    return;
  }
  if (state.energy === 0) {
    showMessage("No energy left. " + (state.place === "Sky Dock" ? "Recharge to travel." : "Reload the page to try again."));
    return;
  }
  state.energy -= 1;
  state.place = destination;
  render();
  showMessage("Pip reaches " + destination + ".");
}

function recharge() {
  if (state.place !== "Sky Dock") {
    showMessage("Recharge is only available at Sky Dock.");
    return;
  }
  state.energy = MAX_ENERGY;
  render();
  showMessage("Pip’s battery is full.");
}

function collect() {
  const part = partsAt[state.place];
  if (!part) {
    showMessage("There is no part here.");
    return;
  }
  if (state.inventory.includes(part)) {
    showMessage("Pip already has the " + part + ".");
    return;
  }
  state.inventory.push(part);
  render();
  showMessage("Pip collects the " + part + ".");
}

function rescue() {
  if (state.place !== "Beacon") {
    showMessage("Travel to the Beacon first.");
    return;
  }
  const ready = needed.every(part => state.inventory.includes(part));
  if (!ready) {
    showMessage("The Beacon needs both the Cog and the Lens.");
    return;
  }
  state.rescued = true;
  render();
  showMessage("Beacon lit. The cloud creatures are safe!");
}

for (const button of moveButtons) {
  button.addEventListener("click", travel);
}
document.querySelector("#charge").addEventListener("click", recharge);
document.querySelector("#collect").addEventListener("click", collect);
document.querySelector("#rescue").addEventListener("click", rescue);
render();

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–25
Lines 1–6 const routes = { "Sky Dock": ["Workshop", "Garden"], Workshop: ["Sky Dock", "Beacon"], Garden: ["Sky Dock", "Beacon"], Beacon: ["Workshop", "Garden"] };
Set up routes. 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 8 const MAX_ENERGY = 6;
Set up MAX_ENERGY. Keep this name attached to the same value.
Line 10 const partsAt = { Workshop: "Cog", Garden: "Lens" };
Set up partsAt. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Line 12 const needed = ["Cog", "Lens"];
Set up needed. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
Line 14 const state = { place: "Sky Dock", energy: MAX_ENERGY, inventory: [], rescued: false };
Set up state. 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 16 const moveButtons = [...document.querySelectorAll("[data-destination]")];
Set up moveButtons. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0. Three dots unpack the existing entries here.
Line 18 function showMessage(message) {
Define showMessage. The body runs when the function is called, with inputs named message.
Line 19 document.querySelector("#report").textContent = message;
Replace the element’s displayed text. The browser treats the value as text.
Line 22 function render() {
Define render. The body runs when the function is called.
Line 23 document.querySelector("#place").textContent = state.place;
Replace the element’s displayed text. The browser treats the value as text.
Line 24 document.querySelector("#energy").textContent = state.energy;
Replace the element’s displayed text. The browser treats the value as text.
Line 25 document.querySelector("#inventory").textContent = state.inventory.join(", ") || "Empty";
JavaScript tries the right side only when the left side is falsy. Combine array entries into a string, with the chosen separator between entries.
Lines 26–37
Line 26 for (const button of moveButtons)
Take one value at a time from this sequence and run the body with it.
Line 26 button.disabled = state.rescued;
Store the result in the name or property to the left.
Line 27 document.querySelector("#charge").disabled = state.rescued;
Store the result in the name or property to the left.
Line 28 document.querySelector("#collect").disabled = state.rescued;
Store the result in the name or property to the left.
Line 29 document.querySelector("#rescue").disabled = state.rescued;
Store the result in the name or property to the left.
Line 32 function travel(event) {
Define travel. The body runs when the function is called, with inputs named event.
Line 33 const destination = event.currentTarget.dataset.destination;
Set up destination. Keep this name attached to the same value.
Line 34 if (state.rescued)
Run this part when the test is truthy.
Line 34 return;
Leave this function immediately.
Line 35 if (!routes[state.place].includes(destination)) {
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test. Work out what is inside the brackets first, then use it as the key or index.
Line 36 showMessage("No route from " + state.place + " to " + destination + ".");
Call showMessage with the values inside the parentheses.
Line 37 return;
Leave this function immediately.
Lines 39–54
Line 39 if (state.energy === 0) {
Run this part when the test is truthy. The triple equals compares without converting the value’s type.
Line 40 showMessage("No energy left. " + (state.place === "Sky Dock" ? "Recharge to travel." : "Reload the page to try again."));
Call showMessage with the values inside the parentheses.
Line 41 return;
Leave this function immediately.
Line 43 state.energy -= 1;
Update the existing value with the operation shown.
Line 44 state.place = destination;
Store the result in the name or property to the left.
Line 45 render();
Call render with the values inside the parentheses.
Line 46 showMessage("Pip reaches " + destination + ".");
Call showMessage with the values inside the parentheses.
Line 49 function recharge() {
Define recharge. The body runs when the function is called.
Line 50 if (state.place !== "Sky Dock") {
Run this part when the test is truthy. The exclamation and two equals signs check whether values differ without type conversion.
Line 51 showMessage("Recharge is only available at Sky Dock.");
Call showMessage with the values inside the parentheses.
Line 52 return;
Leave this function immediately.
Line 54 state.energy = MAX_ENERGY;
Store the result in the name or property to the left.
Lines 55–70
Line 55 render();
Call render with the values inside the parentheses.
Line 56 showMessage("Pip’s battery is full.");
Call showMessage with the values inside the parentheses.
Line 59 function collect() {
Define collect. The body runs when the function is called.
Line 60 const part = partsAt[state.place];
Set up part. 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 61 if (!part) {
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
Line 62 showMessage("There is no part here.");
Call showMessage with the values inside the parentheses.
Line 63 return;
Leave this function immediately.
Line 65 if (state.inventory.includes(part)) {
Run this part when the test is truthy. Check whether the collection contains the supplied item or text.
Line 66 showMessage("Pip already has the " + part + ".");
Call showMessage with the values inside the parentheses.
Line 67 return;
Leave this function immediately.
Line 69 state.inventory.push(part);
Add entries to the end of the array and return its new length.
Line 70 render();
Call render with the values inside the parentheses.
Lines 71–86
Line 71 showMessage("Pip collects the " + part + ".");
Call showMessage with the values inside the parentheses.
Line 74 function rescue() {
Define rescue. The body runs when the function is called.
Line 75 if (state.place !== "Beacon") {
Run this part when the test is truthy. The exclamation and two equals signs check whether values differ without type conversion.
Line 76 showMessage("Travel to the Beacon first.");
Call showMessage with the values inside the parentheses.
Line 77 return;
Leave this function immediately.
Line 79 const ready = needed.every(part => state.inventory.includes(part));
Set up ready. Keep this name attached to the same value. Check whether every array entry passes the test.
Line 80 if (!ready) {
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
Line 81 showMessage("The Beacon needs both the Cog and the Lens.");
Call showMessage with the values inside the parentheses.
Line 82 return;
Leave this function immediately.
Line 84 state.rescued = true;
Store the result in the name or property to the left.
Line 85 render();
Call render with the values inside the parentheses.
Line 86 showMessage("Beacon lit. The cloud creatures are safe!");
Call showMessage with the values inside the parentheses.
Lines 89–95
Line 89 for (const button of moveButtons) {
Take one value at a time from this sequence and run the body with it.
Line 90 button.addEventListener("click", travel);
Register a function the browser should call when the named event happens.
Line 92 document.querySelector("#charge").addEventListener("click", recharge);
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 93 document.querySelector("#collect").addEventListener("click", collect);
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 94 document.querySelector("#rescue").addEventListener("click", rescue);
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 95 render();
Call render with the values inside the parentheses.

Mission challenge

Write down a route that tests the missing-parts message before completing the rescue.

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