帮我生成一个控制2个电梯运行的python代码
时间: 2023-04-03 17:02:37 浏览: 36
好的,以下是一个控制2个电梯运行的Python代码:
```python
class Elevator:
def __init__(self, id):
self.id = id
self.current_floor = 1
self.direction = 1
self.destinations = []
def add_destination(self, floor):
if floor not in self.destinations:
self.destinations.append(floor)
self.destinations.sort()
def move(self):
if not self.destinations:
return
if self.current_floor == self.destinations[]:
self.destinations.pop()
if not self.destinations:
return
if self.current_floor < self.destinations[]:
self.current_floor += 1
self.direction = 1
elif self.current_floor > self.destinations[]:
self.current_floor -= 1
self.direction = -1
class ElevatorController:
def __init__(self):
self.elevators = [Elevator(1), Elevator(2)]
def request_elevator(self, floor):
elevator = self._get_nearest_elevator(floor)
elevator.add_destination(floor)
return elevator.id
def _get_nearest_elevator(self, floor):
distances = []
for elevator in self.elevators:
if elevator.direction == 1 and floor >= elevator.current_floor:
distances.append(floor - elevator.current_floor)
elif elevator.direction == -1 and floor <= elevator.current_floor:
distances.append(elevator.current_floor - floor)
else:
distances.append(abs(elevator.current_floor - floor))
return self.elevators[distances.index(min(distances))]
def step(self):
for elevator in self.elevators:
elevator.move()
```
这个代码实现了一个电梯控制器,可以控制两个电梯运行。你可以调用 `request_elevator` 方法来请求电梯,然后电梯会自动运行到你所在的楼层。你可以调用 `step` 方法来让电梯控制器运行一步,这样电梯就会移动到下一个目的地。