基于莫尔型状态机的简易状态机交通灯控制系统设计代码
时间: 2024-12-13 07:12:47 浏览: 10
基于莫尔型( Moore 图)的状态机用于交通信号灯控制系统的设计,通常采用固定的输入和输出关联规则。以下是一个简单的Python伪代码示例,描述了如何创建一个四路口交通灯控制系统的状态机:
```python
class TrafficLightStateMachine:
def __init__(self):
self.states = {
"Red": {"NorthSouth": "Green", "EastWest": "Yellow"},
"Green": {"NorthSouth": "Yellow", "EastWest": "Red"},
"Yellow": {"NorthSouth": "Red", "EastWest": "Red"}
}
self.current_state = "Red"
def update(self, direction):
next_state = self.states[self.current_state][direction]
print(f"{direction} turning is {next_state}")
self.current_state = next_state
# 实例化并开始操作
traffic_light = TrafficLightStateMachine()
while True:
# 用户输入方向(例如:"North"、"South"、"East"、"West")
user_direction = input("Enter direction (North/South/East/West): ")
# 更新对应的方向灯状态
traffic_light.update(user_direction)
time.sleep(3) # 模拟红绿黄灯切换时间,这里实际应用可能需要硬件延时
阅读全文