-
Notifications
You must be signed in to change notification settings - Fork 5.9k
Expand file tree
/
Copy pathintersection_state.py
More file actions
67 lines (51 loc) · 2.57 KB
/
intersection_state.py
File metadata and controls
67 lines (51 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from abc import ABC, abstractmethod
from direction import Direction
from light_color import LightColor
from typing import TYPE_CHECKING
import time
if TYPE_CHECKING:
from intersection_controller import IntersectionController
class IntersectionState(ABC):
@abstractmethod
def handle(self, context: 'IntersectionController'):
pass
class EastWestGreenState(IntersectionState):
def handle(self, context: 'IntersectionController'):
print(f"\n--- INTERSECTION {context.get_id()}: Cycle -> East-West GREEN ---")
# Turn East and West green, ensure North and South are red
context.get_light(Direction.EAST).start_green()
context.get_light(Direction.WEST).start_green()
context.get_light(Direction.NORTH).set_color(LightColor.RED)
context.get_light(Direction.SOUTH).set_color(LightColor.RED)
# Wait for green light duration
time.sleep(context.get_green_duration() / 1000.0)
# Transition East and West to Yellow
context.get_light(Direction.EAST).transition()
context.get_light(Direction.WEST).transition()
# Wait for yellow light duration
time.sleep(context.get_yellow_duration() / 1000.0)
# Transition East and West to Red
context.get_light(Direction.EAST).transition()
context.get_light(Direction.WEST).transition()
# Change the intersection's state back to let North-South go
context.set_state(NorthSouthGreenState())
class NorthSouthGreenState(IntersectionState):
def handle(self, context: 'IntersectionController'):
print(f"\n--- INTERSECTION {context.get_id()}: Cycle Start -> North-South GREEN ---")
# Turn North and South green, ensure East and West are red
context.get_light(Direction.NORTH).start_green()
context.get_light(Direction.SOUTH).start_green()
context.get_light(Direction.EAST).set_color(LightColor.RED)
context.get_light(Direction.WEST).set_color(LightColor.RED)
# Wait for green light duration
time.sleep(context.get_green_duration() / 1000.0)
# Transition North and South to Yellow
context.get_light(Direction.NORTH).transition()
context.get_light(Direction.SOUTH).transition()
# Wait for yellow light duration
time.sleep(context.get_yellow_duration() / 1000.0)
# Transition North and South to Red
context.get_light(Direction.NORTH).transition()
context.get_light(Direction.SOUTH).transition()
# Change the intersection's state to let East-West go
context.set_state(EastWestGreenState())