To draw traffic lights you need to design a solution before you try to solve the problem. You then need to write the code directly into functions rather than trying to code it as direct commands. This requires a reasonable fluency with the Logo primitives we have covered so far. It also raises the possibility of writing your code in a simple editor such as Notepad and then transferring it to the Logo environment.
A broad view of the traffic lights problem might be:
(This is far enough for now, completing the sequence through amber and red is left as an exercise)
We can now expand each of these steps into Logo functions. First we need the rectangle in black:
Converting this to Logo we have:
to rectangle
pu bk 95 lt 90 fd 100 rt 90 pd
fd 190 rt 90
fd 100 rt 90
fd 190 rt 90
fd 100 rt 90
end
Remember that if you copy code from here into Logo you will have to press Enter after each END to tell Logo about the function.
We now need 3 functions to provide the drawing position for each of the three lights. In outline these are:
In Logo:
to redposition
pu fd 150 rt 90 fd 20 lt 90 pd
end
to amberposition
pu bk 60 pd
end
to greenposition
pu bk 60 pd
end
(Press Enter after each END after copying it into Logo.)
The redposition function moves the turtle from the lower corner of the rectangle to somewhere near the top of the rectangle and then in a little bit before drawing a circle and filling it. The other functions move the turtle from the red light to the amber and from the amber to the green.
The drawing functions are:
In Logo:
to redlighton
setpc 10
repeat 60 [fd 3 rt 6]
rt 90 fd 20 fill bk 20 lt 90 wait 100
end
to amberlighton
setpc 52
repeat 60 [fd 3 rt 6]
rt 90 fd 20 fill bk 20 lt 90 wait 100
end
to greenlighton
setpc 32
repeat 60 [fd 3 rt 6]
rt 90 fd 20 fill bk 20 lt 90 wait 100
end
(Press Enter after each END after copying it into Logo.)
Notice that we have slipped in the WAIT command. This causes the code to wait for the period specified in hundredths of a second.
Before we turn the green light on we should turn off red and amber. This means returning to the red position and drawing a new circle (a white circle would be preferable but we cannot do this against a white background otherwise the fill command runs across the whole screen). We then return to the amber position and draw over the amber light with another colour. We can then turn on the green light.
In Logo:
to redamberoff
setpc 1
pu fd 60 pd
repeat 60 [fd 3 rt 6]
rt 90 fd 20 fill bk 20 lt 90
pu bk 60 pd
repeat 60 [fd 3 rt 6]
rt 90 fd 20 fill bk 20 lt 90
end
(Press Enter after END after copying it into Logo.)
Finally we need a function to hold the sequence of instructions to produce the traffic lights:
to
trafficlights
rectangle
redposition
redlighton
amberposition
amberlighton
redamberoff
greenposition
greenlighton
end
(Press Enter after END after copying it into Logo.)
Now we draw the lights with:
cs trafficlights
Complete the sequence by: