Created
September 14, 2021 11:56
-
-
Save skipperkongen/a33bcf2df971c6df1fcc77284077643b to your computer and use it in GitHub Desktop.
Lazer simulation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import simpy | |
import random | |
import statistics | |
env = simpy.Environment() | |
charger = simpy.Resource(env, 5) | |
class Lazer(object): | |
def __init__(self, env, id, charger): | |
self.env = env | |
self.id = id | |
self.shots_fired = 0 | |
self.charger = charger | |
# Start the run process everytime an instance is created. | |
self.action = env.process(self.run()) | |
def run(self): | |
while True: | |
with self.charger.request() as request: | |
yield request | |
print(f'[{env.now}] Lazer {self.id} plugging into charger') | |
yield self.env.timeout(1) | |
# We yield the process that process() returns | |
# to wait for it to finish | |
yield self.env.process(self.charge()) | |
# Fire | |
print(f'[{env.now}] Lazer {self.id} fired!!') | |
self.shots_fired += 1 | |
# Cool down | |
duration = random.randint(1, 10) | |
print(f'[{env.now}] Lazer {self.id} cooling down for {duration} seconds') | |
yield self.env.timeout(duration) | |
def charge(self): | |
print(f'[{env.now}] Lazer {self.id} charging') | |
duration = random.randint(1,5) | |
yield self.env.timeout(duration) | |
lazers = [] | |
for lazer_id in range(10): | |
lazers.append(Lazer(env, lazer_id+1, charger)) | |
env.run(until=15) | |
print('Average shots fired:', statistics.mean([l.shots_fired for l in lazers])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment