帮我写一段关于电影院排队python的simpy代码
时间: 2024-02-07 19:04:03 浏览: 63
当然可以,下面是关于电影院排队的Python代码:
```python
import simpy
import random
total_time = 120
movie_time = 90
num_people = 20
arrive_time = 0
wait_times = []
class Person:
def __init__(self, env, name, enter_time):
self.env = env
self.name = name
self.enter_time = enter_time
def buy_ticket(self, movie):
with movie.ticket.request() as request:
yield request
yield self.env.timeout(random.randint(1, 3))
print(f"{self.name}买完票了")
def go_to_movie(self, movie):
with movie.entrance.request() as request:
yield request
yield self.env.timeout(random.randint(1, 3))
print(f"{self.name}进入了影院")
wait_time = self.env.now - self.enter_time
wait_times.append(wait_time)
print(f"{self.name}等了{wait_time}分钟")
yield self.env.timeout(movie_time)
print(f"{self.name}观影结束,离开影院")
def generate_people(env, num_people, arrive_time, movie):
for i in range(num_people):
p = Person(env, f"顾客{i + 1}", env.now)
env.process(p.buy_ticket(movie))
env.process(p.go_to_movie(movie))
inter_arrival_time = random.expovariate(1.0 / arrive_time)
yield env.timeout(inter_arrival_time)
class Movie:
def __init__(self, env):
self.ticket = simpy.Resource(env, capacity=1)
self.entrance = simpy.Resource(env, capacity=1)
env = simpy.Environment()
movie = Movie(env)
env.process(generate_people(env, num_people, arrive_time, movie))
env.run(until=total_time)
print(f"所有观影者平均等待时间为 {sum(wait_times) / len(wait_times):.2f} 分钟")
```
这段代码使用了simpy模块来模拟电影院排队的过程,人们先买票,然后等待进入影院观影。模拟过程中记录了每个人的等待时间,最后统计平均等待时间。希望可以帮到你!
阅读全文