Functions and structured code · GCSE · OCR J277 2.1.1, AQA 8525 3.1.1, Edexcel 1CP2 1.1.1 · about 20 min
Structure diagrams, and hiding the details of a job behind a function.
[1 mark]What is decomposition?
[1 mark]What is abstraction?
[1 mark]A simulator's mat keeps the walls and distances but not the carpet colour. Which idea is that?
[1 mark]What does a structure diagram show?
[1 mark]Why keep a delivery route as a list of stops, separate from the code that drives?
Write go_to(x, y) and signal(), then use them to visit three stops in order, signalling at each: A at (30, 10), B at (30, 60) and C at (0, 60), all in cm from where the robot starts. The robot starts in the bottom left of the mat.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
def go_to(x, y):
"""Drive to (x, y), in cm from where the robot started."""
here_x, here_y = position()
def signal():
"""Light and beep at a stop."""
led("green")The hint students can ask for: Work out where you are, then how far you still have to go in each direction, and drive that difference. Sideways and forwards are separate moves. Do the signal at each stop.
from bugbot import *
connect()
def go_to(x, y):
"""Drive to (x, y), in cm from where the robot started."""
here_x, here_y = position()
across = x - here_x
up = y - here_y
if across > 0:
right(60, distance=across)
elif across < 0:
left(60, distance=-across)
if up > 0:
forward(60, distance=up)
elif up < 0:
backward(60, distance=-up)
def signal():
"""Light and beep at a stop."""
led("green")
tone(784, 0.3)
led("off")
for x, y in [(30, 10), (30, 60), (0, 60)]:
go_to(x, y)
signal()
Any program that meets the task's checks is marked correct in the simulator; this is one way, not the only way.