Robot Commands
Learning Objectives
- You can trace a grid robot’s position and heading through method calls.
- You can use loops and helper functions to repeat and combine movements.
- You can read the current state to decide when a loop should stop.
- You can explain where a program stops when an action is blocked.
In Part 6, methods changed the state of game objects. Our first robot also has state: its grid position and the direction it faces. Calling one of its movement methods changes that state. The supplied simulator handles the board and drawing; your functions choose the commands.
The Grid and Starting State
The board below has five columns and four rows. Columns increase to the right; rows increase upward. R marks the robot, initially facing east, G marks the goal, and # marks a wall. A dot is an empty cell.
columns 1 2 3 4 5row 4 . . . . .row 3 . . . G .row 2 . . # . .row 1 R . . . .The robot starts at column 1, row 1. It can occupy empty cells and the goal cell. A movement into a wall or outside the board is rejected.
Commands and Relative Movement
The commands refer to the robot’s direction, not the top or bottom of the screen:
| Command | Change |
|---|---|
forward() | Move one cell in the current heading. |
backward() | Move one cell opposite the current heading; keep that heading. |
turn_left() | Rotate 90 degrees left; keep the current cell. |
turn_right() | Rotate 90 degrees right; keep the current cell. |
Call these methods on the supplied object, for example robot.forward(). Each action finishes before the next call begins. robot.state() returns a fresh dictionary containing column, row, heading, and holding. Reading it does not move the robot. holding is False because no block is attached; the next chapter introduces attachment.
The diagram below follows the turns from an east-facing robot. Each edge is one turn in place, with no change in its grid coordinates.
Turning changes heading while preserving the robot’s cell.
Running and Reading the Preview
The simulator creates the robot and calls program(robot), supplying that object. Put your commands inside this function. You do not construct a robot or call program yourself.
Run main.py below. The supplied program moves three cells east, turns left, and moves two cells north to the goal. Before stepping through it, predict the position immediately after the turn.
Select main.py and Run. Click the preview if prompted. Right arrow advances one action, Space plays or pauses, and R rewinds to the starting state. Read the position, heading, and action below the board.
The program runs once before playback. These controls replay its recorded actions. After editing program, Run main.py again to calculate a new sequence from a fresh board. Rewinding does not execute your code again.
Keep the supplied board and support files unchanged. robot_api.py supplies the model, runner.py records execution, boards.py contains exercise boards, and pyxel_graphics.py draws the preview. The browser already supplies Pyxel; no package installation is needed here.
After the first three movements, the robot is at column 4, row 1. The turn keeps that cell and changes the heading to north. The final movements reach row 3. Replacing that turn with turn_right() would make the next movement leave the board below row 1.
Inspecting an Action with print
Replace only program in the editor with this short inspection, leaving the supplied launch code below it:
def program(robot): print("Before:", robot.state()["column"], robot.state()["row"]) robot.forward() print("After:", robot.state()["column"], robot.state()["row"])Run again. The printed output is Before: 1 1 followed by After: 2 1. The first reading describes the starting cell; the second describes the state after the method call. The robot has not reached the goal, but this small program helps you check one action. Printed output comes from execution and does not change as you replay the recording. Keep debugging prints short so they fit beside the preview.
A dictionary returned by state() describes that moment. It does not update itself when a later action changes the robot. Call state() again when you need a new reading.
Trace position and heading together in the next question.
Heading and Backward Movement
0 / 5 points
An open board has six columns and four rows. A cell is written as (column, row). Columns increase to the right and rows increase upward. The robot starts at (4, 2), facing north, with no block attached.
The supplied runner calls:
def program(robot): robot.backward() robot.turn_left() robot.forward()What are the robot’s final cell and heading?
Repeating Forward Steps
A counted loop replaces repeated movement calls. A helper gives that operation a name:
def forward_steps(robot, count): for step in range(count): robot.forward()
def program(robot): forward_steps(robot, 3) robot.turn_left() forward_steps(robot, 2) print(robot.state())Replace program with these two functions in the editor and run them. They reach the same goal as the original commands. The caller passes the same robot to both helper calls. The helper changes that object; it does not create a robot or return a new position. With count equal to zero, the loop makes no movement calls.
Practise the command, loop, and dictionary-lookup notation before planning another route. Each step supplies a small working practice.py with its own robot. Make the stated change, Run to inspect its printed state, and Submit to check the result.
Planning and Checking a Route
Before planning your own route, inspect a blocked movement. In the chapter’s editor, replace only program with this version and run main.py again:
def program(robot): robot.forward() robot.forward() robot.turn_left() robot.forward()The robot reaches column 3, row 1 and faces north. Its next destination is the wall at column 3, row 2. The last call raises ValueError and stops the program. The rejected action leaves the robot at column 3, row 1; the earlier movements are not undone.
Step through the completed actions. Read the failed action and its destination before changing the code. R rewinds the recorded run, while editing and running again executes a new program from the starting board. Reset differs from backward(), which moves the current robot.
The next exercise has its own board and starting heading. Trace from that starting state rather than copying the route above. You may use individual calls or loops.
Reach the Goal
0 / 20 points
Write program(robot) to move the robot to column 2, row 4. It starts at column 6, row 1, facing north. Choose any route that avoids walls and stays inside the board; the final heading does not matter.
1 2 3 4 5 6row 5 . . . . . .row 4 . G . . . .row 3 . . # . . .row 2 . . . . # .row 1 . . . . . RUse the robot’s movement methods and keep the supplied preview code unchanged.
Now write a reusable backward-movement helper. Its preview uses three steps, while Submit also checks other counts and headings. The parameter determines the repetition count; the robot’s heading determines the direction of each movement.
Backward Steps
0 / 15 points
Write backward_steps(robot, count). Call robot.backward() exactly count times, without turning or making other robot actions. Do not return a value.
count is a nonnegative integer, and there is enough room for the requested movements. The robot may start facing any direction. Keep the supplied preview code unchanged.
Combining Side Lengths
A longer route can combine shorter operations. For example, forward_steps(robot, 2) and forward_steps(robot, 5) use the same helper with different arguments. A turn between calls changes the direction of the later segment.
For a rectangle, opposite sides have equal lengths. A complete circuit needs all four sides and a turn at each corner, including the final corner. Returning to the starting cell alone does not show that the robot followed the intended route: a program that did nothing would also stay there. Step through the sides and check the heading as well.
Use two length parameters to describe a rectangle without assuming a particular starting heading.
A Rectangle Route
0 / 20 points
Write rectangle_route(robot, width, height). Move forward along four sides, turning left at each corner. The first and third sides have width steps; the second and fourth have height steps. Include the final turn to restore the starting heading. Do not return a value.
Both lengths are positive integers. The robot starts detached, with enough clear space for the route. Use only forward movements and the four left turns. Keep the supplied preview code unchanged; you may add helpers.
Stopping When the State Matches
A counted loop knows how many times to repeat. A while loop can instead check the robot’s current state. On the chapter’s original board, this version stops on column 4 of the bottom row:
def program(robot): while robot.state()["column"] < 4: robot.forward() print(robot.state())The robot starts facing east, with a clear row ahead. Each movement increases its column, and the next condition reads a fresh state. The loop stops when the column reaches 4. This example relies on that heading and clear route; reading a coordinate does not tell you whether a cell contains a wall.
If you read state = robot.state() once before the loop and keep checking that old dictionary, its column stays unchanged. The loop needs a new reading after the robot acts. The same idea applies to a heading: a turn changes the current heading, so check it again before deciding whether another turn is needed.
Use the requested heading to control the next function. It should make no turns if the robot already faces that direction.
Turning to a Heading
0 / 20 points
Write turn_to(robot, heading). Turn in place until the robot faces heading, using turn_left() or turn_right(). If it already faces that direction, make no action calls. Do not return a value.
heading is "east", "north", "west", or "south", and the robot starts detached. Read its current heading with robot.state()["heading"]. Keep the supplied preview code unchanged.
Tracing an Interrupted Program
Trace a different program to identify the first blocked action and the state left when execution stops.
A Blocked Movement
0 / 5 points
A board has six columns and four rows. Coordinates are (column, row), with rows increasing upward. There is one wall at (4, 1) and no blocks. The robot starts at (2, 1), facing east.
The supplied runner calls:
def program(robot): robot.forward() robot.forward() robot.turn_left() robot.backward()Which statement describes where execution stops and the resulting robot state?
Check Your Understanding
- Why does a turn change a later
forward()movement even though it preserves the current cell? - How do the
widthandheightarguments describe the rectangle when the robot starts facing north instead of east? - Why can repeatedly checking one saved
state()dictionary fail to stop a turning loop? - When a movement is rejected, which earlier changes remain, and what does rewinding the preview restore?