Run a Robot Program
Advanced · Write the code · from Grid Robot Algorithms: MOVE_FORWARD, ROTATE and CAN_MOVE
From the lesson: Grid Robot Algorithms: MOVE_FORWARD, ROTATE and CAN_MOVE
Many exam questions show a robot on a grid and ask which code segment gets it to a goal square, using four commands from the reference sheet: MOVE_FORWARD(), ROTATE_LEFT(), ROTATE_RIGHT() and CAN_MOVE(direction). The small Python robot on this page runs any path you write, so you can check a trace instead of guessing.
Read the lessonWrite run_program(grid, row, col, facing, commands). commands is a list of "F" (MOVE_FORWARD), "L" (ROTATE_LEFT) and "R" (ROTATE_RIGHT). Run them in order and return a tuple (row, col, facing) with where the robot ends.
Follow the reference sheet's rule: if an "F" would move into a "#" square or off the grid, the robot stays where it is and the program terminates. Return its position at that moment and ignore the remaining commands.
grid = ["....", ".#..", "...."]
run_program(grid, 2, 0, "right", ["F", "F", "L", "F", "F"]) -> (0, 2, 'up')
run_program(grid, 2, 0, "up", ["F", "R", "F"]) -> (1, 0, 'right')What Check runs
Your code runs first, then each of these lines, and 2 more that stay hidden. The output must match exactly.
| Runs | Expected output |
|---|---|
| run_program(["....", ".#..", "...."], 2, 0, "right", ["F", "F", "L", "F", "F"]) | (0, 2, 'up') |
| run_program(["....", ".#..", "...."], 2, 0, "up", ["F", "R", "F"]) | (1, 0, 'right') |
More Grid Robot exercises
- Which Way Now?Beginner
- Is That Square Open?Intermediate