| 1 |
# |
| 2 |
# trafficlightstate.pystate |
| 3 |
# |
| 4 |
# state machine model of the states and associated behaviors and properties for each |
| 5 |
# different state of a traffic light |
| 6 |
|
| 7 |
|
| 8 |
# define state machine with transitions |
| 9 |
# (states will be implemented as Python classes, so use name case appropriate for class names) |
| 10 |
statemachine TrafficLightState: |
| 11 |
Red -> Green |
| 12 |
Green -> Yellow |
| 13 |
Yellow -> Red |
| 14 |
|
| 15 |
|
| 16 |
# statemachine only defines the state->state transitions - actual behavior and properties |
| 17 |
# must be added separately |
| 18 |
|
| 19 |
|
| 20 |
# define some class level constants |
| 21 |
Red.cars_can_go = False |
| 22 |
Yellow.cars_can_go = True |
| 23 |
Green.cars_can_go = True |
| 24 |
|
| 25 |
|
| 26 |
# setup some class level methods |
| 27 |
def flash_crosswalk(s): |
| 28 |
def flash(): |
| 29 |
print(f"{s}...{s}...{s}") |
| 30 |
|
| 31 |
return flash |
| 32 |
|
| 33 |
Red.crossing_signal = staticmethod(flash_crosswalk("WALK")) |
| 34 |
Yellow.crossing_signal = staticmethod(flash_crosswalk("DONT WALK")) |
| 35 |
Green.crossing_signal = staticmethod(flash_crosswalk("DONT WALK")) |
| 36 |
|
| 37 |
|
| 38 |
# setup some instance methods |
| 39 |
def wait(nSeconds): |
| 40 |
def waitFn(self): |
| 41 |
print("<wait %d seconds>" % nSeconds) |
| 42 |
|
| 43 |
return waitFn |
| 44 |
|
| 45 |
Red.delay = wait(20) |
| 46 |
Yellow.delay = wait(3) |
| 47 |
Green.delay = wait(15) |