JavaScript 16 · Give every move an energy cost

JavaScript lesson 16 of 50 · Early intermediate · About 35 minutes

Add an energy meter and a recharge point to the island map.

Pip pauses where stone paths branch toward a crystal-roof workshop, a hanging garden and a distant beacon.
Mission Make legal travel cost one energy, and recharge to six units only at Sky Dock.

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 route. Reject destinations with no direct trail. → Check and spend. Use one energy for a successful move. → Recharge. Refill the battery only at the dock.
Check the route → Check and spend → Recharge

Understand the JavaScript in this lesson

Language to look for named constants, negative checks, -= operator, ternary expression, guard clauses.

1. Name the energy limit

The number six is the battery capacity. MAX_ENERGY names it in one place so the starting battery and recharge rule agree. The uppercase spelling is a common way to mark a fixed setting. This is a number, so it has no quotation marks.

const MAX_ENERGY = 6;

2. Check the cheapest mistake first

An impossible route should not cost anything. That is why the route check comes before the charge check. When energy equals zero, send a helpful message and return before moving. The small ? : expression chooses a message depending on whether Pip is already on the dock.

if (state.energy === 0) {

3. Spend exactly one unit

state.energy -= 1 subtracts one from the stored energy. It runs only after both earlier checks pass. Then travel writes the new place, calls render() and gives the arrival message. The view follows the game data every time.

state.energy -= 1;

4. Add a recovery control

The Recharge button has its own click listener. The function checks for a valid location using !==, meaning these two values are different. Only Sky Dock can supply power. On a successful recharge, the function assigns the maximum and renders the new amount. Refuelling at the dock before a long route is good mission planning.

state.energy = MAX_ENERGY;
Follow what happens step by step
  1. Go from Sky Dock to Workshop.
    Energy falls from 6 to 5.Why The map allows the move and the battery is positive.
  2. Try recharging in Workshop, then return and recharge at Sky Dock.
    Workshop keeps the same energy. At Sky Dock energy is 6 again.Why Only the dock meets the location check.

Predict before you run Does choosing Beacon direct from Sky Dock use one energy?

Reveal the answer

No energy is spent. The route check returns before the subtraction.

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>
  <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>
  <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 state = { place: "Sky Dock", energy: MAX_ENERGY };

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

function travel(event) {
  const destination = event.currentTarget.dataset.destination;
  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.");
}

for (const button of moveButtons) {
  button.addEventListener("click", travel);
}
document.querySelector("#charge").addEventListener("click", recharge);
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 state = { place: "Sky Dock", energy: MAX_ENERGY };
Set up state. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Line 12 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 14 function showMessage(message) {
Define showMessage. The body runs when the function is called, with inputs named message.
Line 15 document.querySelector("#report").textContent = message;
Replace the element’s displayed text. The browser treats the value as text.
Line 18 function render() {
Define render. The body runs when the function is called.
Line 19 document.querySelector("#place").textContent = state.place;
Replace the element’s displayed text. The browser treats the value as text.
Line 20 document.querySelector("#energy").textContent = state.energy;
Replace the element’s displayed text. The browser treats the value as text.
Line 23 function travel(event) {
Define travel. The body runs when the function is called, with inputs named event.
Line 24 const destination = event.currentTarget.dataset.destination;
Set up destination. Keep this name attached to the same value.
Line 25 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.
Lines 26–41
Line 26 showMessage("No route from " + state.place + " to " + destination + ".");
Call showMessage with the values inside the parentheses.
Line 27 return;
Leave this function immediately.
Line 29 if (state.energy === 0) {
Run this part when the test is truthy. The triple equals compares without converting the value’s type.
Line 30 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 31 return;
Leave this function immediately.
Line 33 state.energy -= 1;
Update the existing value with the operation shown.
Line 34 state.place = destination;
Store the result in the name or property to the left.
Line 35 render();
Call render with the values inside the parentheses.
Line 36 showMessage("Pip reaches " + destination + ".");
Call showMessage with the values inside the parentheses.
Line 39 function recharge() {
Define recharge. The body runs when the function is called.
Line 40 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 41 showMessage("Recharge is only available at Sky Dock.");
Call showMessage with the values inside the parentheses.
Lines 42–53
Line 42 return;
Leave this function immediately.
Line 44 state.energy = MAX_ENERGY;
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’s battery is full.");
Call showMessage with the values inside the parentheses.
Line 49 for (const button of moveButtons) {
Take one value at a time from this sequence and run the body with it.
Line 50 button.addEventListener("click", travel);
Register a function the browser should call when the named event happens.
Line 52 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 53 render();
Call render with the values inside the parentheses.

Mission challenge

Map out a four-move journey that starts and ends at Sky Dock and predict its battery reading before recharging.

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