AI Course > Grades 8–9 > Lesson 1
GRADES 8–9 · LESSON 1

First Moving Sprite: Arrow Keys and Walls

Make a square that obeys your arrow keys and never slips off the screen.

By the end of this lesson you will have — one sprite that moves with the arrow keys and stops at all four walls, built in the p5.js Web Editor

What you'll show at the end: A screenshot of your sketch running, with your sprite pressed against a wall and your 3-line spec written next to it.

p5.js Web Editor

Check each tool's age rule before you sign up. If you are under 13, ask a parent first — some tools here are 13+ only.

Follow these steps

  1. Open the p5.js Web Editor. You can write and run code without an account. Delete the example code in the editor first, then paste the starter code from this page and press Play: you should see a square that does not move.
  2. Before you code, write your spec in 3 lines: how many pixels the sprite moves each frame, which keys move it, and exactly where it must stop.
  3. Inside draw(), use keyIsDown(LEFT_ARROW), RIGHT_ARROW, UP_ARROW, and DOWN_ARROW to change x and y. Then use constrain() so x and y cannot pass the edges. Press Play and drive into all four walls.
  4. Stuck or curious? Copy the question from the box next to these steps into the AI you're allowed to use (under 13: a parent's account, with your parent). Without an account, keep your work by copying your code into a file on your device. Then take a screenshot.
Starting fresh?
No sprite yet? Paste this into the editor and press Play. You will see a square that does not move yet.

let x = 185;
let y = 185;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  // Your movement code goes here
  square(x, y, 30);
}
Source (adapted for this grade: wording changed, facts unchanged)
anthropic.com/learn — AI Fluency: Framework and Foundations, Description and Discernment (adapted for Grades 8–9)

Say it, predict it, check it