Class Light
The class Light
represents a traffic signal.
A traffic signal is characterized by the following attributes:
- period i.e. the number of time steps between two changes from green to red
- green period i.e. the number of time steps where the signal is green.
The course of a signal with period 7 and green period 3 can be illustrated in this way:
Timestep | 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 |
A signal thus has an internal clock that runs "circular", i.e. it starts at zero and goes to the period length after which it starts at zero again.
The class needs
-
a constructor
Light(period, green_period)
which specifies the attributes, -
a method
step()
which advances the internal clock, -
a method
is_green()
which returnsTrue
if the signal is green, andFalse
otherwise,and -
a
__str__()
-method that returns an appropriate text representation of the signal.
Note that the color does not need to be stored as an instantiated variable. That attribute is easily calculated based on the value of the green period and the value of the internal clock.
Demonstration:Kod | Utskrift |
---|---|
def demo_light(): """Demonstrats the Light class""" a_light = Light(7, 3) for i in range(15): print(i, a_light, a_light.is_green()) a_light.step() | 0 (G) True 1 (G) True 2 (G) True 3 (R) False 4 (R) False 5 (R) False 6 (R) False 7 (G) True 8 (G) True 9 (G) True 10 (R) False 11 (R) False 12 (R) False 13 (R) False 14 (G) True |