from nullptr.store import store from nullptr.models.ship import Ship from nullptr.mission import * from random import choice from time import sleep class CentralCommand: def __init__(self, api): self.missions = {} self.stopping = False self.api = api self.update_missions() def get_ready_missions(self): result = [] for ship, mission in self.missions.items(): if mission.is_ready(): result.append(ship) return result def tick(self): missions = self.get_ready_missions() if len(missions) == 0: return ship = choice(missions) mission = self.missions[ship] mission.step() def run(self): self.update_missions() while not self.stopping: self.tick() self.api.save() sleep(0.5) self.stopping = False def stop(self): self.stopping = True def set_mission_param(self, ship, nm, val): if ship not in self.missions: print('set a mission for this ship first') return mission = self.missions[ship] params = mission.params() if not nm in params: print(f'{nm} is not a valid param') return param = params[nm] try: parsed_val = param.parse(val) except ValueError as e: print(e) return print('ok') ship.mission_state[nm] = parsed_val def update_missions(self): for s in store.all(Ship): if s.mission is None: if s in self.missions: self.stop_mission(s) elif s not in self.missions: self.start_mission(s) def start_mission(self, s): mtype = s.mission m = create_mission(mtype, s, self.api) self.missions[s] = m return m def stop_mission(self, s): if s in self.missions: del self.missions[s]