Scratch 16 · Make an enemy that can find its way

A robot follows a dotted route around grid walls towards a fox.

Scratch lesson 16 of 20 · Advanced · About 60–75 minutes

Can a maze robot get around a wall instead of walking straight into it? Build a grid chase and use breadth-first search to find a shortest route made of legal steps.

What you’ll make Build a two-character maze in which a robot plans one legal move towards the player every half-second.

Get ready

Open the Scratch editor (opens in a new tab) and start a new project.

  • Start a new Scratch project. Paint three small sprites named Player, Robot and Wall. Aim for player and robot costumes about 22 pixels wide and a solid Wall square about 34 pixels across. Keep each costume centred on its crosshair.
  • Create Grid, Player tile and Running for all sprites. The map has four rows and four columns. Read across the rows from the top left, numbering tiles 1 to 16.
  • On Wall create Wall tile for this sprite only. On Robot create Enemy tile, Goal, Head, Current and Step for this sprite only. Make Frontier and Parent lists for Robot only. Hide their monitors after testing.
  • The map is 0100010001000000. A 0 is open and a 1 is a wall. Walls are at tiles 2, 6 and 10, so the way around is through the bottom row.

To keep your project, choose File → Save to your computer in Scratch.

Check open tiles. Find legal next moves. → Search the maze. Record how each tile was reached. → Follow the path. Test walls and dead ends.
Project flow · Check open tiles → Search the maze → Follow the path

Build it in Scratch

Choose the sprite named above each stack. The colours help you find the block categories. Indented rows sit inside the block above. Follow the end marker to see where each loop or condition closes.

1. Set up the board before the chase

On the Stage, make the messages Reset maze and Chase. Reset sets the map and starting tile. The Stage waits for the finite setup scripts to finish before allowing key presses or starting the chase.

Block stack for Stage
when green flag clicked
set [Running] to (0)
set [Grid] to [0100010001000000]
set [Player tile] to (4)
broadcast [Reset maze] and wait
set [Running] to (1)
broadcast [Chase]

2. Turn a tile number into screen coordinates

Make a My Blocks block place at tile with a number or text input named tile. Add this block to each of the three sprites separately. mod gives the column after subtracting one. floor in the Operators menu gives the row after dividing by four. Tile 1 is at x −60, y 60. Tile 16 is at x 60, y −60.

Block stack for Player, Robot and Wall
define place at tile (tile)
go to x: (((((tile) - (1)) mod (4)) * (40)) - (60)) y: ((60) - (([floor] of (((tile) - (1)) / (4))) * (40)))

3. Draw the walls from the map

On Wall, scan all 16 characters. Each clone inherits a copy of the original sprite’s Wall tile at the instant it is created. The original stays hidden. The green flag clears the old clones when you restart.

Block stack for Wall
when I receive [Reset maze]
hide
set [Wall tile] to (1)
repeat (16)
if <(letter (Wall tile) of (Grid)) = [1]> then
create clone of [myself]
↳ End of block
change [Wall tile] by (1)
↳ End of block
when I start as a clone
place at tile (Wall tile)
show

4. Give the player four legal moves

Make a Player block try tile with a number or text input called target. Its checks reject positions outside the board and walls. Add the four separate key stacks. The left and right tests stop the player wrapping from one row to the next. The vertical moves change the tile number by four.

Block stack for Player
when I receive [Reset maze]
place at tile (Player tile)
show
define try tile (target)
if <<not <(target) < (1)>> and <not <(target) > (16)>>> then
if <(letter (target) of (Grid)) = [0]> then
set [Player tile] to (target)
place at tile (Player tile)
↳ End of block
↳ End of block
when [left arrow] key pressed
if <<(Running) = (1)> and <not <(((Player tile) - (1)) mod (4)) = (0)>>> then
try tile ((Player tile) - (1))
↳ End of block
when [right arrow] key pressed
if <<(Running) = (1)> and <not <(((Player tile) - (1)) mod (4)) = (3)>>> then
try tile ((Player tile) + (1))
↳ End of block
when [up arrow] key pressed
if <(Running) = (1)> then
try tile ((Player tile) - (4))
↳ End of block
when [down arrow] key pressed
if <(Running) = (1)> then
try tile ((Player tile) + (4))
↳ End of block

