def play(self): log.log("Launching the game") gfx.start() self.running = True self.screen = gfx.scr() self.gui.init() self.gui.owner = self.world.player self.loop() self.quit()
def waitForInput(key = None): c = -1 if key == None: while str(c)=="-1": c = gfx.scr().getch() return c else: while str(c) != str(key): c = gfx.scr().getch() if c!=-1: log.log(str(c))
def on(self, duration=None): self_level = self.level(AmpBuff.SELF_AMP) team_level = self.level(AmpBuff.TEAM_AMP) if self_level >= self.publish_level: self_level = -1 team_level = min(team_level, self.max_team_level - 1) team_description = self.toggle_buffs( AmpBuff.TEAM_AMP, self.publish_level + team_level) else: if team_level > 0: buff_value = self.buffs[self.publish_level + team_level - 1].get() buff_time = self.buffs[self.publish_level + team_level - 1].timeleft() team_description = f" lv{team_level}({buff_value:.2f}/{buff_time:.2f}s)" else: team_description = " lv0" self_description = self.toggle_buffs(AmpBuff.SELF_AMP, self_level) log( "amp", self.name, f"self{self_description}", f"team{team_description}", ) return self
def on(self): if not self.active: if self.zeroed is not None: self.zeroed[0].index = self.zeroed[1] self.zeroed = None act = self.a_x_alt[1] doing = act._static.doing if not doing.idle and doing.status == -1: try: doing.startup_timer.off() doing._setprev() doing._static.doing = doing.nop act() except: pass log('debug', '{} x_alt on'.format(self.name)) self.active = True self.adv.x = self.x_alt if self.l_x_alt: self.adv.l_x.off() self.l_x_alt.on() if self.no_fs: self.adv.fs = self.act_off if self.no_dodge: self.adv.dodge = self.act_off
def d_shift_end(self, t): if self.action_timer is not None: self.action_timer.off() self.action_timer = None duration = now() - self.shift_start_time log( self.name, '{:.2f}dmg / {:.2f}s, {:.2f} dps'.format( self.shift_damage_sum, duration, self.shift_damage_sum / duration), ' '.join(self.act_sum)) self.act_sum = [] self.act_list = [] self.dracolith_mod.off() if self.off_ele_mod is not None: self.off_ele_mod.off() self.ds_reset() if not self.is_dragondrive: self.shift_silence = True Timer(self.end_silence).on(10) self.dragon_gauge_pause_timer = Timer(self.resume_auto_gauge).on( self.dragon_gauge_timer_diff) self.status = -2 self._setprev() # turn self from doing to prev self._static.doing = self.nop self.end_event() self.idle_event()
def makeLink(self, localName, remoteURL=""): remoteHost = None remotePort = None remoteID = None if remoteURL != "": URL = urlparse(remoteURL) remoteHost = URL.hostname remotePort = settings.defaultPort if URL.port == None else URL.port remoteID = URL.path[1:] self.handleMessage(messages.MakeLink( localHost=self.settings.advertizedHost, localPort=self.settings.advertizedPort, localID=localName, remoteHost=remoteHost, remotePort=remotePort, remoteID=remoteID )) try: self.makeConnection(localName) except network.ConnectFailed: log.log("Connect failed (ignored)") return "amikolink://%s/%s" % \ (self.settings.getAdvertizedNetworkLocation(), localName)
def d_act_do(self, t): if self.c_act_name == 'ds': self.skill_use -= 1 self.skill_spc = 0 self.ds_event() self.shift_damage_sum += self.ds_proc() or 0 self.shift_end_timer.add(self.conf.ds.startup+self.conf.ds.recovery) self.act_sum.append('s') elif self.c_act_name == 'end': self.d_shift_end(None) self.shift_end_timer.off() return elif self.c_act_name != 'dodge': # dname = self.c_act_name[:-1] if self.c_act_name != 'dshift' else self.c_act_name self.shift_damage_sum += self.adv.dmg_make(self.c_act_name, self.c_act_conf.dmg, 'x' if self.c_act_name != 'dshift' else self.c_act_name) if self.c_act_name.startswith('dx'): if len(self.act_sum) > 0 and self.act_sum[-1][0] == 'c' and int(self.act_sum[-1][1]) < int(self.c_act_name[-1]): self.act_sum[-1] = 'c'+self.c_act_name[-1] else: self.act_sum.append('c'+self.c_act_name[-1]) if self.skill_sp > 0 and self.skill_spc < self.skill_sp: self.skill_spc += self.adv.sp_convert(self.adv.sp_mod('x'), 5) if self.skill_spc > self.skill_sp: self.skill_spc = self.skill_sp log(self.c_act_name, 'sp', f'{self.skill_spc}/{self.skill_sp}') if self.c_act_conf.hit > -1: self.adv.hits += self.c_act_conf.hit else: self.adv.hits = -self.c_act_conf.hit self.d_act_next()
def l_extend_time(self, e): if self.get( ) and e.name != 'ds' and e.base == self.base and e.group == self.group: skill = self.adv.a_s_dict[self.base] delta = skill.ac.getstartup() + skill.ac.getrecovery() self.add_time(delta) log('debug', e.name, 'extend', delta)
def check(self, k, group=None, seq=None, *args): if self.get(k, False): subdict = self[k] if group is not None: if isinstance(group, int): group -= 1 if seq is not None: try: return subdict[group][seq].get() except KeyError: return False else: try: log( 'debug', str([(b.name, b.get()) for b in subdict[group].values()])) return any(b.get() for b in subdict[group].values()) except KeyError: return False else: return any(b.get() for sub in subdict.values() for b in sub.values()) else: return False
def handleMessage(self, msg): returnValue = None with self.__node: #makes sure the state is saved or restored in the end messageQueue = [msg] while len(messageQueue) > 0: msg = messageQueue.pop(0) newMessages = [] log.log("Processing message %s" % str(msg.__class__)) #Messages for the API: if msg.__class__ == messages.ReturnValue: #Should happen only once per call of this function. #Otherwise, some return values will be forgotten. returnValue = msg.value else: #All other messages go to the node: newMessages = self.__node.handleMessage(msg) #Put new messages in the right places: for msg in newMessages: if msg.__class__ == messages.TimeoutMessage: #Add to the list of time-out messages: self.__addTimeoutMessage(msg) else: #Process in another iteration of the loop we're in: messageQueue.append(msg) self.__cleanupState() return returnValue
def timeleft(self): from core.log import log log("timeleft", self.timing - _g_now, self.pause_time) if self.pause_time > 0: return self.pause_time return self.timing - _g_now
def effect_on(self): value = self.get() if self.mod_type == "defense" and value > 0: db = Event("defchain") db.source = self.source db.on() if self.bufftype == "team": log("buff", "doublebuff", 15 * self.bufftime()) if self.bufftime == self._bufftime: self._static.adv.slots.c.set_need_bufftime() elif self.mod_type == "maxhp": if self._static.adv.sub_mod("maxhp", "buff") < Buff.MAXHP_BUFF_CAP: self.modifier.on() percent = value * 100 log("heal", self.name, self._static.adv.max_hp * value, "team" if self.bufftype == "team" else "self") self._static.adv.add_hp(percent) # FIXME: heal formula 1day twust elif self.mod_type == "regen" and value != 0: self.set_hp_event = Event("set_hp") self.set_hp_event.delta = value self.regen_timer = Timer(self.hp_regen, 3.9, True).on() elif self.mod_type == "heal" and value != 0: self.set_hp_event = Event("heal_make") self.set_hp_event.name = self.name self.set_hp_event.delta = self._static.adv.heal_formula( self.source, value) self.set_hp_event.target = "team" if self.bufftype == "team" else "self" self.regen_timer = Timer(self.hp_regen, 2.9, True).on() else: return self.modifier and self.modifier.on()
def count_team_buff(self): base_mods = [ Modifier('base_cc', 'crit', 'chance', 0.12), Modifier('base_killer', 'killer','passive', 0.30) ] self.dmg_test_event.modifiers = ModifierDict() for mod in base_mods: self.dmg_test_event.modifiers.append(mod) for b in filter(lambda b: b.get() and b.bufftype == 'simulated_def', self._static.all_buffs): self.dmg_test_event.modifiers.append(b.modifier) self.dmg_test_event() no_team_buff_dmg = self.dmg_test_event.dmg placeholders = [] for b in filter(lambda b: b.get() and b.bufftype in ('team', 'debuff'), self._static.all_buffs): placehold = None if b.modifier.mod_type == 's': placehold = Modifier('placehold_sd', 'att', 'sd', b.modifier.get() / 2) elif b.modifier.mod_type == 'spd': placehold = Modifier('placehold_spd', 'att', 'spd', b.modifier.get()) elif b.modifier.mod_type.endswith('_killer'): placehold = Modifier('placehold_k', 'killer', 'passive', b.modifier.get()) if placehold: self.dmg_test_event.modifiers.append(placehold) placeholders.append(placehold) else: self.dmg_test_event.modifiers.append(b.modifier) self.dmg_test_event() team_buff_dmg = self.dmg_test_event.dmg log('buff', 'team', team_buff_dmg / no_team_buff_dmg - 1) for mod in chain(base_mods, placeholders): mod.off()
def switch_t(self, t): prev_x = t.prev_x_alt log("debug", "{} x_alt off".format(prev_x.name)) if prev_x.active: doing = prev_x.a_x_alt[1]._static.doing prev_x.zeroed = (doing, doing.index) doing.index = 0 prev_x.active = False if prev_x.l_x_alt: prev_x.l_x_alt.off() prev_x.adv.l_x.on() if prev_x.no_fs: prev_x.adv.fs = prev_x.fs_og if prev_x.no_dodge: prev_x.adv.dodge = prev_x.dodge_og log("debug", "{} x_alt on".format(self.name)) self.active = True self.adv.x = self.x_alt if self.l_x_alt: self.adv.l_x.off() self.l_x_alt.on() if self.no_fs: self.adv.fs = self.act_off if self.no_dodge: self.adv.dodge = self.act_off
def check(self, dryrun=True): if self.disabled or self.shift_silence: return False if self.dragon_gauge < self.shift_cost and not ( self.is_dragondrive and self.dragondrive_buff.get()): return False doing = self.getdoing() if not doing.idle: if isinstance(doing, S) or isinstance(doing, DragonForm): return False if dryrun == False: if doing.status == Action.STARTUP: doing.startup_timer.off() doing.end_event() log( "interrupt", doing.name, "by " + self.name, "after {:.2f}s".format(now() - doing.startup_start), ) elif doing.status == Action.RECOVERY: doing.recovery_timer.off() doing.end_event() log( "cancel", doing.name, "by " + self.name, "after {:.2f}s".format(now() - doing.recover_start), ) return True
def d_act_next(self): nact = None if self.repeat_act and not self.act_list: self.parse_act(self.conf.act) if self.act_list: if self.act_list[0] != 'ds' or self.ds_check(): if self.act_list[0] == 'end' and not self.allow_end: nact = None else: nact = self.act_list.pop(0) # print('CHOSE BY LIST', nact, self.c_act_name) if nact is None: if self.c_act_name[0:2] == 'dx': nact = 'dx{}'.format(int(self.c_act_name[2])+1) if not nact in self.dx_list: if self.ds_check(): nact = 'ds' elif self.dodge_cancel(): nact = 'dodge' else: nact = 'dx1' else: nact = 'dx1' # print('CHOSE BY DEFAULT', nact, self.c_act_name) if nact == 'ds' or nact == 'dodge' or (nact == 'end' and self.c_act_name != 'ds'): # cancel count = self.clear_delayed() if count > 0: log('cancel', self.c_act_name, f'by {nact}', f'lost {count} hit{"s" if count > 1 else ""}') self.act_timer(self.d_act_start_t, self.conf.latency, nact) else: # regular recovery self.act_timer(self.d_act_start_t, self.c_act_conf.recovery, nact)
def _charge_utp(self, name, value): # sync with timer value if self.utp_infinte: self.utp_gauge = self.max_utp_gauge if self.status: self.utp_gauge = self.shift_end_timer.timeleft() * self.utp_drain gauge_before = self.utp_gauge # use utp_gauge from here on self.utp_gauge = max(0, min(self.max_utp_gauge, gauge_before + value)) delta = self.utp_gauge - gauge_before if delta != 0: if self.log_utp: log( "utpgauge", name, f"{int(delta):+} ({delta/self.utp_drain:+2.4}s)", f"{int(self.utp_gauge)}/{int(self.max_utp_gauge)} ({self.dtime():2.4}s)", ) if self.utp_gauge <= 0: self.utp_gauge = 0 self.d_shift_end(reason="gauge deplete") else: self.shift_end_timer.add(delta / self.utp_drain) self.utp_event.name = name self.utp_event.value = value self.utp_event.delta = delta self.utp_event.gauge = self.utp_gauge self.utp_event() return value
def __cleanupState(self): with self.__node: #makes sure the state is saved or restored in the end #Remove finished payer and related objects: if not (self.__node.payerLink is None) and \ self.__node.payerLink.state in [payerlink.PayerLink.states.cancelled, payerlink.PayerLink.states.committed]: log.log('Cleaning up payer') if not (self.__node.payerLink.amount is None): self.payLog.writePayer(self.__node.payerLink) self.__node.payerLink = None self.__node.connections[messages.payerLocalID].close() self.__node.timeoutMessages = \ [ msg for msg in self.__node.timeoutMessages if msg.message.__class__ != messages.Timeout ] #Remove finished payee and related objects: payeeIDs = self.__node.payeeLinks.keys() for payeeID in payeeIDs: payee = self.__node.payeeLinks[payeeID] if payee.state in [payeelink.PayeeLink.states.cancelled, payeelink.PayeeLink.states.committed]: log.log('Cleaning up payee ' + payeeID) self.payLog.writePayee(payee) del self.__node.payeeLinks[payeeID] self.__node.connections[payeeID].close()
def __loadState(self): oldFile = self.settings.stateFile + ".old" if os.access(oldFile, os.F_OK): if os.access(self.settings.stateFile, os.F_OK): #Remove old file if normal state file exists: os.remove(oldFile) else: #Use old file if state file does not exist: os.rename(oldFile, self.settings.stateFile) try: with open(self.settings.stateFile, 'rb') as fp: state = json.load(fp) #print state except IOError: log.log("Failed to load from %s" % self.settings.stateFile) log.log("Starting with empty state") state = {"links":[], "meetingPoints":[]} for lnk in state["links"]: self.routingContext.links.append(link.Link( self.context, self.routingContext, self.bitcoind, self.settings, lnk)) for mp in state["meetingPoints"]: self.routingContext.meetingPoints.append( meetingpoint.MeetingPoint(str(mp["ID"])))
def charge_gauge(self, value, utp=False, dhaste=True, percent=False, auto=False): # if dhaste is None: # dhaste = not utp dh = self.dhaste() if dhaste else 1 if utp: dh *= self.adv.mod("utph", operator=operator.add) if percent: value *= self.max_gauge / 100 value = self.adv.sp_convert(dh, value) delta = min(self.dragon_gauge + value, self.max_gauge) - self.dragon_gauge if self.is_dragondrive and self.dragondrive_buff.get(): self.add_drive_gauge_time(delta) elif delta != 0: self.dragon_gauge += delta log( "dragon_gauge", "{:+} ({:+.2f}%)".format(int(delta), delta / self.max_gauge * 100), f"{int(self.dragon_gauge)}/{int(self.max_gauge)}", "{:.2f}%".format(self.dragon_gauge / self.max_gauge * 100), "auto" if auto else "", ) return value
def remove_charges(self): from core.log import log prev_charge = self.Skillful_Charges if self.Skillful_Charges > 0: self.Skillful_Charges -= 1 log('debug', 'Skillful_Trickster', f'+{-1}', self.Skillful_Charges) self.trickster_check(prev_charge)
def d_shift_end(self, t): if self.action_timer is not None: self.action_timer.off() self.action_timer = None duration = now()-self.shift_start_time shift_dmg = g_logs.shift_dmg g_logs.log_shift_dmg(False) count = self.clear_delayed() if count > 0: log('cancel', self.c_act_name, f'by shift end', f'lost {count} hit{"s" if count > 1 else ""}') log(self.name, '{:.2f}dmg / {:.2f}s, {:.2f} dps'.format(shift_dmg, duration, shift_dmg/duration), ' '.join(self.act_sum)) self.act_sum = [] self.act_list = [] if self.off_ele_mod is not None: self.off_ele_mod.off() if self.shift_spd_mod is not None: self.shift_spd_mod.off() self.ds_reset() if not self.is_dragondrive: self.shift_silence = True Timer(self.end_silence).on(10) self.dragon_gauge_pause_timer = Timer(self.resume_auto_gauge).on(self.dragon_gauge_timer_diff) self.status = Action.OFF self._setprev() # turn self from doing to prev self._static.doing = self.nop self.end_event() self.idle_event()
def __call__(self): if not self.check(dryrun=False): return False self.shift_count += 1 if self.is_dragondrive: self.act_list = ['end'] if self.dragondrive_buff.get(): self.d_dragondrive_end('<turn off>') return True else: self.dragondrive_timer.on(self.max_gauge / self.drain) self.dragondrive_buff.on() else: if len(self.act_list) == 0: self.parse_act(self.conf.act) self.dragon_gauge -= self.shift_cost self.dracolith_mod.mod_value = self.ddamage() self.dracolith_mod.on() if self.off_ele_mod is not None: self.off_ele_mod.on() self.pause_auto_gauge() self.shift_damage_sum = 0 self.status = -1 self._setdoing() self.shift_start_time = now() self.shift_end_timer.on(self.dtime()) self.shift_event() log('cast', 'dshift', self.name) self.d_act_start('dshift') return True
def __call__(self): if not self.check(dryrun=False): return False if self.is_dragondrive: self.act_list = ['end'] if self.dragondrive_buff.get(): self.d_dragondrive_end('<turn off>') return True else: log('cast', 'dragondrive', self.name, f'base duration {self.dragon_gauge/self.drain:.4}s') self.dragondrive_timer.on(self.dragon_gauge/self.drain) self.dragondrive_buff.on() else: log('cast', 'dshift', self.name) if len(self.act_list) == 0: self.parse_act(self.conf.act) self.dragon_gauge -= self.shift_cost if self.off_ele_mod is not None: self.off_ele_mod.on() if self.shift_spd_mod is not None: self.shift_spd_mod.on() self.pause_auto_gauge() self.shift_count += 1 self.status = Action.STARTUP self._setdoing() g_logs.log_shift_dmg(True) self.shift_start_time = now() self.shift_end_timer.on(self.dtime()) self.reset_allow_end() self.shift_event() self.d_act_start('dshift') return True
def resume(self, e=None): if self.pause_time > 0: for b in self.buffs: self.pause_time = max(self.pause_time, b.refresh_time) for b in self.buffs: b.buff_end_timer.on(self.pause_time) log("resume", self.pause_by, self.pause_time, now() + self.pause_time) self.pause_time = -1
def __handlePaySignal(self, connection, message): for p in self.payees: if p.ID == message.value: p.connect(connection) return log.log("Received pay message with unknown ID") connection.close()
def __handleLinkSignal(self, connection, message): for lnk in self.routingContext.links: if lnk.localID == message.ID: lnk.connect(connection, message) return log.log("Received link message with unknown ID") connection.close()
def d_act_start(self, name): if name in self.conf and self._static.doing == self and self.action_timer is None: log('d_act', name) self.prev_act = self.c_act_name self.prev_conf = self.c_act_conf self.c_act_name = name self.c_act_conf = self.conf[name] self.act_timer(self.d_act_do, self.c_act_conf.startup)
def permanent_curse(e): if hasattr(adv, 'afflict_guard') and adv.afflict_guard > 0: adv.afflict_guard -= 1 else: adv.skill._static.silence = 1 adv.dragonform.disabled = True from core.log import log log('debug', 'permanent_curse')
def on(self, uses=1): log('debug', 'fs_alt on', uses) self.uses = uses self.adv.a_fs = self.a_fs_alt self.adv.conf = self.conf_alt self.adv.fs_proc = self.fs_proc if self.has_fsf: self.adv.fsf = self.a_fsf_alt
def resume(self, e=None): if self.pause_time > 0: self.pause_time = max(self.pause_time, self.buffs[self.level - 1].refresh_time) self.buffs[self.level - 1].buff_end_timer.on(self.pause_time) log("resume", self.pause_by, self.pause_time, now() + self.pause_time) self.pause_time = -1
def ds_proc_slayer(e): log("ds_proc_slayer", "wweeeee") if o_ds_proc: o_ds_proc() e = adv.Event("slayed") e.count = 25 e.name = "dx" e()
def off(self): log('debug', 'fs_alt off', 0) self.uses = 0 self.adv.a_fs = self.a_fs_og self.adv.conf = self.conf_og self.adv.fs_proc = self.fs_proc_og if self.has_fsf: self.adv.fsf = self.a_fsf_og
def l_extend_time(self, e): if self.get( ) and e.name != "ds" and e.base == self.base and e.group == self.group: skill = self.adv.a_s_dict[self.base] delta = (skill.ac.getstartup() + skill.ac.getrecovery()) / self.adv.speed() self.add_time(delta) log("debug", e.name, "extend", delta)
def reset_allow_end(self): if self.is_dragondrive: self.allow_end = True else: log('allow_end', self.allow_end_cd) self.allow_end = False self.allow_force_end_timer = Timer(self.set_allow_end, timeout=self.allow_end_cd) self.allow_force_end_timer.on() self.allow_end_cd += self.conf.allow_end_step
def x_proc_default(self, e): xseq = e.name dmg_coef = self.conf[xseq].dmg sp = self.conf[xseq].sp hit = self.conf[xseq].hit log("x", xseq, self.name) self.adv.hits += hit self.adv.dmg_make(xseq, dmg_coef) self.adv.charge(xseq, sp)
def d_dragondrive_end(self, t): log('dragondrive', 'end') self.dragondrive_buff.off() Timer(self.end_silence).on(10) self.status = -2 self._setprev() # turn self from doing to prev self._static.doing = self.nop self.dragondrive_end_event() self.idle_event()
def makeConnection(self, ID): persistentConn = self.__node.connections[ID] if None in (persistentConn.host, persistentConn.port, persistentConn.connectMessage): log.log( 'Not enough information for creating connection %s; skipping' % \ ID) return self.__network.makeConnection( (persistentConn.host, persistentConn.port), ID, persistentConn.connectMessage)
def handleMessage(self, msg): returnValue = None setEvents = set([]) with self.__node: #makes sure the state is saved or restored in the end messageQueue = [msg] while len(messageQueue) > 0: msg = messageQueue.pop(0) newMessages = [] log.log("Processing message %s" % str(msg.__class__)) #Messages for the API: if msg.__class__ == messages.ReturnValue: #Should happen only once per call of this function. #Otherwise, some return values will be forgotten. returnValue = msg.value elif msg.__class__ == messages.SetEvent: setEvents.add(msg.event) #Messages for Bitcoind: elif msg.__class__ == messages.BitcoinCommand: #Right now, these messages are not buffered/stored. #We depend on bitcoind to remain available. #TODO: find out whether buffering of messages in the node #state makes sense. newMessages = self.bitcoind.handleMessage(msg) else: #All other messages go to the node: newMessages = self.__node.handleMessage(msg) #Put new messages in the right places: for msg in newMessages: if msg.__class__ == messages.TimeoutMessage: #Add to the list of time-out messages: self.__addTimeoutMessage(msg) else: #Process in another iteration of the loop we're in: messageQueue.append(msg) self.__cleanupState() # Set all generated events, but only after the above processing is # completely finished, and no exceptions have occurred. for e in setEvents: self.__events[e].set() return returnValue
def run(self): """ The thread function. Intended for internal use by Node. Not intended to be part of the API. """ log.log("\n\nAmiko thread started") #Start listening listener = network.Listener(self.context, self.settings.listenHost, self.settings.listenPort) #TODO: (re-)enable creation of new transactions self.__stop = False while True: self.context.dispatchNetworkEvents() self.context.dispatchTimerEvents() self.watchdog.check() with self._commandFunctionLock: s = self._commandFunction if s != None: try: self._commandReturnValue = s[0](self, *s[1], **s[2]) except Exception as e: self._commandReturnValue = e log.logException() self._commandProcessed.set() self._commandFunction = None if self.__doSave: self.__saveState() self.__doSave = False self.__movePayeesToPayLog() if self.__stop: #TODO: stop creation of new transactions #TODO: only break once there are no more open transactions break #This closes all network connections etc. self.context.sendSignal(None, event.signals.quit) log.log("Node thread terminated\n\n")
def __init__(self, conf="amikopay.conf"): """ Constructor. Arguments: conf: Name of the configuration file to be loaded, or a settings.Settings instance """ threading.Thread.__init__(self) if isinstance(conf, settings.Settings): self.settings = conf else: self.settings = settings.Settings(conf) #threading.Thread attribute; used in log.py self.name = self.settings.name self.__network = network.Network( self.settings.listenHost, self.settings.listenPort, callback=self) self.bitcoind = bitcoind.Bitcoind(self.settings) self.payLog = paylog.PayLog(self.settings) self.__stop = False self._commandFunctionLock = threading.Lock() self._commandFunction = None self._commandProcessed = threading.Event() self._commandReturnValue = None # TODO: recover from a state where one of the events can be set, # but the user interface is not waiting for it anymore after a re-start. self.__events = {name: threading.Event() for name in messages.SetEvent.events} self.__node = persistentobject.PersistentObject( filename=self.settings.stateFile, defaultObject=nodestate.NodeState() #empty state; used when file can not be loaded ) #Establish connections for ID in self.__node.connections.keys(): try: self.makeConnection(ID) except network.ConnectFailed as e: log.log("Connect failed (ignored)")
def start(): global screen screen = curses.initscr() curses.noecho() curses.cbreak() curses.curs_set(0) screen.keypad(1) screen.nodelay(1) curses.nonl() screen.scrollok(False) curses.start_color() for i in range(0, 17): curses.init_pair(i+1, i, 0) #log.log("Pair : ({}, {}, 0)".format(i+1,i)) h, w = screen.getmaxyx() log.log("Screen size : {}x{}".format(h, w))
def __saveState(self): state = self.__getState(forDisplay=False) #ensure_ascii doesn't seem to do what I expected, #so it becomes required that state is ASCII-only. state = json.dumps(state, sort_keys=True, ensure_ascii=True, indent=4, separators=(',', ': ')) #print state newFile = self.settings.stateFile + ".new" log.log("Saving in " + newFile) with open(newFile, 'wb') as fp: fp.write(state) oldFile = self.settings.stateFile + ".old" #Replace old data with new data os.rename(self.settings.stateFile, oldFile) os.rename(newFile, self.settings.stateFile) os.remove(oldFile)
def __init__(self): #self.map = utils.textToMap("data/map.txt") self.map = utils.generateMap(29,71) self.min_y = 0 self.min_x = 0 self.w = len(self.map[0]) self.h = len(self.map) self.seen = [[0 for i in range(self.w)] for j in range(self.h)] self.player = entity.Player("Character Random Name", 4, 6) self.entities = utils.jsonToEntities("data/ent_map.json") self.chests = utils.jsonToChests("data/items.json") self.moving = True self.fov = None log.log("{} entité(s) chargée(s)".format(len(self.entities))) log.log("-----Debut Map------") for y in self.map: tLigne = "" for x in y: tLigne+=x log.log(tLigne) log.log("-----Fin Map------") log.log("Taille map : {}x{}".format(self.h, self.w))
def run(self): """ The thread function. Intended for internal use by Node. Not intended to be part of the API. """ log.log("\n\nNode thread started") #TODO: (re-)enable creation of new transactions self.__stop = False while True: self.__network.processNetworkEvents(timeout=0.01) #API events: with self._commandFunctionLock: s = self._commandFunction if s != None: try: self._commandReturnValue = s[0](self, *s[1], **s[2]) except Exception as e: self._commandReturnValue = e log.logException() self._commandProcessed.set() self._commandFunction = None #Time-out events: while len(self.__node.timeoutMessages) > 0 and self.__node.timeoutMessages[0].timestamp < time.time(): msg = self.__node.timeoutMessages.pop(0) self.handleMessage(msg.message) #Connections: data transmission and closing doSaveState = False for localID, c in self.__node.connections.copy().iteritems(): #New attempt to send the outbox: if c.transmit(self.__network): doSaveState = True #Close interface whenever requested: if c.canBeClosed(): log.log('Closing persistent connection ' + localID) del self.__node.connections[localID] self.__network.closeInterface(localID) doSaveState = True if doSaveState: self.__node.save() if self.__stop: #TODO: stop creation of new transactions #TODO: only break once there are no more open transactions break log.log("Node thread terminated\n\n")
def log(self, text): self.logs.append(text) if len(self.logs)>self.nbLines+15: self.logs.remove(self.logs[0]) log.log(text)
def quit(self): gfx.stop() log.log("Stopping the game")
def __handleSaveSignal(self): log.log("Save handler called") self.__doSave = True