Skip to main content

Lesson 4-4 · The Driver

Module 4 · Manhattan Navigation

Lesson 4-4 · The Driver

55–65 minPython codeHeadings as numbersRobot stays on the deskSlides (PowerPoint)
👩‍🏫

Teacher mode is on. Toggle it off (bottom-right) to preview the student view.

The planner is real. Now the driver stub goes. At each intersection on the path, the robot does two things: turn to face the next intersection, then drive to it. Today you write the loop that does that and the function that works out which way to face. Turning and driving stay stubs for now, so every move shows up as printed lines.

Learning Objectives

By the end of this lesson you will be able to:

  • Break driving a path into two steps at each intersection: turn, then drive
  • Read one item of a list or one part of a tuple by its index, counting from 0
  • Write get_desired_heading(position, next_pos), which turns a one-step move into a heading (0 = N, 1 = E, 2 = S, 3 = W)
  • Write the real drive_path() loop, with stubs for turning and driving
  • (Optional) Catch a mistake early by raising an error when a function is asked something it can't answer

Heading is a number​

Since Lesson 4-1 the program has carried a robot_heading that never changed. Now it gets used. The four directions are numbered clockwise from North:

Heading0123
DirectionNorthEastSouthWest

Numbers are easy to do arithmetic on (a clockwise quarter turn adds 1), but 0 in a printout is hard to read. So the program needs a way to turn 0 into N and 2 into S.

Picking one item: indexing​

Put the four letters in a list, in heading order:

HEADING_NAMES = ["N", "E", "S", "W"]

Every item in a list has a position number, its index, counting from 0. Square brackets after the name pick one item out:

print(HEADING_NAMES[0]) # N
print(HEADING_NAMES[2]) # S
heading = 3
print(HEADING_NAMES[heading]) # W

The headings were numbered 0 to 3 so that a heading is the index of its own letter.

A tuple is indexed the same way. For a position, index 0 is x and index 1 is y:

next_pos = (2, 3)
print(next_pos[0]) # 2 -> x
print(next_pos[1]) # 3 -> y

For a position you'll usually want both numbers, so this program keeps unpacking them, as the planner does. Indexing is for picking one item out of many. Asking for an index that isn't there, like HEADING_NAMES[4], stops the program with an IndexError.

Knowledge Check

What does this print?

path = [(1, 0), (2, 0), (2, 1)]
last = path[2]
print(last[1])

Which way to face?​

Between two adjacent intersections, either x changes by one or y changes by one, never both. That's four cases, one per compass direction:

Coordinate changeDirectionHeading
y +1 (up, away from you)North0
x +1 (right)East1
y −1 (down, toward you)South2
x −1 (left)West3

The part to keep straight: x comes first in the tuple, but North and South change the second number. North is away from you, so moving North makes y bigger.

The robot at an intersection facing north, with a card at each neighbor. North is heading 0, y goes up by 1. East is 1, x goes up by 1. South is 2, y goes down by 1. West is 3, x goes down by 1. Curved arrows between them, each marked +1, show that every clockwise turn adds 1, wrapping from 3 back to 0.
The four neighbors of an intersection, the coordinate change that reaches each one, and its heading. Clockwise adds 1.
Knowledge Check

The robot moves from (2, 3) to (3, 3). Which direction is that, and what heading?

get_desired_heading(position, next_pos) works out that table. It unpacks both positions, as the planner did, then finds the one number that changed. Four if lines, one per row: if next_y is bigger than y, the move is North; if next_x is bigger than x, it's East; and the same with "smaller" for South and West.

This lesson's skeleton​

Put these above the drive_path() function: the list of letters, the function you write, a quick test for it, and two new stubs.

HEADING_NAMES = ["N", "E", "S", "W"] # HEADING_NAMES[2] -> "S"

def get_desired_heading(position, next_pos):
"""Return the heading (0-3) that points from position to
next_pos, which must be one step away."""
# 1. unpack position into x, y and next_pos into
# next_x, next_y
# 2. one if per row of the table, each returning its
# heading. North is: if next_y > y: return 0
# 3. (optional) none matched: raise ValueError, naming
# both positions -- see "Catching mistakes early"
pass

def test_headings():
for next_pos in [(0, 1), (1, 2), (2, 1), (1, 0)]:
heading = get_desired_heading((1, 1), next_pos)
print("(1, 1) to", next_pos, ":", heading, HEADING_NAMES[heading])

def turn_to(current_heading, desired_heading):
"""STUB: pretend the robot turned. Lesson 4-5
replaces it."""
print("turning: from", HEADING_NAMES[current_heading],
"to:", HEADING_NAMES[desired_heading])
return desired_heading

def fake_track_to_intersection():
"""STUB for track_to_intersection(): print instead of
driving. Lesson 4-6 swaps in the real one."""
print("tracking to intersection")

Then fill in the drive_path() stub you already have. Its loop gets four new steps, and the docstring changes:

def drive_path(path, current_position, current_heading):
"""Turn and drive through every intersection in path;
return the final position and heading."""
for next_pos in path:
# 1. desired_heading: which way to face next_pos
# 2. print("moving: from", current_position, "to:", next_pos,
# "heading:", HEADING_NAMES[desired_heading])
# 3. turn: current_heading = turn_to(...)
# 4. drive there: fake_track_to_intersection()
current_position = next_pos # the robot is there now
return current_position, current_heading

turn_to() hands back the new heading, so step 3 keeps current_heading up to date the same way the main program keeps robot_position up to date.

One more line changes. In test_delivery(), make the new position: print show the letter:

print("new position:", robot_position,
"heading:", HEADING_NAMES[robot_heading])

Activity · Write it, test it, run it​

Step 1 · get_desired_heading()​

Write its body from the outline. Work out the four answers for test_headings() from the table first: from (1, 1) to (0, 1), (1, 2), (2, 1) and (1, 0). Set the run line to test_headings() and run it.

What correct looks like: four lines whose heading numbers and letters match your four answers.

Step 2 · The drive_path() loop​

Fill in steps 1 to 4 of the loop. Set the run line to test_delivery() and run it.

What correct looks like: under each path, one moving: line per intersection in it, each followed by a turning: line and tracking to intersection. Each move starts where the last one ended, and its letter matches the table: Leg 1 is E, E, N, N, N. Each turning: starts from the heading the one before it ended on. The last line says new position: (0, 0) heading: S: the last move of the run goes South.

Knowledge Check

Going from (1, 3) to (1, 2), what does get_desired_heading() return?

Optional: open it if you have time. Nothing later depends on it.

Wrap-up​

  • What two steps happen at each intersection? (Turn to face the next one, then drive to it.)
  • Between adjacent intersections, what can change? (x or y, by one: four cases, four headings.)
  • What does HEADING_NAMES[heading] do? (Picks the item at that index, counting from 0: the heading's letter.)
  • Why does drive_path() write current_heading = turn_to(...)? (turn_to() hands back the new heading; assigning it is the only way drive_path() keeps it.)

Resources​