面向对象电梯仿真的python代码
时间: 2023-10-12 19:16:46 浏览: 56
以下是一个简单的面向对象电梯仿真的 Python 代码:
```python
class Elevator:
def __init__(self, floors):
self.floors = floors
self.current_floor = 1
self.direction = 0 # 0 for idle, 1 for up, -1 for down
self.destinations = []
def add_destination(self, floor):
self.destinations.append(floor)
self.direction = 1 if floor > self.current_floor else -1
def move(self):
if self.destinations:
if self.current_floor in self.destinations:
self.destinations.remove(self.current_floor)
if not self.destinations:
self.direction = 0
if self.direction == 1:
self.current_floor += 1
elif self.direction == -1:
self.current_floor -= 1
def __str__(self):
return f"Elevator is on floor {self.current_floor} going {'up' if self.direction == 1 else 'down' if self.direction == -1 else 'nowhere'} with destinations {self.destinations}"
class Building:
def __init__(self, num_floors, num_elevators):
self.floors = num_floors
self.elevators = [Elevator(num_floors) for _ in range(num_elevators)]
def call_elevator(self, floor):
elevators = sorted(self.elevators, key=lambda e: abs(e.current_floor - floor))
elevators[0].add_destination(floor)
def step(self):
for elevator in self.elevators:
elevator.move()
def __str__(self):
return "\n".join(str(elevator) for elevator in self.elevators)
```
使用方式:
```python
# create a building with 10 floors and 2 elevators
building = Building(10, 2)
# call an elevator to floor 5
building.call_elevator(5)
# simulate a few steps
building.step()
building.step()
building.step()
# print the state of the elevators
print(building)
```
这个简单的代码模拟了一个有多个电梯的楼房,可以通过 `call_elevator` 方法调用电梯到指定楼层,模拟电梯的运行过程。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)