5. Record a new square and where it came from

On Robot, make offer (previous) (candidate). Both inputs are numbers or text. This block lets only open, unvisited tiles into Frontier, the queue of tiles to check. A value of zero in Parent means unvisited. Recording the previous tile both marks the candidate visited and gives you a pointer back along the route.

Block stack for Robot
define offer (previous) (candidate)
if <<not <(candidate) < (1)>> and <not <(candidate) > (16)>>> then
if <<(letter (candidate) of (Grid)) = [0]> and <(item (candidate) of [Parent]) = (0)>> then
replace item (candidate) of [Parent] with (previous)
add (candidate) to [Frontier]
↳ End of block
↳ End of block

6. Search outwards, then follow the route backwards

Make a Robot block plan one step and tick Run without screen refresh in its creation dialogue. In the search, read Frontier from the front using Head and add new tiles at the end. This checks every tile one move away before checking tiles two moves away. When you reach Goal, follow Parent backwards until you reach the first move from the robot. Offer neighbours in the order shown so a tie produces the same choice each time.

Block stack for Robot
define plan one step
delete all of [Frontier]
delete all of [Parent]
repeat (16)
add (0) to [Parent]
↳ End of block
set [Goal] to (Player tile)
set [Step] to (Enemy tile)
if <not <(Goal) = (Enemy tile)>> then
add (Enemy tile) to [Frontier]
replace item (Enemy tile) of [Parent] with (Enemy tile)
set [Head] to (1)
repeat until <<(Head) > (length of [Frontier])> or <not <(item (Goal) of [Parent]) = (0)>>>
set [Current] to (item (Head) of [Frontier])
if <not <(((Current) - (1)) mod (4)) = (3)>> then
offer (Current) ((Current) + (1))
↳ End of block
offer (Current) ((Current) + (4))
if <not <(((Current) - (1)) mod (4)) = (0)>> then
offer (Current) ((Current) - (1))
↳ End of block
offer (Current) ((Current) - (4))
change [Head] by (1)
↳ End of block
if <not <(item (Goal) of [Parent]) = (0)>> then
set [Step] to (Goal)
repeat until <(item (Step) of [Parent]) = (Enemy tile)>
set [Step] to (item (Step) of [Parent])
↳ End of block
↳ End of block
↳ End of block

7. Chase one square at a time

The robot replans after every wait, using the player’s latest square. If the two sprites land on the same tile, disable the player’s keys and show the ending. Start a fresh maze with the green flag.

Block stack for Robot
when I receive [Reset maze]
set [Enemy tile] to (1)
place at tile (Enemy tile)
say []
show
when I receive [Chase]
repeat until <(Enemy tile) = (Player tile)>
wait (0.5) seconds
plan one step
set [Enemy tile] to (Step)
place at tile (Enemy tile)
↳ End of block
set [Running] to (0)
say [Caught! Click the green flag to try again.]

Test your project

  1. Select Robot and turn on its Enemy tile monitor. Leave the player in tile 4. The robot should take this route: 1, 5, 9, 13, 14, 15, 16, 12, 8, 4. Check that it moves one square per turn and avoids the three wall tiles.
  2. Restart. Move the player down and then left. The robot should choose a new route, and a left move from tile 1 or 5 should never wrap across a row.
  3. Try Grid 0100010001000100 with the same starting squares. The full wall divides the board. The robot should stay in place and keep trying, without freezing.

If something goes wrong

The robot tries to walk straight through walls.
Check that offer reads the character at candidate, and accepts it only if it is 0. In Scratch the first list item and first letter both use index 1.
The project hangs while planning.
Set Parent before appending the tile and increase Head once per processed tile. Each tile should enter Frontier at most once.
The wall sprites all pile up.
Use a variable for this sprite only for Wall tile. Each clone needs its own copy.

Make it your own

  • Try a 0.8 second wait for an easier maze, then 0.3 seconds for a harder one. Change only that delay and compare the feel.
  • Create another 16-character map with a route from tile 1 to tile 4. Time the robot in both mazes and check which route needs more steps.

What you’ve learned Breadth-first search uses a queue and a visited record to find a route with the fewest moves on a grid where every move costs one step.