Comet opens rover.py and cracks her knuckles. "Today Pip gets move() and run() for real," she says.
Wren taps the folder. "What does the evidence say we should do first?" he asks. "Save a snapshot. If the new code goes wrong, we still have the version that worked."
Nova projects the file with the new parts glowing. "How can I help?" she asks. "Add one piece, then run a short drive. Predict every time."
"Lead programmer," Comet says, "you type. I will read out the route."
Pip gets one more instance variable, _log, an empty list. A constructor gives every instance variable a starting value, so it goes in __init__.
get_log() is an accessor: it hands back a copy of the log, like get_samples().
# rover.py
# A Rover drives on a FieldGrid, one cell at a time.
HEADINGS = ["N", "E", "S", "W"]
STEPS = {"N": (-1, 0), "E": (0, 1), "S": (1, 0), "W": (0, -1)} def __init__(self, name, row=0, col=0):
self.name = name
self._row = row
self._col = col
self._heading = "E"
self._battery = 100
self._capacity = 3
self._samples = []
self._log = []
Rover.rovers_built += 1 def get_log(self):
return list(self._log)
def step_use(self):
"""Battery used by one step forward."""
return 5 Then add move() exactly as you traced it on Monday. Run 1:
# first_drive.py
from field_data import FIELD
from grid import FieldGrid
from rover import Rover
grid = FieldGrid(FIELD)
pip = Rover("Pip")
pip.move(grid)
pip.move(grid)
pip.turn_right()
pip.move(grid)
print(pip.status())
print(pip.get_log()) Pip at (1, 2) facing S, battery 85 ['moved to (0, 1)', 'moved to (0, 2)', 'moved to (1, 2)']
Now add run() as you read it on Tuesday. Run 2:
# long_drive.py
from field_data import FIELD
from grid import FieldGrid
from rover import Rover
grid = FieldGrid(FIELD)
pip = Rover("Pip")
pip.run("FFRFFFLFF", grid)
grid.show(pip)
print(pip.status())
print(len(pip.get_log()), "log lines") ..*..# .#.... ...#*. *...R. ..#..* Pip at (3, 4) facing E, battery 65 7 log lines
Change it once. In rover.py, change step_use() to return 10. Save and run long_drive.py again.
..*..# .#.... ...#*. *...R. ..#..* Pip at (3, 4) facing E, battery 30 7 log lines
Break it once. Set step_use() back to 5. Then, in move(), change STEPS to STEP. Save and run long_drive.py.
Traceback (most recent call last):
File "long_drive.py", line 8, in <module>
pip.run("FFRFFFLFF", grid)
~~~~~~~^^^^^^^^^^^^^^^^^^^
File "rover.py", line 92, in run
self.move(grid)
~~~~~~~~~^^^^^^
File "rover.py", line 73, in move
d_row, d_col = STEP[self._heading]
^^^^
NameError: name 'STEP' is not defined. Did you mean: 'STEPS'? Pip drives for real. Tomorrow you will see what goes wrong when a check is missing.