Skip to content

Instantly share code, notes, and snippets.

@skipperkongen
Created September 14, 2021 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skipperkongen/a33bcf2df971c6df1fcc77284077643b to your computer and use it in GitHub Desktop.
Save skipperkongen/a33bcf2df971c6df1fcc77284077643b to your computer and use it in GitHub Desktop.
Lazer simulation
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