JavaScript 32 · Fly Pip with arrow keys and buttons

JavaScript lesson 32 of 50 · Advanced · About 5 minutes

Connect real player input to the coordinate map and keep Pip inside its edges.

Three cloud creatures follow Pip across lighted floating platforms toward the wind beacon in a rainstorm.
Mission Connect real player input to the coordinate map and keep Pip inside its edges.

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.

Input. An arrow key or button chooses a direction. → Proposed square. Add the step to the current point. → Boundary. Draw the move if the square is inside.
Input → Proposed square → Boundary

Understand the JavaScript in this lesson

Language to look for Map, keyboard events, button events, bounds checking.

1. Translate the controls

A Map stores key and value pairs. Each input name maps to a step object. ArrowLeft maps to x = −1, y = 0 because Pip moves one column left and stays on the same row. The get method retrieves the step for the pressed key.

const step = directions.get(key);

2. Listen for keys on the board

Tab to the board and use the arrow keys. The listener checks event.target so an arrow pressed while another control has focus keeps its usual behavior. The return exits early for other keys. preventDefault stops the page scrolling when an arrow is used to steer from the board.

event.preventDefault();

3. Send button clicks to the same move function

Each control button has a data-move value in the HTML. JavaScript reads it as dataset.move. The arrow function runs after the click and supplies that value to move. Using the same names for keyboard and buttons keeps both controls following the same rules.

button.addEventListener("click", () => move(button.dataset.move));

4. Work out the next square before moving

Add the step to Pip's coordinates to make a next object. The && operator means each boundary test must pass. If the position passes inside, save it as state and draw the board again. When a test fails, the old state remains and the symbol stays in place.

if (inside(next)) {
Follow what happens step by step
  1. Press Up from the Hub
    Pip stays at column 1, row 1.Why The proposed y is −1.
  2. Click Right twice
    Pip reaches column 3, row 1.Why Each click adds one to x.

Predict before you run How does the Down button change the coordinate pair (1, 1)?

Reveal the answer

It becomes (1, 2). Down adds one to y.

Complete checkpoint

HTML · the page and controls

<main id="sky" tabindex="0" aria-label="Sky Island Rescue board">
  <h2>Sky Island Rescue</h2>
  <p id="legend">P = Pip, H = Hub, W = Workshop, G = Garden, B = Beacon, # = rock, . = open sky.</p>
  <pre id="board" aria-hidden="true"></pre>
  <p id="status" role="status"></p>
  <div aria-label="Move Pip">
    <button type="button" data-move="ArrowUp">Up</button>
    <button type="button" data-move="ArrowLeft">Left</button>
    <button type="button" data-move="ArrowDown">Down</button>
    <button type="button" data-move="ArrowRight">Right</button>
  </div>
  <p>Use the move buttons or focus the board and press an arrow key.</p>
</main>

JavaScript · the instructions

const stage = document.querySelector("#sky");
const board = document.querySelector("#board");
const status = document.querySelector("#status");
const columns = 5;
const rows = 4;
const landmarks = {
  "0,0": "H", "4,0": "W", "0,3": "G", "4,3": "B"
};
const directions = new Map([
  ["ArrowUp", { x: 0, y: -1 }],
  ["ArrowDown", { x: 0, y: 1 }],
  ["ArrowLeft", { x: -1, y: 0 }],
  ["ArrowRight", { x: 1, y: 0 }]
]);
let state = { x: 0, y: 0 };
function render() {
  const lines = [];
  for (let y = 0; y < rows; y += 1) {
    const line = [];
    for (let x = 0; x < columns; x += 1) {
      const label = `${x},${y}`;
      const hasPip = x === state.x && y === state.y;
      line.push(hasPip ? "P" : (landmarks[label] ?? "."));
    }
    lines.push(line.join(" "));
  }
  board.textContent = lines.join("\n");
  const position = `Pip is at column ${state.x + 1}, row ${state.y + 1}.`;
  status.textContent = position;
}
function inside({ x, y }) {
  return x >= 0 && y >= 0 && x < columns && y < rows;
}
function move(key) {
  const step = directions.get(key);
  if (!step) return;
  const next = { x: state.x + step.x, y: state.y + step.y };
  if (inside(next)) {
    state = next;
    render();
  }
}
stage.addEventListener("keydown", (event) => {
  if (event.target !== stage || !directions.has(event.key)) return;
  event.preventDefault();
  move(event.key);
});
for (const button of stage.querySelectorAll("[data-move]")) {
  button.addEventListener("click", () => move(button.dataset.move));
}
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–19
Line 1 const stage = document.querySelector("#sky");
Set up stage. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 2 const board = document.querySelector("#board");
Set up board. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 3 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 4 const columns = 5;
Set up columns. Keep this name attached to the same value.
Line 5 const rows = 4;
Set up rows. Keep this name attached to the same value.
Lines 6–8 const landmarks = { "0,0": "H", "4,0": "W", "0,3": "G", "4,3": "B" };
Set up landmarks. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Lines 9–14 const directions = new Map([ ["ArrowUp", { x: 0, y: -1 }], ["ArrowDown", { x: 0, y: 1 }], ["ArrowLeft", { x: -1, y: 0 }], ["ArrowRight", { x: 1, y: 0 }] ]);
Set up directions. Keep this name attached to the same value. Use new to create a fresh Map object.
Line 15 let state = { x: 0, y: 0 };
Set up state. Give this name a starting value that later code can change. Braces create an object. Properties give names to the stored values.
Line 16 function render() {
Define render. The body runs when the function is called.
Line 17 const lines = [];
Set up lines. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
Line 18 for (let y = 0; y < rows; y += 1) {
Set up the counter, check the condition and run the body. Update the counter after each pass.
Line 19 const line = [];
Set up line. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
Lines 20–35
Line 20 for (let x = 0; x < columns; x += 1) {
Set up the counter, check the condition and run the body. Update the counter after each pass.
Line 21 const label = `${x},${y}`;
Set up label. Keep this name attached to the same value. The backticks keep the text together. JavaScript fills each ${…} gap with a value.
Line 22 const hasPip = x === state.x && y === state.y;
Set up hasPip. Keep this name attached to the same value. JavaScript evaluates the right side only when the left side is truthy. The triple equals compares without converting the value’s type.
Line 23 line.push(hasPip ? "P" : (landmarks[label] ?? "."));
Add entries to the end of the array and return its new length.
Line 25 lines.push(line.join(" "));
Add entries to the end of the array and return its new length.
Line 27 board.textContent = lines.join("\n");
Combine array entries into a string, with the chosen separator between entries. Replace the element’s displayed text. The browser treats the value as text.
Line 28 const position = `Pip is at column ${state.x + 1}, row ${state.y + 1}.`;
Set up position. Keep this name attached to the same value. The backticks keep the text together. JavaScript fills each ${…} gap with a value.
Line 29 status.textContent = position;
Replace the element’s displayed text. The browser treats the value as text.
Line 31 function inside({ x, y }) {
Define inside. The body runs when the function is called, with inputs named { x, y }.
Line 32 return x >= 0 && y >= 0 && x < columns && y < rows;
Leave this function and send the value back to the caller. JavaScript evaluates the right side only when the left side is truthy. Check whether the first is greater than or equal to the second.
Line 34 function move(key) {
Define move. The body runs when the function is called, with inputs named key.
Line 35 const step = directions.get(key);
Set up step. Keep this name attached to the same value. Read the matching value from the collection.
Lines 36–48
Line 36 if (!step)
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
Line 36 return;
Leave this function immediately.
Line 37 const next = { x: state.x + step.x, y: state.y + step.y };
Set up next. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values. Plus adds numbers or joins text, depending on its values.
Line 38 if (inside(next)) {
Run this part when the test is truthy. Call inside with the values inside the parentheses.
Line 39 state = next;
Store the result in the name or property to the left.
Line 40 render();
Call render with the values inside the parentheses.
Line 43 stage.addEventListener("keydown", (event) => {
This function body is passed as an input. Register a function the browser should call when the named event happens.
Line 44 if (event.target !== stage || !directions.has(event.key))
Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy. The exclamation and two equals signs check whether values differ without type conversion.
Line 44 return;
Leave this function immediately.
Line 45 event.preventDefault();
Stop the browser’s usual response to this event where permitted.
Line 46 move(event.key);
Call move with the values inside the parentheses.
Line 48 for (const button of stage.querySelectorAll("[data-move]")) {
Take one value at a time from this sequence and run the body with it.
Lines 49–51
Line 49 button.addEventListener("click", () => move(button.dataset.move));
Register a function the browser should call when the named event happens.
Line 51 render();
Call render with the values inside the parentheses.

Mission challenge

Try arriving at the bottom edge with the keyboard and the right edge with buttons. Predict the last valid x and y before playing.

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