The class Light
The class Light
will represent a traffic light.
A traffic light is characterized by the following properties:
- Its period, i.e. the number of time steps between two transitions from green to red.
- Green period, i.e. the number of time steps that the light is green.
The sequence for a signal of period 7 and green period 3 can be illustrated as:
Time step: | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
Internal clock: | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 0 | 1 |
Color: | G | G | G | R | R | R | R | G | G | G | R | R | R | R | G | G |
Note that the internal clock is not stored as an instance variable since it can easily
be computed with the help of the global time step clock wallclock.get_time()
.
By doing this we avoid writing a method that steps the traffic light.
We need to be able to ask the light if it is green or not, but this property does not need to be stored as an instance variable either, and can easily be computed every time the question is asked.
We thus arrive at the following class diagram: |
![]() |
wallclock.tick()
.