def choose_server_ip_in_a_list(self): servers_list = None try: f = urllib.urlopen(SERVERS_LIST_URL) if f.read(len(SERVERS_LIST_HEADER)) == SERVERS_LIST_HEADER: servers_list = f.readlines() except: pass if servers_list is None: voice.alert([1029]) # hostile sound warning("couldn't get the servers list from the metaserver" " => using the default servers list") servers_list = DEFAULT_SERVERS nb = 0 menu = Menu() for s in servers_list: try: ip, version, login, port = s.split()[1:] # ignore the first parameter (time) except: warning("line not recognized from the metaserver: %s", s) continue nb += 1 if version == VERSION: menu.append([login, 4073, login], (connect_and_play, ip, port)) menu.title = nb2msg(len(menu.choices)) + [4078] + nb2msg(nb) + [4079] menu.append([4075, 4076], None) menu.run()
def input_string(msg=[], pattern="^[a-zA-Z0-9]$", default="", spell=True): voice.menu(msg) s = default while True: e = pygame.event.poll() if e.type == QUIT: sys.exit() elif e.type == KEYDOWN: pygame.event.clear() if e.key in [K_LSHIFT, K_RSHIFT]: continue if e.key in (K_RETURN, K_KP_ENTER): voice.item([s]) return s elif e.key == K_ESCAPE: return None elif e.key == K_BACKSPACE: s = s[:-1] voice.item(string_to_msg(s, spell)) elif re.match(pattern, e.unicode) != None: try: c = e.unicode.encode("ascii") # telnetlib doesn't like unicode s += c voice.item(string_to_msg(c) + [9999] + string_to_msg(s, spell)) except: warning("error reading character from keyboard") voice.item([1003, 9999] + string_to_msg(s, spell)) else: voice.item([1003, 9999] + string_to_msg(s, spell)) elif e.type == USEREVENT: voice.update() voice.update() # XXX useful for SAPI
def _unzip(self, zip_name): z = zipfile.ZipFile(zip_name) for name in z.namelist(): if name.startswith(self.name) and ".." not in name: z.extract(name, PACKAGES_PATH) else: warning("didn't extract %s", name)
def update(self): s = self.main_server.read_line() if s is not None: args = s.split() if args[0] == "pong": chrono.stop("ping") elif args[0] == "all_orders": self.all_orders.append(args[1:]) self.delay = time.time() - self.interface.next_update elif args[0] == "synchronization_error": if IS_DEV_VERSION: open("user/tmp/%s-%s.txt" % ( self.world.previous_state[0], md5(self.world.previous_state[1]).hexdigest()), "w").write(self.world.previous_state[1]) open("user/tmp/%s-%s.txt" % ( self.world.previous_previous_state[0], md5(self.world.previous_previous_state[1]).hexdigest()), "w").write(self.world.previous_previous_state[1]) else: try: send_error_to_metaserver(self.get_sync_debug_msg_1()) send_error_to_metaserver(self.get_sync_debug_msg_2()) except: exception("error sending sync debug data") else: warning("ignored data from server: %s", s) # check for timeout and alert server if time.time() > self._previous_update + 5.0: self.main_server.write_line("timeout") self._previous_update += 5.0
def __init__(self, replay): self._file = open(replay) game_type_name = self.replay_read() if game_type_name in ("multiplayer", "training"): self.default_triggers = _MultiplayerGame.default_triggers game_name = self.replay_read() version = self.replay_read() mods = self.replay_read() _compatibility_version = self.replay_read() if _compatibility_version != compatibility_version(): voice.alert([1029, 4012]) # hostile sound "version error" warning("Version mismatch. Version should be: %s. Mods should be: %s.", version, mods) self.map = Map() self.map.unpack(self.replay_read()) players = self.replay_read().split() self.alliances = map(int, self.replay_read().split()) self.races = self.replay_read().split() self.seed = int(self.replay_read()) self.me = ReplayClient(players[0], self) self.players = [self.me] for x in players[1:]: if x in ["aggressive", "easy"]: # the "ai_" prefix wasn't recorded self.players += [DummyClient(x)] else: self.players += [HalfDummyClient(x)] self.me.nb_humans += 1
def __init__(self, replay): self._file = open(replay) game_type_name = self.replay_read() if game_type_name in ("multiplayer", "training"): self.default_triggers = _MultiplayerGame.default_triggers game_name = self.replay_read() voice.alert([game_name]) version = self.replay_read() mods = self.replay_read() if mods != config.mods: config.mods = mods reload_all() _compatibility_version = self.replay_read() if _compatibility_version != compatibility_version(): voice.alert([1029, 4012]) # hostile sound "version error" warning( "Version mismatch. Version should be: %s. Mods should be: %s.", version, mods) self.map = Map() self.map.unpack(self.replay_read()) players = self.replay_read().split() self.alliances = map(int, self.replay_read().split()) self.factions = self.replay_read().split() self.seed = int(self.replay_read()) self.me = ReplayClient(players[0], self) self.players = [self.me] for x in players[1:]: if x in ["aggressive", "easy"]: # the "ai_" prefix wasn't recorded self.players += [DummyClient(x)] else: self.players += [HalfDummyClient(x)] self.me.nb_humans += 1
def take_order(self, o, forget_previous=True, imperative=False, order_id=None): # an imperative "go" order on a unit is an "attack" order # note: this could be done by the user interface if imperative and o[0] == "go": target = self.player.get_object_by_id(o[1]) if getattr(target, "player", None) is not None: o[0] = "attack" if self.is_inside: self.place.notify("order_impossible") return cls = ORDERS_DICT.get(o[0]) if cls is None: warning("unknown order: %s", o) return if not cls.is_allowed(self, *o[1:]): self.notify("order_impossible") debug("wrong order to %s: %s", self.type_name, o) return if forget_previous and not cls.never_forget_previous: self.cancel_all_orders() order = cls(self, o[1:]) order.id = order_id if imperative: order.is_imperative = imperative order.immediate_action()
def add_block(self, block): # check last hash if self.get_last_hash() != block.previous_hash: warning('last hash not matching') return False # check transactions validity if not block.is_valid(self): warning('block not valid') return False debug('accepted block') # add block, save THEN change last hash self.db.add_json_block(self.get_last_hash(), block.toJson()) self.db.set_last_hash(block.get_hash()) # reward sender self.update_addresses_amount([(block.miner_address, Blockchain.REWARD) ]) # transactions are already checked within block for t in block.transactions: sender = t.senderAddress() self.db.set_address_spent(sender, True) self.update_addresses_amount(t.receivers) return True
def enable(self): try: self.plex = fetch_plex_instance(self.pi_dash) super(Plugin, self).enable() except NotFound: log.warning('Plex server not available.') return self.disable()
def loop(): _buf = "" while True: try: _buf = sock.recv(4) if not _buf: continue len_, = struct.unpack(">I", _buf[:4]) _buf = _buf[4:] while True: _buf += sock.recv(512) if len(_buf) >= len_: break ctx = _buf[:len_] _buf = _buf[len_:] timeout.reset_timeout() protocol.data_received(ctx) except Timeout: log.warning("%r disconnect timeout", addr) sock.close() break except Exception as e: log.error("%r disconnect error:%s", *(addr, repr(e))) sock.close() break
def __init__(self, replay): self._file = open(replay) game_type_name = self.replay_read() if game_type_name in ("multiplayer", "training"): self.default_triggers = _MultiplayerGame.default_triggers game_name = self.replay_read() voice.alert([game_name]) version = self.replay_read() mods = self.replay_read() res.set_mods(mods) _compatibility_version = self.replay_read() if _compatibility_version != compatibility_version(): voice.alert([1029, 4012]) # hostile sound "version error" warning("Version mismatch. Version should be: %s. Mods should be: %s.", version, mods) campaign_path_or_packed_map = self.replay_read() if game_type_name == "mission" and "***" not in campaign_path_or_packed_map: from campaign import Campaign self.map = Campaign(campaign_path_or_packed_map)._get(int(self.replay_read())) else: self.map = Map() self.map.unpack(campaign_path_or_packed_map) players = self.replay_read().split() self.alliances = map(int, self.replay_read().split()) self.factions = self.replay_read().split() self.seed = int(self.replay_read()) self.me = ReplayClient(players[0], self) self.players = [self.me] for x in players[1:]: if x in ["aggressive", "easy"]: # the "ai_" prefix wasn't recorded self.players += [DummyClient(x)] else: self.players += [HalfDummyClient(x)] self.me.nb_humans += 1
def init_position(self): def equivalent_type(t): tn = getattr(t, "type_name", "") if rules.get(self.faction, tn): return self.world.unit_class(rules.get(self.faction, tn)[0]) return t self.resources = self.start[0][:] normalize_cost_or_resources(self.resources) self.gathered_resources = self.resources[:] for place, type_ in self.start[1]: if self.world.must_apply_equivalent_type: type_ = equivalent_type(type_) if isinstance(type_, str) and type_[0:1] == "-": self.forbidden_techs.append(type_[1:]) elif isinstance(type_, Upgrade): self.upgrades.append( type_.type_name ) # type_.upgrade_player(self) would require the units already there elif not type_: warning("couldn't create an initial unit") else: place = self.world.grid[place] x, y, land = place.find_and_remove_meadow(type_) x, y = place.find_free_space(type_.airground_type, x, y) if x is not None: unit = type_(self, place, x, y) unit.building_land = land self.triggers = self.start[2] if rules.get(self.faction, getattr(self, "AI_type", "")): self.set_ai(rules.get(self.faction, self.AI_type)[0])
def update(self): s = self.main_server.read_line() if s is not None: args = s.split() if args[0] == "pong": chrono.stop("ping") elif args[0] == "all_orders": self.all_orders.append(args[1:]) self.delay = time.time() - self.interface.next_update elif args[0] == "synchronization_error": if IS_DEV_VERSION: open( "user/tmp/%s-%s.txt" % (self.world.previous_state[0], md5(self.world.previous_state[1]).hexdigest()), "w").write(self.world.previous_state[1]) open( "user/tmp/%s-%s.txt" % (self.world.previous_previous_state[0], md5(self.world.previous_previous_state[1]).hexdigest( )), "w").write(self.world.previous_previous_state[1]) else: try: send_error_to_metaserver(self.get_sync_debug_msg_1()) send_error_to_metaserver(self.get_sync_debug_msg_2()) except: exception("error sending sync debug data") else: warning("ignored data from server: %s", s) # check for timeout and alert server if time.time() > self._previous_update + 5.0: self.main_server.write_line("timeout") self._previous_update += 5.0
def unit_class(self, s): """Get a class-like unit generator from its name. Example: unit_class("peasant") to get a peasant generator At the moment, unit_classes contains also: upgrades, abilities... """ if not self.unit_classes.has_key(s): try: base = self.unit_base_classes[rules.get(s, "class")[0]] except: if rules.get(s, "class") != ["race"]: warning("no class defined for %s", s) self.unit_classes[s] = None return try: dct = rules.get_dict(s) t = Type(s, (base,), dct) if base is Upgrade: t = base(s, dct) # factory-prototypes are only for units self.unit_classes[s] = t except: exception("problem with unit_class('%s')", s) self.unit_classes[s] = None return return self.unit_classes[s]
def execute_command(self, data): args = string.split(data) cmd = "cmd_" + string.lower(args[0]) if hasattr(self, cmd): getattr(self, cmd)(args[1:]) else: warning("unknown command: '%s' (%s)" % (cmd, data))
def play(self): if self.AI_type == "timers": return if not self._should_play_this_turn(): return #print self.number, "plays turn", self.world.turn self._update_effect_users_and_workers() self._update_time_has_come() self._send_workers_to_forgotten_building_sites() self._idle_workers_gather() self._send_explorer() if self._attacked_places: self._eventually_attack(self._attacked_places) self._attacked_places = [] elif self.constant_attacks: self._eventually_attack(self._enemy_presence) if self.research: self.idle_buildings_research() self._raise_dead() self._build_a_warehouse_if_useful() self.get(10, self.equivalent("peasant")) try: self._follow_plan() except RuntimeError: warning("recursion error with %s; current ai.txt line is: %s", self.AI_type, self._plan[self._line_nb]) if IS_DEV_VERSION: exception("") self._line_nb += 1 # go to next step
def get_all_orders_from_server(self): # assertion: the orders arrive in the right order (guaranteed by the server) s = self.main_server.read_line() if s is not None: debug("main server data for %s: %s", self.login, s) args = s.split() if args[0] == "all_orders": self.orders_digest.update(s) # used by the synchronization debugger players_orders = args[1:] for player_orders in players_orders: player, orders = player_orders.split("/") orders = orders.replace(NEWLINE_REPLACEMENT, "\n").replace(SPACE_REPLACEMENT, " ") for order in orders.strip().split("\n"): # strip() to remove empty order at the end of the list direct_player = self.get_client_by_login(player).player if direct_player: debug("player: %s order: %s", player, order) self.queue_command(direct_player, order) if order != "update" and not order.startswith("control"): self._all_orders += order.replace("order 0 0 ", "") + ";" self._all_orders = self._all_orders[-100:] elif args[0] == "synchronization_error": try: send_error_to_metaserver(self.get_sync_debug_msg_1()) send_error_to_metaserver(self.get_sync_debug_msg_2()) except: exception("error sending sync debug data") else: warning("ignored data from server: %s", s)
def init_position(self): def equivalent_type(t): tn = getattr(t, "type_name", "") if rules.get(self.faction, tn): return self.world.unit_class(rules.get(self.faction, tn)[0]) return t self.resources = self.start[0][:] normalize_cost_or_resources(self.resources) self.gathered_resources = self.resources[:] for place, type_ in self.start[1]: if self.world.must_apply_equivalent_type: type_ = equivalent_type(type_) if isinstance(type_, str) and type_[0:1] == "-": self.forbidden_techs.append(type_[1:]) elif isinstance(type_, Upgrade): self.upgrades.append(type_.type_name) # type_.upgrade_player(self) would require the units already there elif not type_: warning("couldn't create an initial unit") else: place = self.world.grid[place] x, y, land = place.find_and_remove_meadow(type_) x, y = place.find_free_space(type_.airground_type, x, y) if x is not None: unit = type_(self, place, x, y) unit.building_land = land self.triggers = self.start[2] if rules.get(self.faction, getattr(self, "AI_type", "")): self.set_ai(rules.get(self.faction, self.AI_type)[0])
def unit_class(self, s): """Get a class-like unit generator from its name. Example: unit_class("peasant") to get a peasant generator At the moment, unit_classes contains also: upgrades, abilities... """ if not self.unit_classes.has_key(s): try: base = self.unit_base_classes[rules.get(s, "class")[0]] except: if rules.get(s, "class") != ["faction"]: warning("no class defined for %s", s) self.unit_classes[s] = None return try: dct = rules.get_dict(s) t = Type(s, (base, ), dct) if base is Upgrade: t = base(s, dct) # factory-prototypes are only for units self.unit_classes[s] = t except: exception("problem with unit_class('%s')", s) self.unit_classes[s] = None return return self.unit_classes[s]
def map_error(line, msg): w = 'error in "%s": %s' % (line, msg) try: open(MAPERROR_PATH, "w").write(w) except: warning("could not write in %s", MAPERROR_PATH) raise MapError(w)
def getStyle(self, name): style = None if name in self.__styles__: if hasattr(type(self.__styles__[name]), "copy"): style = self.__styles__[name].copy() if not style: log.warning(function=self.getStyle, args=name, returns=style) return style
def check_timeout(self): if self._timeout_reference is None: self._timeout_reference = time.time() elif time.time() > self._timeout_reference + config.timeout: for player in self._orders.players_without_orders(): warning("timeout %s", player.login) player.handle_close() # disconnect player break # don't continue! (might disconnect more players)
def get(self, obj, attr, warn_if_not_found=True): result = _Definitions.get(self, obj, attr) if result is None and warn_if_not_found: result = [] # the caller might expect a list if (obj, attr) not in self._style_warnings: self._style_warnings.append((obj, attr)) warning("no value found for %s.%s (check style.txt)", obj, attr) return result
def __init__(self, model, interface=None): self.model = model self.interface = interface for k, v in style.get_dict(model.keyword).items(): if hasattr(self, k): setattr(self, k, v) else: warning("in %s: %s doesn't have any attribute called '%s'", model.keyword, self.__class__.__name__, k)
def unregister(self): try: info("unregistering server...") s = urllib.urlopen(UNREGISTER_URL + "?ip=" + self.ip).read() except: s = "couldn't access to the metaserver" if s: warning("couldn't unregister from the metaserver (%s)", s[:80])
def _delta(self, total, percentage): # (percentage / 100) * total / (self.time_cost / VIRTUAL_TIME_INTERVAL) # (reordered for a better precision) delta = int(total * percentage * VIRTUAL_TIME_INTERVAL / self.time_cost / 100) if delta == 0 and total != 0: warning("insufficient precision (delta: %s total: %s)", delta, total) return delta
def enable(self): apikey = self.pi_dash.config.get(self.namespace, 'apikey') self.location = self.pi_dash.config.get(self.namespace, 'location', 'autoip') if not apikey: log.warning('Wunderground apikey not specified.') return self.disable() self.update_url = UPDATE_URL % {'apikey':apikey, 'location':self.location} super(Plugin, self).enable()
def move_to(self, new_place, x=None, y=None, o=90, exit1=None, exit2=None): if x is None: x = new_place.x y = new_place.y # make sure the object is not a memory if self.is_memory: warning("Will move the real object instead of its memorized version.") self.initial_model.move_to(new_place, x, y, o, exit1, exit2) return # abort if there isn't enough space if new_place is not None and self.collision: if self.place is not None and not self.is_inside: self.world.collision[self.airground_type].remove(self.x, self.y) x, y = new_place.find_free_space(self.airground_type, x, y, new_place is self.place, self.player) if self.place is not None and not self.is_inside: self.world.collision[self.airground_type].add(self.x, self.y) if x is None: if self.place is not None: return else: raise NotEnoughSpaceError # move if self.place is not None and not self.is_inside and self.collision: self.world.collision[self.airground_type].remove(self.x, self.y) self.x = x self.y = y self.o = o if new_place is not self.place: current_place = self.place if current_place is not None: # quit the current place current_place.objects.remove(self) if current_place.__class__.__name__ == "Square": self._previous_square = current_place self.place = new_place if new_place is not None: # enter the new place new_place.objects.append(self) if self.id is None: # new in the world # enter the world self.id = new_place.world.get_next_id() new_place.world.objects[self.id] = self if hasattr(self, "update"): self.place.world.active_objects.append(self) else: # quit the world if self in current_place.world.active_objects: current_place.world.active_objects.remove(self) # reactions if new_place is not None: self.action_target = None if self.place is not None and not self.is_inside and self.collision: self.world.collision[self.airground_type].add(self.x, self.y) if self.speed: self.is_moving = True
def _get_ip_address(self): try: self.ip = urllib.urlopen(WHATISMYIP_URL).read().strip() if not re.match("^[0-9.]{7,40}$", self.ip): self.ip = "" except: self.ip = "" if not self.ip: warning("could not get my IP address from %s", WHATISMYIP_URL)
def display_objects(self): for o in self.interface.dobjets.values(): self.display_object(o) if o.place is None and not o.is_inside \ and not (self.interface.already_asked_to_quit or self.interface.end_loop): warning("%s.place is None", o.type_name) if o.is_memory: warning("(memory)")
def move_to(self, o): self.parent.place = o.place for self.sub_x, self.sub_y in _subzone_name.keys(): self.update_coords() if self.contains(o): self.parent.set_obs_pos() break if not self.contains(o): warning("zoom: couldn't move to object")
def pre_run(self): nb_human_players = len([p for p in self.players if p.login != "ai"]) if nb_human_players > 1: if compatibility_version() != COMPATIBILITY_VERSION: warning("rules.txt or ai.txt has been modified" " after the program started: exit...") sys.exit() send_platform_version_to_metaserver(self.map.get_name(), nb_human_players) self._countdown()
def enable(self): try: self.plex = fetch_plex_instance(self.pi_dash) self.ignores = self.pi_dash.config.get(self.namespace, 'ignores', '') self.ignores = list(filter(None, self.ignores.split('\n'))) super(Plugin, self).enable() except NotFound: log.warning('Plex server not available.') return self.disable()
def int_sqrt(x): r = int(math.sqrt(x)) while r ** 2 > x: warning("sqrt(%s): removing 1 to %s" % (x, r)) r -= 1 while (r + 1) ** 2 < x: warning("sqrt(%s): adding 1 to %s" % (x, r)) r += 1 return r
def findTileWidgetById(self, tId): result = None for tw in self.getTileWidgets(): if tId==tw.tile.id(): result = tw break if not result: log.warning(function=self.findTileWidgetById, args=tId, returns=result) return result
def enable(self): self.username = self.pi_dash.config.get(self.namespace, 'username', '') if not self.username: log.warning('Username not specified.') return self.disable() self.albums_url = ALBUMS_URL % {'username': self.username} self.ignores = self.pi_dash.config.get(self.namespace, 'ignores', '') self.ignores = list(filter(None, self.ignores.split('\n'))) self.last_albums_update = 0 super(Plugin, self).enable()
def __init__(self, name, dct): self.type_name = name self.__name__ = name for k, v in dct.items(): if k == "class": continue if hasattr(self, k) and not callable(getattr(self, k)): setattr(self, k, v) else: warning("in %s: %s doesn't have any attribute called '%s'", name, self.__class__.__name__, k)
def translate_ns(s): s = "%s" % s if sounds.is_text(s): return sounds.get_text(s) if re.match("^[0-9]+$", s) is not None and int(s) >= 1000000: return u"%s" % (int(s) - 1000000) if sounds.get_sound(s): return sounds.get_sound(s) if re.match("^[0-9]+$", s) is not None: warning("this sound may be missing: %s", s) return unicode(s)
def on_wounded(self, attacker_type, attacker_id, level): if self.player == self.interface.player: self.unit_attacked_alert() s = style.get(attacker_type, "attack_hit_level_%s" % level) if s is not None: if s: self.launch_event(random.choice(s)) else: warning("no sound found for: %s %s", attacker_type, "attack_hit_level_%s" % level) if get_fullscreen() and attacker_id in self.interface.dobjets: self.interface.grid_view.display_attack(attacker_id, self)
def _register(self): try: s = urllib.urlopen(REGISTER_URL + "?version=%s&login=%s&ip=%s&port=%s" % (VERSION, self.login, self.ip, options.port)).read() except: s = "couldn't access to the metaserver" if s: warning("couldn't register to the metaserver (%s)", s[:80]) else: info("server registered")
def _process_server_event(self, s): debug("server event: %s", s) cmd_args = s.strip().split(" ") cmd = "srv_" + cmd_args[0] args = cmd_args[1:] if hasattr(self, cmd): return getattr(self, cmd)(args) elif cmd == "srv_all_orders": debug("ignored by ServerMenu: %s", s) elif cmd != "srv_": warning("not recognized by ServerMenu: %s", s)
def _get_ip_address(self): if options.ip: self.ip = options.ip return try: self.ip = urllib2.urlopen(WHATISMYIP_URL, timeout=3).read().strip() if not re.match("^[0-9.]{7,40}$", self.ip): self.ip = "" except: self.ip = "" if not self.ip: warning("could not get my IP address from %s", WHATISMYIP_URL)
def __init__(self, s, v, x, y, priority, limit=0, ambient=False): self.sound = sounds.get_sound(s) self.v = v self.x = x self.y = y self.priority = priority self.ambient = ambient if self.sound is None: warning("this sound may be missing: %s", s) self.has_stopped = True elif psounds.should_be_played(self.sound, limit): self._start()
def _read_ai_to_dict(s, d): s = preprocess(s) name = None for line in s.split("\n"): words = line.split() if not words: continue if words[0] == "def": name = words[1] d[name] = [] elif name is not None: d[name] += [line] else: warning("'def <AI_name>' is missing (check ai.txt)")
def init_dict(self, target): target.type_name = self.type_name for k, v in self.dct.items(): if k == "class": continue if (hasattr(self.cls, k) or k.endswith("_bonus") and hasattr(self.cls, k[:-6]) ) and not callable(getattr(self.cls, k, None)): if k == "cost": normalize_cost_or_resources(v) setattr(target, k, v) elif target is self: warning("in %s: %s doesn't have any attribute called '%s'", self.type_name, self.cls.__name__, k)