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 cmd_order(self, args): self.group_had_enough_mana = False try: order_id = self.world.get_next_order_id() # used when several workers must create the same construction site forget_previous = args[0] == "0" del args[0] imperative = args[0] == "1" del args[0] if args[0] == "reset_group": self._reset_group(args[1]) return for u in self.group: if u.group and u.group != self.group: u.group.remove(u) u.group = None if u.player in self.allied_control: # in case the unit has died or has been converted try: if args[0] == "default": u.take_default_order(args[1], forget_previous, imperative, order_id) else: u.take_order(args, forget_previous, imperative, order_id) except: exception("problem with order: %s" % args) except: exception("problem with order: %s" % args)
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 cmd_order(self, args): self.group_had_enough_mana = False try: order_id = self.world.get_next_order_id( ) # used when several workers must create the same construction site forget_previous = args[0] == "0" del args[0] imperative = args[0] == "1" del args[0] if args[0] == "reset_group": self._reset_group(args[1]) return for u in self.group: if u.group and u.group != self.group: u.group.remove(u) u.group = None if u.player in self.allied_control: # in case the unit has died or has been converted try: if args[0] == "default": u.take_default_order(args[1], forget_previous, imperative, order_id) else: u.take_order(args, forget_previous, imperative, order_id) except: exception("problem with order: %s" % args) except: exception("problem with order: %s" % args)
def update(self): # normal updates for p in self.players[:]: if p in self.players: try: p.update() except: exception("") for o in self.active_objects[:]: # much faster way to check if "o in self.active_objects": if o.place is not None: try: o.update() except: exception("") # slow updates (called every second) if self.time >= self._previous_slow_update + 1000: for o in self.active_objects[:]: # much faster way to check if "o in self.active_objects": if o.place is not None: try: o.slow_update() except: exception("") for p in self.players[:]: if p in self.players: try: p.slow_update() except: exception("") self._previous_slow_update += 1000 # signal the end of the updates for this time self.time += VIRTUAL_TIME_INTERVAL for p in self.players[:]: if p.is_human(): p.ready = False try: def _copy(l): return set(copy.copy(o) for o in l) collision_debug = None # collision_debug = copy.deepcopy(self.collision) if p.is_local_human(): # avoid unnecessary copies if p.cheatmode: observed_before_squares = self.squares else: observed_before_squares = p.observed_before_squares p.push("voila", self.time, _copy(p.memory), _copy(p.perception), p.observed_squares.keys(), observed_before_squares, collision_debug) except: exception("") # if no "true" player is playing any more, end the game if not self.true_playing_players: for p in self.players: p.quit_game()
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 attribute_bgsize(self, value): try: bgsize = value.lower() self.bgsize = bgsize if bgsize == 'fit' else QtCore.QSize( *map(int, bgsize.split(','))) except: log.exception('Invalid background size: %s', value)
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 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 _put_building_site(self, type, target): place, x, y, _id = target.place, target.x, target.y, target.id # remember before deletion if not hasattr(place, "place"): # target is a square place = target if not (getattr(target, "is_an_exit", False) or type.is_buildable_anywhere): target.delete() # remove the meadow replaced by the building remember_land = True else: remember_land = False site = BuildingSite(self.player, place, x, y, type) if remember_land: site.building_land = target if getattr(target, "is_an_exit", False): site.block(target) # update the orders of the workers order = self.orders[0] for unit in self.player.units: if unit is self: continue for n in range(len(unit.orders)): try: if unit.orders[n] == order: # why not before: unit.orders[n].cancel() ? unit.orders[n] = BuildPhaseTwoOrder(unit, [site.id]) # the other peasants help the first one unit.orders[n].on_queued() except: # if order is not a string? exception("couldn't check unit order") self.orders[0] = BuildPhaseTwoOrder(self, [site.id]) self.orders[0].on_queued()
def _menu(self, strict=False): menu = [] try: # TODO: remove this "try... except" when rules.txt checking is implemented for order_class in get_orders_list(): menu.extend(order_class.menu(self, strict=strict)) except: exception("problem with %s.menu() of %s", order_class, self.type_name) return menu
def attribute_bgpos(self, value): try: x, y = value.lower().split(',') x = x if x in ['left', 'center', 'right'] else int(x) y = y if y in ['top', 'center', 'bottom'] else int(y) self.bgpos = (x, y) except: log.exception('Invalid background position: %s', value)
def _menu(self, strict=False): menu = [] try: # XXX remove this "try... except" when rules.txt checking is implemented for order_class in get_orders_list(): menu.extend(order_class.menu(self, strict=strict)) except: exception("problem with %s.menu() of %s", order_class, self.type_name) return menu
def loop(self): while (self.__dict__): # cf clean() if not self._command_queue.empty(): player, order = self._command_queue.get() try: player.execute_command(order) except: exception("") else: time.sleep(.01)
def speak(text): assert isinstance(text, unicode) global _tts_previous_start_time if not is_available: return with _lock: try: _tts.Speak(text, pyTTS.tts_async, pyTTS.tts_purge_before_speak) except: exception("error during tts_speak('%s'): back to recorded speech", text) _tts_previous_start_time = time.time()
def loop(self): while(self.__dict__): # cf clean() if not self._command_queue.empty(): player, order = self._command_queue.get() try: player.execute_command(order) except: exception("") else: time.sleep(.01)
def handle_error(self): try: debug("Server.handle_error %s", sys.exc_info()[0]) except: pass if sys.exc_info()[0] in [SystemExit, KeyboardInterrupt]: sys.exit() else: try: exception("Server.handle_error") except: pass
def main(): try: for i, message in enumerate(streamer.iter_stream(STREAM_URL)): handle_message(message) if i and i % 100 == 0: log.info('Processed %d messages', i) except KeyboardInterrupt: log.info('Bye bye!') except Exception, e: log.exception('Error handling message: %s', e) log.warn('Exiting...') return 1
def main(): try: try: init_media() revision_checker.start_if_needed() Application().main() except SystemExit: raise except: exception("error") finally: close_media()
def action_fly_to_remote_target(self): dmax = int_distance(self.x, self.y, self.action_target.x, self.action_target.y) self.o = int_angle(self.x, self.y, self.action_target.x, self.action_target.y) # turn toward the goal self._d = self.speed * VIRTUAL_TIME_INTERVAL / 1000 # used by _future_coords and _heuristic_value x, y = self._future_coords(0, dmax) if not self.place.contains(x, y): try: new_place = self.world.get_place_from_xy(x, y) self.move_to(new_place, x, y, self.o) except: exception("problem when flying to a new square") else: self.move_to(self.place, x, y)
def _loop(self): self._must_loop = True while(self._must_loop): if not self._command_queue.empty(): player, order = self._command_queue.get() try: if player is None: order() else: player.execute_command(order) except: exception("") else: time.sleep(.001)
def _loop(self): self._must_loop = True while (self._must_loop): if not self._command_queue.empty(): player, order = self._command_queue.get() try: if player is None: order() else: player.execute_command(order) except: exception("") else: time.sleep(.001)
def main(): try: init_media() revision_checker.start_if_needed() if "connect_localhost" in sys.argv: connect_and_play() else: main_menu() except SystemExit: raise except: exception("error") finally: close_media()
def start_server(parameters=sys.argv, is_standalone=True): try: server = Server(parameters, is_standalone) server.startup() finally: try: info("closing server...") if hasattr(server, "ticker"): server.ticker.cancel() server.unregister() # make sure channels are closed (useful?) for c in server.clients: c.close() server.close() except: exception("couldn't close the server")
def unpack(self, map_string): self._original_map_string = map_string try: self.mapfile, content = map_string.split("***", 1) if self.mapfile != "zip": self.map_string = base64.b64decode(content) open(os.path.join(TMP_PATH, "recent_map.txt"), "wb").write(self.map_string) else: zf = os.path.join(TMP_PATH, "recent_map.tmp") open(zf, "wb").write(base64.b64decode(content)) zd = os.path.join(TMP_PATH, "recent_map") shutil.rmtree(zd, True) zipdir.unzipdir(zf, zd) self.mapfile = zd os.remove(zf) except: exception("unpacking problem")
def connect_and_play(host="127.0.0.1", port=options.port, auto=False): try: server = ConnectionToServer(host, port) ServerMenu(server, auto=auto).loop() server.close() # without this, the server isn't closed after a game except UnreachableServerError: voice.alert(mp.SERVER_UNREACHABLE) except WrongServerError: voice.alert(mp.UNEXPECTED_REPLY + [compatibility_version()]) except CompatibilityOrLoginError: voice.alert(mp.CONNECTION_REJECTED + [compatibility_version()] + mp.OR_LOGIN_REJECTED) except ConnectionAbortedError: voice.alert(mp.CONNECTION_INTERRUPTED) except SystemExit: raise except: voice.alert(mp.ERROR_DURING_CONNECTION) exception("error during connection to server")
def save(self): f = open(SAVE_PATH, "w") i = stats.Stats(None, None)._get_weak_user_id() f.write("%s\n" % i) self.world.remove_links_for_savegame() self._rules = rules self._ai = definitions._ai self._style = style if self.record_replay: self._replay_file.flush() os.fsync(self._replay_file.fileno()) # just to be sure self._replay_file_content = open(self._replay_file.name).read() try: pickle.dump(self, f) voice.info(mp.OK) except: exception("save game failed") voice.alert(mp.BEEP) self.world.restore_links_for_savegame()
def connect_and_play(host="127.0.0.1", port=config.port): try: server = ConnectionToServer(host, port) ServerMenu(server).loop() server.close() # without this, the server isn't closed after a game except UnreachableServerError: # "failure: the server unreachable. The server is closed or behind a firewall or behind a router." voice.alert([4081]) except WrongServerError: # "failure: unexpected reply from the server. The server is not a SoundRTS server" (version) voice.alert([4082, compatibility_version()]) except CompatibilityOrLoginError: # "failure: connexion rejected the server. The server is not a SoundRTS server" (version) # "or your login has been rejected" voice.alert([4083, compatibility_version(), 4084]) except ConnectionAbortedError: voice.alert([4102]) # connection aborted except SystemExit: raise except: voice.alert([4085]) # "error during connexion to server" exception("error during connection to server")
def play(self): if self.never_played: self.attack_squares = [self.world.grid[name] for name in self.world.starting_squares] if self.units[0].place in self.attack_squares: # may not happen if additional units in other squares self.attack_squares.remove(self.units[0].place) self.my_base = self.units[0].place worldrandom.shuffle(self.attack_squares) self.never_played = False self.idle_peasants_gather() if self.constant_attacks: self.try_constant_attacks() if self.research: self.idle_buildings_research() if self.raise_dead: self.raise_dead_units() if self.send_soldiers_to_base and self.my_base is not None: if self.send_timer == 0: self.send_soldiers_to_my_base() self.send_timer = 40 else: self.send_timer -= 1 if self.AI_timer == 0: if not self.is_building_or_repairing: # XXX: not perfect (one building at a time; problems if peasants destroyed) but the AI must not be too good try: if not self.build_a_warehouse_if_useful(): self._play() except RuntimeError: # XXX: maximum recursion (for example if no TownHall and no Peasant) warning("recursion error with %s; current ai.txt line is: %s", self.AI_type, self._plan[self._line_nb]) if VERSION[-4:] == "-dev": exception("") self._line_nb += 1 # go to next step; useful? self.AI_timer = 100 # probably not, so make a big pause # else: # self.send_some_peasants_to_building_site() # Don't know if it will be needed, # But sometimes AI forget the building being constructed else: self.AI_timer -= 1
def restore_game(self): n = SAVE_PATH if not os.path.exists(n): voice.alert([1029]) # hostile sound return f = open(n) try: i = int(stats.Stats(None, None)._get_weak_user_id()) j = int(f.readline()) except: i = 0 j = "error" if i == j: try: game_session = pickle.load(f) except: exception("cannot load savegame file") voice.alert([1029]) # hostile sound return game_session.run_on() else: warning("savegame file is not from this machine") voice.alert([1029]) # hostile sound
def handle_message_with_entities(message): assert message['entities'] for url_info in message['entities']['urls']: url = url_info['expanded_url'] log.info('Found URL: %s', url) try: canonical_url = urlwork.canonicalize(url) except requests.TooManyRedirects: log.error('Too many redirects: %s', url) except Exception, e: log.exception('Canonicalization error: %s', e) log.error('URL info: %r', url_info) else: if canonical_url != url: log.info('=> %s', canonical_url) source = message['user']['id'] source_url = make_tweet_url(message) count = db.add(canonical_url, source, source_url) if count >= int(os.environ.get('THRESHOLD', 5)): log.info('URL %s seen %d times!', canonical_url, count) handle_thresholded_url(canonical_url)
def ext_title(self): try: return self.title + mp.AT + self.place.title except: exception("problem with %s.ext_title", self.type_name)
def ext_title(self): try: return self.title + [107] + self.place.title except: exception("problem with %s.ext_title", self.type_name)
def attribute_bgfade(self, value): try: self.bgfade = float(value) except: log.exception('Invalid bgfade value: %s', value)
def wrap(*args, **kwargs): try: return func(*args, **kwargs) except Exception as err: log.exception(err)
def update(self): chrono.start("update") # normal updates self._update_terrain() self._update_buckets() self._update_cloaking() self._update_detection() for p in self.players[:]: if p in self.players: try: p.update() except: exception("") for o in self.active_objects[:]: # much faster way to check if "o in self.active_objects": if o.place is not None: try: o.update() except: exception("") # slow updates (called every second) if self.time >= self._previous_slow_update + 1000: for o in self.active_objects[:]: # much faster way to check if "o in self.active_objects": if o.place is not None: try: o.slow_update() except: exception("") for p in self.players[:]: if p in self.players: try: p.slow_update() except: exception("") self._previous_slow_update += 1000 # remove from perception the objects deleted during this turn for p in self.players: for o in p.perception.copy(): if o.place is None: p.perception.remove(o) chrono.stop("update") self._record_sync_debug_info() # signal the end of the updates for this time self.time += VIRTUAL_TIME_INTERVAL for p in self.players[:]: try: def _copy(l): return set(copy.copy(o) for o in l) collision_debug = None # collision_debug = copy.deepcopy(self.collision) if p.is_local_human(): # avoid unnecessary copies if p.cheatmode: observed_before_squares = self.squares else: observed_before_squares = p.observed_before_squares p.push("voila", self.time, _copy(p.memory), _copy(p.perception), p.observed_squares, observed_before_squares, collision_debug) except: exception("") # if no "true" player is playing any more, end the game if not self.true_playing_players: for p in self.players: p.quit_game()
def update_perception(self): try: for p in self.world.players: p.update_perception_of_object(self) except: exception("%s", self.type_name)
def send_error_to_metaserver(error_msg): try: params = urllib.urlencode({"method": "add", "msg": error_msg}) urllib.urlopen(METASERVER_URL + "errors.php?%s" % params).read() except: exception("could not send error message to web server")