四层电梯程序
时间: 2023-11-27 15:55:08 浏览: 29
以下是一个简单的四层电梯程序示例:
```python
class Elevator:
def __init__(self):
self.current_floor = 1
self.direction = "up"
self.destinations = []
def add_destination(self, floor):
if floor not in self.destinations:
self.destinations.append(floor)
if self.direction == "up":
self.destinations.sort()
else:
self.destinations.sort(reverse=True)
def move(self):
if len(self.destinations) == 0:
return
if self.direction == "up":
self.current_floor += 1
else:
self.current_floor -= 1
if self.current_floor in self.destinations:
self.destinations.remove(self.current_floor)
print("Elevator stopped at floor", self.current_floor)
if len(self.destinations) == 0:
self.direction = "up"
elif self.current_floor == max(self.destinations):
self.direction = "down"
elif self.current_floor == min(self.destinations):
self.direction = "up"
self.move()
elevator = Elevator()
elevator.add_destination(3)
elevator.add_destination(1)
elevator.add_destination(4)
elevator.add_destination(2)
elevator.move()
```
解释:
1. 创建一个 `Elevator` 类,其中包含电梯当前所在楼层、电梯运行方向、电梯要到达的目标楼层等属性。
2. 定义 `add_destination` 方法,用于将用户需要前往的楼层添加到目标列表中,并根据当前电梯方向对目标列表进行排序。
3. 定义 `move` 方法,用于模拟电梯的运行过程。
4. 首先判断目标列表是否为空,如果是,则直接返回。
5. 如果电梯方向为向上,则当前楼层加1,否则减1。
6. 判断当前楼层是否是目标列表中的一个目标楼层,如果是,则将该楼层从目标列表中删除,并输出电梯停在该楼层的消息。
7. 如果目标列表为空,则将电梯方向设置为向上。
8. 如果当前楼层是目标列表中最大的楼层,则将电梯方向设置为向下。
9. 如果当前楼层是目标列表中最小的楼层,则将电梯方向设置为向上。
10. 最后递归调用 `move` 方法,继续模拟电梯的运行过程。
11. 创建一个 `Elevator` 实例,通过调用 `add_destination` 方法添加目标楼层,最后调用 `move` 方法开始模拟电梯的运行过程。