def show(self): self._files, self._maps_display = SavegameManager.get_maps() self._gui.distributeInitialData({ 'maplist': self._maps_display, 'playerlimit': range(2, MULTIPLAYER.MAX_PLAYER_COUNT) }) if self._maps_display: # select first entry self._gui.distributeData({'maplist': 0, 'playerlimit': 0}) self._update_infos() self._gui.findChild(name="maplist").mapEvents( {'maplist/action': self._update_infos}) gamenametextfield = self._gui.findChild(name='gamename') def gamename_clicked(): if gamenametextfield.text == 'Unnamed Game': gamenametextfield.text = "" gamenametextfield.capture(gamename_clicked, event_name='mouseClicked') self._gui.show()
def _start_map(map_name, is_scenario=False): """Start a map specified by user @return: bool, whether loading succeded""" maps = SavegameManager.get_scenarios( ) if is_scenario else SavegameManager.get_maps() map_file = None for i in xrange(0, len(maps[1])): # exact match if maps[1][i] == map_name: map_file = maps[0][i] break # check for partial match if maps[1][i].startswith(map_name): if map_file is not None: # multiple matches, collect all for output map_file += u'\n' + maps[0][i] else: map_file = maps[0][i] if map_file is None: print _("Error: Cannot find map \"%s\".") % map_name return False if len(map_file.splitlines()) > 1: print _("Error: Found multiple matches: ") for match in map_file.splitlines(): print os.path.basename(match) return False load_game(map_file, is_scenario) return True
def _start_map( map_name, ai_players=0, is_scenario=False, pirate_enabled=True, trader_enabled=True, force_player_id=None, is_map=False, ): """Start a map specified by user @param map_name: name of map or path to map @return: bool, whether loading succeeded""" if is_scenario: savegames = SavegameManager.get_available_scenarios(locales=True) else: savegames = SavegameManager.get_maps() map_file = _find_matching_map(map_name, savegames) if not map_file: return False options = StartGameOptions.create_start_singleplayer( map_file, is_scenario, ai_players, trader_enabled, pirate_enabled, force_player_id, is_map ) start_singleplayer(options) return True
def _start_map(map_name, ai_players=0, human_ai=False, is_scenario=False, campaign=None, pirate_enabled=True, trader_enabled=True, force_player_id=None): """Start a map specified by user @param map_name: name of map or path to map @return: bool, whether loading succeded""" # check for exact/partial matches in map list first maps = SavegameManager.get_available_scenarios() if is_scenario else SavegameManager.get_maps() map_file = None for i in xrange(0, len(maps[1])): # exact match if maps[1][i] == map_name: map_file = maps[0][i] break # check for partial match if maps[1][i].startswith(map_name): if map_file is not None: # multiple matches, collect all for output map_file += u'\n' + maps[0][i] else: map_file = maps[0][i] if map_file is None: # not a map name, check for path to file or fail if os.path.exists(map_name): map_file = map_name else: #xgettext:python-format print u"Error: Cannot find map '{name}'.".format(name=map_name) return False if len(map_file.splitlines()) > 1: print "Error: Found multiple matches:" for match in map_file.splitlines(): print os.path.basename(match) return False load_game(ai_players, human_ai, map_file, is_scenario, campaign=campaign, trader_enabled=trader_enabled, pirate_enabled=pirate_enabled, force_player_id=force_player_id) return True
def show(self): self._files, self._maps_display = SavegameManager.get_maps() self._gui.distributeInitialData({ 'maplist': self._maps_display, 'playerlimit': range(2, MULTIPLAYER.MAX_PLAYER_COUNT) }) if self._maps_display: # select first entry self._gui.distributeData({ 'maplist': 0, 'playerlimit': 0 }) self._update_infos() self._gui.findChild(name="maplist").mapEvents({ 'maplist/action': self._update_infos }) gamenametextfield = self._gui.findChild(name='gamename') def gamename_clicked(): if gamenametextfield.text == 'Unnamed Game': gamenametextfield.text = "" gamenametextfield.capture(gamename_clicked, event_name='mouseClicked') self._gui.show()
def editor_load_map(self): """Show a dialog for the user to select a map to edit.""" old_current = self._switch_current_widget('editor_select_map') self.current.show() map_files, map_file_display = SavegameManager.get_maps() self.current.distributeInitialData({'maplist': map_file_display}) bind = { OkButton.DEFAULT_NAME : True, CancelButton.DEFAULT_NAME : False, } retval = self.show_dialog(self.current, bind) if not retval: # Dialog cancelled self.current = old_current return selected_map_index = self.current.collectData('maplist') if selected_map_index == -1: # No map selected yet => select first available one self.current.distributeData({'maplist': 0}) self.current = old_current self.show_loading_screen() horizons.main.edit_map(map_file_display[selected_map_index])
def __show_create_game(self): """Shows the interface for creating a multiplayer game""" event_map = { 'cancel' : self.show_multi, 'create' : self.__create_game } self.__apply_new_nickname() self._switch_current_widget('multiplayer_creategame', center=True, event_map=event_map, hide_old=True) self.current.files, self.maps_display = SavegameManager.get_maps() self.current.distributeInitialData({ 'maplist' : self.maps_display, 'playerlimit' : range(2, MULTIPLAYER.MAX_PLAYER_COUNT) }) def _update_infos(): mapindex = self.current.collectData('maplist') mapfile = self.current.files[mapindex] number_of_players = SavegameManager.get_recommended_number_of_players( mapfile ) #xgettext:python-format self.current.findChild(name="recommended_number_of_players_lbl").text = \ _("Recommended number of players: {number}").format(number=number_of_players) if len(self.maps_display) > 0: # select first entry self.current.distributeData({ 'maplist' : 0, 'playerlimit' : 0 }) _update_infos() self.current.show() self.on_escape = event_map['cancel']
def _start_map(map_name, is_scenario = False): """Start a map specified by user @return: bool, whether loading succeded""" maps = SavegameManager.get_scenarios() if is_scenario else SavegameManager.get_maps() map_file = None for i in xrange(0, len(maps[1])): # exact match if maps[1][i] == map_name: map_file = maps[0][i] break # check for partial match if maps[1][i].startswith(map_name): if map_file is not None: # multiple matches, collect all for output map_file += u'\n' + maps[0][i] else: map_file = maps[0][i] if map_file is None: print _("Error: Cannot find map \"%s\".") % map_name return False if len(map_file.splitlines()) > 1: print _("Error: Found multiple matches: ") for match in map_file.splitlines(): print os.path.basename(match) return False load_game(map_file, is_scenario) return True
def _start_dev_map(ai_players, human_ai, force_player_id): # start the development map for m in SavegameManager.get_maps()[0]: if 'development' in m: break load_game(ai_players, human_ai, m, force_player_id=force_player_id) return True
def editor_load_map(self): """Show a dialog for the user to select a map to edit.""" old_current = self._switch_current_widget('editor_select_map') self.current.show() map_files, map_file_display = SavegameManager.get_maps() self.current.distributeInitialData({'maplist': map_file_display}) bind = { OkButton.DEFAULT_NAME: True, CancelButton.DEFAULT_NAME: False, } retval = self.show_dialog(self.current, bind) if not retval: # Dialog cancelled self.current = old_current return False selected_map_index = self.current.collectData('maplist') if selected_map_index == -1: # No map selected yet => select first available one self.current.distributeData({'maplist': 0}) self.current = old_current self.show_loading_screen() horizons.main.edit_map(map_files[selected_map_index]) return True
def edit_map(map_name): """ Start editing the map file specified by the name. @param map_name: name of map or path to map @return: bool, whether loading succeeded """ return _edit_map(_find_map(map_name, SavegameManager.get_maps()))
def edit_map(map_name): """ Start editing the map file specified by the name. @param map_name: name of map or path to map @return: bool, whether loading succeeded """ return _edit_map(_find_matching_map(map_name, SavegameManager.get_maps()))
def prepare(self): if self._mode == 'load': self._map_files, self._map_file_display = SavegameManager.get_saves( ) if not self._map_files: self._windows.open_popup( T("No saved games"), T("There are no saved games to load.")) return False elif self._mode == 'save': self._map_files, self._map_file_display = SavegameManager.get_regular_saves( ) elif self._mode == 'editor-save': self._map_files, self._map_file_display = SavegameManager.get_maps( ) self._gui.distributeInitialData( {'savegamelist': self._map_file_display}) if self._mode == 'load': self._gui.distributeData({'savegamelist': 0}) self._cb = self._create_show_savegame_details(self._gui, self._map_files, 'savegamelist') if self._mode in ('save', 'editor-save'): def selected_changed(): """Fills in the name of the savegame in the textbox when selected in the list""" if self._gui.collectData( 'savegamelist' ) == -1: # set blank if nothing is selected self._gui.findChild(name="savegamefile").text = u"" else: savegamefile = self._map_file_display[ self._gui.collectData('savegamelist')] self._gui.distributeData({'savegamefile': savegamefile}) self._cb = Callback.ChainedCallbacks(self._cb, selected_changed) self._cb() # Refresh data on start self._gui.mapEvents({'savegamelist/action': self._cb}) self._gui.findChild(name="savegamelist").capture( self._cb, event_name="keyPressed") self._gui.findChild(name="savegamelist").capture( self.check_double_click, event_name="mousePressed") self.return_events = { OkButton.DEFAULT_NAME: True, CancelButton.DEFAULT_NAME: False, DeleteButton.DEFAULT_NAME: 'delete' } if self._mode in ('save', 'editor-save'): self.return_events['savegamefile'] = True
def show(self): self._files, maps_display = SavegameManager.get_maps() self._gui.distributeInitialData({'maplist': maps_display}) self._gui.mapEvents({ 'maplist/action': self._update_map_infos, }) if maps_display: # select first entry self._gui.distributeData({'maplist': 0}) self._update_map_infos() self._gui.findChild(name='game_settings_box').addChild(self._game_settings.get_widget()) self._game_settings.show() self._aidata.show()
def _start_map(map_name, ai_players=0, human_ai=False, is_scenario=False, campaign=None, pirate_enabled=True, trader_enabled=True, force_player_id=None): """Start a map specified by user @param map_name: name of map or path to map @return: bool, whether loading succeded""" if is_scenario: savegames = SavegameManager.get_available_scenarios(locales=True) else: savegames = SavegameManager.get_maps() map_file = _find_matching_map(map_name, savegames) if not map_file: return False load_game(ai_players, human_ai, map_file, is_scenario, campaign=campaign, trader_enabled=trader_enabled, pirate_enabled=pirate_enabled, force_player_id=force_player_id) return True
def _start_map(map_name, ai_players=0, human_ai=False, is_scenario=False, campaign=None, pirate_enabled=True, trader_enabled=True, force_player_id=None): """Start a map specified by user @param map_name: name of map or path to map @return: bool, whether loading succeded""" maps = SavegameManager.get_available_scenarios(locales=True) if is_scenario else SavegameManager.get_maps() map_file = None # get system's language game_language = fife.get_locale() # now we have "_en.yaml" which is set to language_extension variable language_extension = '_' + game_language + '.' + SavegameManager.scenario_extension # check for exact/partial matches in map list first for i in xrange(0, len(maps[1])): # exact match if maps[1][i] == map_name: map_file = maps[0][i] break # we want to match when map_name is like "tutorial" not "tutorial_en" if maps[1][i] == map_name + language_extension: map_file = maps[0][i] break # check for partial match if maps[1][i].startswith(map_name): if map_file is not None: # multiple matches, collect all for output map_file += u'\n' + maps[0][i] else: map_file = maps[0][i] if map_file is None: # not a map name, check for path to file or fail if os.path.exists(map_name): map_file = map_name else: #xgettext:python-format print u"Error: Cannot find map '{name}'.".format(name=map_name) return False if len(map_file.splitlines()) > 1: print "Error: Found multiple matches:" for match in map_file.splitlines(): print os.path.basename(match) return False load_game(ai_players, human_ai, map_file, is_scenario, campaign=campaign, trader_enabled=trader_enabled, pirate_enabled=pirate_enabled, force_player_id=force_player_id) return True
def show(self): self._files, self._maps_display = SavegameManager.get_maps() self._gui.distributeInitialData({ 'maplist': self._maps_display, 'playerlimit': range(2, MULTIPLAYER.MAX_PLAYER_COUNT) }) if self._maps_display: # select first entry self._gui.distributeData({'maplist': 0, 'playerlimit': 0}) self._update_infos() self._gui.findChild(name="maplist").mapEvents( {'maplist/action': self._update_infos}) self._gui.show()
def _start_map(map_name, ai_players=0, is_scenario=False, pirate_enabled=True, trader_enabled=True, force_player_id=None, is_map=False): """Start a map specified by user @param map_name: name of map or path to map @return: bool, whether loading succeeded""" if is_scenario: map_file = _find_scenario(map_name, SavegameManager.get_available_scenarios(locales=True)) else: map_file = _find_map(map_name, SavegameManager.get_maps()) if not map_file: return False options = StartGameOptions.create_start_singleplayer(map_file, is_scenario, ai_players, trader_enabled, pirate_enabled, force_player_id, is_map) start_singleplayer(options) return True
def __show_create_game(self): """Shows the interface for creating a multiplayer game""" event_map = {'cancel': self.show_multi, 'create': self.__create_game} self.__apply_new_nickname() self.__apply_new_color() self._switch_current_widget('multiplayer_creategame', center=True, event_map=event_map, hide_old=True) self.current.files, self.maps_display = SavegameManager.get_maps() self.current.distributeInitialData({ 'maplist': self.maps_display, 'playerlimit': range(2, MULTIPLAYER.MAX_PLAYER_COUNT) }) def _update_infos(): mapindex = self.current.collectData('maplist') mapfile = self.current.files[mapindex] number_of_players = SavegameManager.get_recommended_number_of_players( mapfile) #xgettext:python-format self.current.findChild(name="recommended_number_of_players_lbl").text = \ _("Recommended number of players: {number}").format(number=number_of_players) if self.maps_display: # select first entry self.current.distributeData({'maplist': 0, 'playerlimit': 0}) _update_infos() self.current.findChild(name="maplist").mapEvents( {'maplist/action': _update_infos}) self.current.findChild(name="password").text = u"" gamename_textfield = self.current.findChild(name="gamename") def clear_gamename_textfield(): gamename_textfield.text = u"" gamename_textfield.capture(clear_gamename_textfield, 'mouseReleased', 'default') self.current.show() self.on_escape = event_map['cancel']
def show(self): self._files, self._maps_display = SavegameManager.get_maps() self._gui.distributeInitialData({ 'maplist': self._maps_display, 'playerlimit': range(2, MULTIPLAYER.MAX_PLAYER_COUNT) }) if self._maps_display: # select first entry self._gui.distributeData({ 'maplist': 0, 'playerlimit': 0 }) self._update_infos() self._gui.findChild(name="maplist").mapEvents({ 'maplist/action': self._update_infos }) self._gui.show()
def __show_create_game(self): """Shows the interface for creating a multiplayer game""" event_map = { 'cancel' : self.show_multi, 'create' : self.__create_game } self.__apply_new_nickname() self.__apply_new_color() self.mainmenu._switch_current_widget('multiplayer_creategame', center=True, event_map=event_map, hide_old=True) self.current = self.mainmenu.current self.current.files, self.maps_display = SavegameManager.get_maps() self.current.distributeInitialData({ 'maplist' : self.maps_display, 'playerlimit' : range(2, MULTIPLAYER.MAX_PLAYER_COUNT) }) def _update_infos(): mapindex = self.current.collectData('maplist') mapfile = self.current.files[mapindex] number_of_players = SavegameManager.get_recommended_number_of_players(mapfile) #xgettext:python-format self.current.findChild(name="recommended_number_of_players_lbl").text = \ _("Recommended number of players: {number}").format(number=number_of_players) if self.maps_display: # select first entry self.current.distributeData({ 'maplist' : 0, 'playerlimit' : 0 }) _update_infos() self.current.findChild(name="maplist").mapEvents({ 'maplist/action': _update_infos }) self.current.findChild(name="password").text = u"" gamename_textfield = self.current.findChild(name="gamename") def clear_gamename_textfield(): gamename_textfield.text = u"" gamename_textfield.capture(clear_gamename_textfield, 'mouseReleased', 'default') self.current.show() self.mainmenu.on_escape = event_map['cancel']
def __show_create_game(self): """Shows the interface for creating a multiplayer game""" event_map = {"cancel": self.show_multi, "create": self.__create_game} self.__apply_new_nickname() self._switch_current_widget("multiplayer_creategame", center=True, event_map=event_map, hide_old=True) self.current.files, self.maps_display = SavegameManager.get_maps() self.current.distributeInitialData( {"maplist": self.maps_display, "playerlimit": range(2, MULTIPLAYER.MAX_PLAYER_COUNT)} ) def _update_infos(): mapindex = self.current.collectData("maplist") mapfile = self.current.files[mapindex] number_of_players = SavegameManager.get_recommended_number_of_players(mapfile) # xgettext:python-format self.current.findChild(name="recommended_number_of_players_lbl").text = _( "Recommended number of players: {number}" ).format(number=number_of_players) if len(self.maps_display) > 0: # select first entry self.current.distributeData({"maplist": 0, "playerlimit": 0}) _update_infos() self.current.findChild(name="maplist").mapEvents( { "maplist/action": _update_infos, "maplist/mouseWheelMovedUp": _update_infos, "maplist/mouseWheelMovedDown": _update_infos, } ) gamename_textfield = self.current.findChild(name="gamename") def clear_gamename_textfield(): gamename_textfield.text = u"" gamename_textfield.capture(clear_gamename_textfield, "mouseReleased", "default") self.current.show() self.on_escape = event_map["cancel"]
def prepare(self): if self._mode == 'load': self._map_files, self._map_file_display = SavegameManager.get_saves() if not self._map_files: self._windows.show_popup(_("No saved games"), _("There are no saved games to load.")) return False elif self._mode == 'save': self._map_files, self._map_file_display = SavegameManager.get_regular_saves() elif self._mode == 'editor-save': self._map_files, self._map_file_display = SavegameManager.get_maps() self._gui.distributeInitialData({'savegamelist': self._map_file_display}) if self._mode == 'load': self._gui.distributeData({'savegamelist': 0}) self._cb = self._create_show_savegame_details(self._gui, self._map_files, 'savegamelist') if self._mode in ('save', 'editor-save'): def selected_changed(): """Fills in the name of the savegame in the textbox when selected in the list""" if self._gui.collectData('savegamelist') == -1: # set blank if nothing is selected self._gui.findChild(name="savegamefile").text = u"" else: savegamefile = self._map_file_display[self._gui.collectData('savegamelist')] self._gui.distributeData({'savegamefile': savegamefile}) self._cb = Callback.ChainedCallbacks(self._cb, selected_changed) self._cb() # Refresh data on start self._gui.mapEvents({'savegamelist/action': self._cb}) self._gui.findChild(name="savegamelist").capture(self._cb, event_name="keyPressed") self._gui.findChild(name="savegamelist").capture(self.check_double_click, event_name="mousePressed") self.return_events = { OkButton.DEFAULT_NAME : True, CancelButton.DEFAULT_NAME: False, DeleteButton.DEFAULT_NAME: 'delete' } if self._mode in ('save', 'editor-save'): self.return_events['savegamefile'] = True
def _start_dev_map(ai_players, human_ai): # start the development map (it's the first one) first_map = SavegameManager.get_maps()[0][1] load_game(ai_players, human_ai, first_map) return True
def start(_command_line_arguments): """Starts the horizons. Will drop you to the main menu. @param _command_line_arguments: options object from optparse.OptionParser. see run_uh.py. """ global debug, preloading, command_line_arguments command_line_arguments = _command_line_arguments # NOTE: globals are designwise the same thing as singletons. they don't look pretty. # here, we only have globals that are either trivial, or only one instance may ever exist. from engine import Fife # handle commandline globals debug = command_line_arguments.debug if command_line_arguments.restore_settings: # just delete the file, Settings ctor will create a new one os.remove( PATHS.USER_CONFIG_FILE ) if command_line_arguments.mp_master: try: mpieces = command_line_arguments.mp_master.partition(':') NETWORK.SERVER_ADDRESS = mpieces[0] # only change port if port is specified if mpieces[2]: NETWORK.SERVER_PORT = parse_port(mpieces[2]) except ValueError: print "Error: Invalid syntax in --mp-master commandline option. Port must be a number between 1 and 65535." return False # init fife before mp_bind is parsed, since it's needed there horizons.globals.fife = Fife() if command_line_arguments.generate_minimap: # we've been called as subprocess to generate a map preview from horizons.gui.modules.singleplayermenu import generate_random_minimap generate_random_minimap( * json.loads( command_line_arguments.generate_minimap ) ) sys.exit(0) if debug: # also True if a specific module is logged (but not 'fife') setup_debug_mode(command_line_arguments) if horizons.globals.fife.get_uh_setting("DebugLog"): set_debug_log(True, startup=True) if command_line_arguments.mp_bind: try: mpieces = command_line_arguments.mp_bind.partition(':') NETWORK.CLIENT_ADDRESS = mpieces[0] horizons.globals.fife.set_uh_setting("NetworkPort", parse_port(mpieces[2])) except ValueError: print "Error: Invalid syntax in --mp-bind commandline option. Port must be a number between 1 and 65535." return False setup_AI_settings(command_line_arguments) # set MAX_TICKS if command_line_arguments.max_ticks: GAME.MAX_TICKS = command_line_arguments.max_ticks preload_lock = threading.Lock() atlas_loading_thread = None atlas_loading_thread = AtlasLoadingThread(preload_lock, command_line_arguments) atlas_loading_thread.start() atlas_loading_thread.join() # init game parts if not setup_gui_logger(command_line_arguments): return False # GUI tests always run with sound disabled and SDL (so they can run under xvfb). # Needs to be done before engine is initialized. if command_line_arguments.gui_test: horizons.globals.fife.engine.getSettings().setRenderBackend('SDL') horizons.globals.fife.set_fife_setting('PlaySounds', False) ExtScheduler.create_instance(horizons.globals.fife.pump) horizons.globals.fife.init() if not VERSION.IS_DEV_VERSION and horizons.globals.fife.get_uh_setting('AtlasesEnabled'): GFX.USE_ATLASES = True PATHS.DB_FILES = PATHS.DB_FILES + (PATHS.ATLAS_DB_PATH, ) horizons.globals.db = _create_main_db() _modules.gui = Gui() SavegameManager.init() horizons.globals.fife.init_animation_loader(GFX.USE_ATLASES) from horizons.entities import Entities Entities.load(horizons.globals.db, load_now=False) # create all references # for preloading game data while in main screen preload_thread = threading.Thread(target=preload_game_data, args=(preload_lock,)) preloading = (preload_thread, preload_lock) # Singleplayer seed needs to be changed before startup. if command_line_arguments.sp_seed: SINGLEPLAYER.SEED = command_line_arguments.sp_seed SINGLEPLAYER.FREEZE_PROTECTION = command_line_arguments.freeze_protection # start something according to commandline parameters startup_worked = True if command_line_arguments.start_dev_map: startup_worked = _start_map('development', command_line_arguments.ai_players, force_player_id=command_line_arguments.force_player_id, is_map=True) elif command_line_arguments.start_random_map: startup_worked = _start_random_map(command_line_arguments.ai_players, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.start_specific_random_map is not None: startup_worked = _start_random_map(command_line_arguments.ai_players, seed=command_line_arguments.start_specific_random_map, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.start_map is not None: startup_worked = _start_map(command_line_arguments.start_map, command_line_arguments.ai_players, force_player_id=command_line_arguments.force_player_id, is_map=True) elif command_line_arguments.start_scenario is not None: startup_worked = _start_map(command_line_arguments.start_scenario, 0, True, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.load_game is not None: startup_worked = _load_cmd_map(command_line_arguments.load_game, command_line_arguments.ai_players, command_line_arguments.force_player_id) elif command_line_arguments.load_quicksave is not None: startup_worked = _load_last_quicksave() elif command_line_arguments.edit_map is not None: startup_worked = edit_map(command_line_arguments.edit_map) elif command_line_arguments.edit_game_map is not None: startup_worked = edit_game_map(command_line_arguments.edit_game_map) elif command_line_arguments.stringpreview: tiny = [ i for i in SavegameManager.get_maps()[0] if 'tiny' in i ] if not tiny: tiny = SavegameManager.get_map()[0] startup_worked = _start_map(tiny[0], ai_players=0, trader_enabled=False, pirate_enabled=False, force_player_id=command_line_arguments.force_player_id, is_map=True) from development.stringpreviewwidget import StringPreviewWidget __string_previewer = StringPreviewWidget(_modules.session) __string_previewer.show() elif command_line_arguments.create_mp_game: _modules.gui.show_main() _modules.gui.windows.open(_modules.gui.multiplayermenu) _modules.gui.multiplayermenu._create_game() _modules.gui.windows._windows[-1].act() elif command_line_arguments.join_mp_game: _modules.gui.show_main() _modules.gui.windows.open(_modules.gui.multiplayermenu) _modules.gui.multiplayermenu._join_game() else: # no commandline parameter, show main screen # initialize update checker if not command_line_arguments.gui_test: setup_update_check() _modules.gui.show_main() if not command_line_arguments.nopreload: preloading[0].start() if not startup_worked: # don't start main loop if startup failed return False if command_line_arguments.gamespeed is not None: if _modules.session is None: print "You can only set the speed via command line in combination with a game start parameter such as --start-map, etc." return False _modules.session.speed_set(GAME_SPEED.TICKS_PER_SECOND*command_line_arguments.gamespeed) if command_line_arguments.gui_test: from tests.gui import TestRunner TestRunner(horizons.globals.fife, command_line_arguments.gui_test) horizons.globals.fife.run()
def start(_command_line_arguments): """Starts the horizons. Will drop you to the main menu. @param _command_line_arguments: options object from optparse.OptionParser. see run_uh.py. """ global debug, preloading, command_line_arguments command_line_arguments = _command_line_arguments # NOTE: globals are designwise the same thing as singletons. they don't look pretty. # here, we only have globals that are either trivial, or only one instance may ever exist. from engine import Fife # handle commandline globals debug = command_line_arguments.debug if command_line_arguments.restore_settings: # just delete the file, Settings ctor will create a new one os.remove(PATHS.USER_CONFIG_FILE) if command_line_arguments.mp_master: try: mpieces = command_line_arguments.mp_master.partition(":") NETWORK.SERVER_ADDRESS = mpieces[0] # only change port if port is specified if mpieces[2]: NETWORK.SERVER_PORT = parse_port(mpieces[2]) except ValueError: print "Error: Invalid syntax in --mp-master commandline option. Port must be a number between 1 and 65535." return False # init fife before mp_bind is parsed, since it's needed there horizons.globals.fife = Fife() if command_line_arguments.generate_minimap: # we've been called as subprocess to generate a map preview from horizons.gui.modules.singleplayermenu import generate_random_minimap generate_random_minimap(*json.loads(command_line_arguments.generate_minimap)) sys.exit(0) if debug: # also True if a specific module is logged (but not 'fife') setup_debug_mode(command_line_arguments) if horizons.globals.fife.get_uh_setting("DebugLog"): set_debug_log(True, startup=True) if command_line_arguments.mp_bind: try: mpieces = command_line_arguments.mp_bind.partition(":") NETWORK.CLIENT_ADDRESS = mpieces[0] horizons.globals.fife.set_uh_setting("NetworkPort", parse_port(mpieces[2])) except ValueError: print "Error: Invalid syntax in --mp-bind commandline option. Port must be a number between 1 and 65535." return False setup_AI_settings(command_line_arguments) # set MAX_TICKS if command_line_arguments.max_ticks: GAME.MAX_TICKS = command_line_arguments.max_ticks preload_lock = threading.Lock() if ( command_line_arguments.atlas_generation and not command_line_arguments.gui_test and VERSION.IS_DEV_VERSION and horizons.globals.fife.get_uh_setting("AtlasesEnabled") and horizons.globals.fife.get_uh_setting("AtlasGenerationEnabled") ): atlas_loading_thread = None atlas_loading_thread = AtlasLoadingThread(preload_lock) atlas_loading_thread.start() # show info label about atlas generation try: import Tkinter from PIL import Image, ImageTk import time try: window = Tkinter.Tk() # iconify window instead of closing window.protocol("WM_DELETE_WINDOW", window.iconify) window.wm_withdraw() window.attributes("-topmost", 1) window.title("Unknown Horizons") window.maxsize(300, 150) logo = Image.open(horizons.constants.PATHS.UH_LOGO_FILE) res_logo = logo.resize((116, 99), Image.ANTIALIAS) res_logo_image = ImageTk.PhotoImage(res_logo) logo_label = Tkinter.Label(window, image=res_logo_image) logo_label.pack(side="left") label = Tkinter.Label(window, padx=10, text="Generating atlases!") label.pack(side="right") # wait a second to give the thread time to check if a generation is necessary at all time.sleep(1.0) window.deiconify() while atlas_loading_thread.is_alive(): if not window.state() == "iconic": window.attributes("-topmost", 0) window.update() time.sleep(0.1) window.destroy() except Tkinter.TclError: # catch #2298 atlas_loading_thread.join() except ImportError: # tkinter or PIL may be missing atlas_loading_thread.join() # init game parts if not setup_gui_logger(command_line_arguments): return False # GUI tests always run with sound disabled and SDL (so they can run under xvfb). # Needs to be done before engine is initialized. if command_line_arguments.gui_test: horizons.globals.fife.engine.getSettings().setRenderBackend("SDL") horizons.globals.fife.set_fife_setting("PlaySounds", False) ExtScheduler.create_instance(horizons.globals.fife.pump) horizons.globals.fife.init() if not VERSION.IS_DEV_VERSION and horizons.globals.fife.get_uh_setting("AtlasesEnabled"): GFX.USE_ATLASES = True PATHS.DB_FILES = PATHS.DB_FILES + (PATHS.ATLAS_DB_PATH,) horizons.globals.db = _create_main_db() _modules.gui = Gui() SavegameManager.init() horizons.globals.fife.init_animation_loader(GFX.USE_ATLASES) from horizons.entities import Entities Entities.load(horizons.globals.db, load_now=False) # create all references # for preloading game data while in main screen preload_thread = threading.Thread(target=preload_game_data, args=(preload_lock,)) preloading = (preload_thread, preload_lock) # Singleplayer seed needs to be changed before startup. if command_line_arguments.sp_seed: SINGLEPLAYER.SEED = command_line_arguments.sp_seed SINGLEPLAYER.FREEZE_PROTECTION = command_line_arguments.freeze_protection # start something according to commandline parameters startup_worked = True if command_line_arguments.start_dev_map: startup_worked = _start_map( "development", command_line_arguments.ai_players, force_player_id=command_line_arguments.force_player_id, is_map=True, ) elif command_line_arguments.start_random_map: startup_worked = _start_random_map( command_line_arguments.ai_players, force_player_id=command_line_arguments.force_player_id ) elif command_line_arguments.start_specific_random_map is not None: startup_worked = _start_random_map( command_line_arguments.ai_players, seed=command_line_arguments.start_specific_random_map, force_player_id=command_line_arguments.force_player_id, ) elif command_line_arguments.start_map is not None: startup_worked = _start_map( command_line_arguments.start_map, command_line_arguments.ai_players, force_player_id=command_line_arguments.force_player_id, is_map=True, ) elif command_line_arguments.start_scenario is not None: startup_worked = _start_map( command_line_arguments.start_scenario, 0, True, force_player_id=command_line_arguments.force_player_id ) elif command_line_arguments.load_game is not None: startup_worked = _load_cmd_map( command_line_arguments.load_game, command_line_arguments.ai_players, command_line_arguments.force_player_id ) elif command_line_arguments.load_quicksave is not None: startup_worked = _load_last_quicksave() elif command_line_arguments.edit_map is not None: startup_worked = edit_map(command_line_arguments.edit_map) elif command_line_arguments.edit_game_map is not None: startup_worked = edit_game_map(command_line_arguments.edit_game_map) elif command_line_arguments.stringpreview: tiny = [i for i in SavegameManager.get_maps()[0] if "tiny" in i] if not tiny: tiny = SavegameManager.get_map()[0] startup_worked = _start_map( tiny[0], ai_players=0, trader_enabled=False, pirate_enabled=False, force_player_id=command_line_arguments.force_player_id, is_map=True, ) from development.stringpreviewwidget import StringPreviewWidget __string_previewer = StringPreviewWidget(_modules.session) __string_previewer.show() elif command_line_arguments.create_mp_game: _modules.gui.show_main() _modules.gui.windows.open(_modules.gui.multiplayermenu) _modules.gui.multiplayermenu._create_game() _modules.gui.windows._windows[-1].act() elif command_line_arguments.join_mp_game: _modules.gui.show_main() _modules.gui.windows.open(_modules.gui.multiplayermenu) _modules.gui.multiplayermenu._join_game() else: # no commandline parameter, show main screen # initialize update checker if not command_line_arguments.gui_test: setup_update_check() _modules.gui.show_main() if not command_line_arguments.nopreload: preloading[0].start() if not startup_worked: # don't start main loop if startup failed return False if command_line_arguments.gamespeed is not None: if _modules.session is None: print "You can only set the speed via command line in combination with a game start parameter such as --start-map, etc." return False _modules.session.speed_set(GAME_SPEED.TICKS_PER_SECOND * command_line_arguments.gamespeed) if command_line_arguments.gui_test: from tests.gui import TestRunner TestRunner(horizons.globals.fife, command_line_arguments.gui_test) horizons.globals.fife.run()
def start(_command_line_arguments): """Starts the horizons. Will drop you to the main menu. @param _command_line_arguments: options object from optparse.OptionParser. see run_uh.py. """ global fife, db, debug, preloading, command_line_arguments command_line_arguments = _command_line_arguments # NOTE: globals are designwise the same thing as singletons. they don't look pretty. # here, we only have globals that are either trivial, or only one instance may ever exist. from engine import Fife # handle commandline globals debug = command_line_arguments.debug if command_line_arguments.restore_settings: # just delete the file, Settings ctor will create a new one os.remove( PATHS.USER_CONFIG_FILE ) if command_line_arguments.mp_master: try: mpieces = command_line_arguments.mp_master.partition(':') NETWORK.SERVER_ADDRESS = mpieces[0] # only change port if port is specified if len(mpieces[2]) > 0: NETWORK.SERVER_PORT = parse_port(mpieces[2], allow_zero=True) except ValueError: print "Error: Invalid syntax in --mp-master commandline option. Port must be a number between 1 and 65535." return False if command_line_arguments.generate_minimap: # we've been called as subprocess to generate a map preview from horizons.gui.modules.singleplayermenu import MapPreview MapPreview.generate_minimap( * json.loads( command_line_arguments.generate_minimap ) ) sys.exit(0) # init fife before mp_bind is parsed, since it's needed there fife = Fife() if command_line_arguments.mp_bind: try: mpieces = command_line_arguments.mp_bind.partition(':') NETWORK.CLIENT_ADDRESS = mpieces[0] fife.set_uh_setting("NetworkPort", parse_port(mpieces[2], allow_zero=True)) except ValueError: print "Error: Invalid syntax in --mp-bind commandline option. Port must be a number between 1 and 65535." return False if command_line_arguments.ai_highlights: AI.HIGHLIGHT_PLANS = True if command_line_arguments.human_ai: AI.HUMAN_AI = True # set singleplayer natural resource seed if command_line_arguments.nature_seed: SINGLEPLAYER.SEED = command_line_arguments.nature_seed # set MAX_TICKS if command_line_arguments.max_ticks: GAME.MAX_TICKS = command_line_arguments.max_ticks db = _create_main_db() # init game parts _init_gettext(fife) client_id = fife.get_uh_setting("ClientID") if client_id is None or len(client_id) == 0: # We need a new client id client_id = "".join("-" if c in (8, 13, 18, 23) else \ random.choice("0123456789abcdef") for c in xrange(0, 36)) fife.set_uh_setting("ClientID", client_id) fife.save_settings() # Install gui logger, needs to be done before instanciating Gui, otherwise we miss # the events of the main menu buttons if command_line_arguments.log_gui: if command_line_arguments.gui_test: raise Exception("Logging gui interactions doesn't work when running tests.") try: from tests.gui.logger import setup_gui_logger setup_gui_logger() except ImportError: import traceback traceback.print_exc() print print "Gui logging requires code that is only present in the repository and is not being installed." return False # GUI tests always run with sound disabled and SDL (so they can run under xvfb). # Needs to be done before engine is initialized. if command_line_arguments.gui_test: fife.engine.getSettings().setRenderBackend('SDL') fife.set_fife_setting('PlaySounds', False) ExtScheduler.create_instance(fife.pump) fife.init() _modules.gui = Gui() SavegameManager.init() from horizons.entities import Entities Entities.load(db, load_now=False) # create all references # for preloading game data while in main screen preload_lock = threading.Lock() preload_thread = threading.Thread(target=preload_game_data, args=(preload_lock,)) preloading = (preload_thread, preload_lock) # initalize update checker from horizons.util.checkupdates import UpdateInfo, check_for_updates, show_new_version_hint update_info = UpdateInfo() update_check_thread = threading.Thread(target=check_for_updates, args=(update_info,)) update_check_thread.start() def update_info_handler(info): if info.status == UpdateInfo.UNINITIALISED: ExtScheduler().add_new_object(Callback(update_info_handler, info), info) elif info.status == UpdateInfo.READY: show_new_version_hint(_modules.gui, info) elif info.status == UpdateInfo.INVALID: pass # couldn't retrieve file or nothing relevant in there update_info_handler(update_info) # schedules checks by itself # Singleplayer seed needs to be changed before startup. if command_line_arguments.sp_seed: SINGLEPLAYER.SEED = command_line_arguments.sp_seed # start something according to commandline parameters startup_worked = True if command_line_arguments.start_dev_map: startup_worked = _start_dev_map(command_line_arguments.ai_players, command_line_arguments.human_ai, command_line_arguments.force_player_id) elif command_line_arguments.start_random_map: startup_worked = _start_random_map(command_line_arguments.ai_players, command_line_arguments.human_ai, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.start_specific_random_map is not None: startup_worked = _start_random_map(command_line_arguments.ai_players, command_line_arguments.human_ai, \ seed=command_line_arguments.start_specific_random_map, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.start_map is not None: startup_worked = _start_map(command_line_arguments.start_map, command_line_arguments.ai_players, \ command_line_arguments.human_ai, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.start_scenario is not None: startup_worked = _start_map(command_line_arguments.start_scenario, 0, False, True, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.start_campaign is not None: startup_worked = _start_campaign(command_line_arguments.start_campaign, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.load_map is not None: startup_worked = _load_map(command_line_arguments.load_map, command_line_arguments.ai_players, \ command_line_arguments.human_ai, command_line_arguments.force_player_id) elif command_line_arguments.load_quicksave is not None: startup_worked = _load_last_quicksave() elif command_line_arguments.stringpreview: tiny = [ i for i in SavegameManager.get_maps()[0] if 'tiny' in i ] if not tiny: tiny = SavegameManager.get_map()[0] startup_worked = _start_map(tiny[0], ai_players=0, human_ai=False, trader_enabled=False, pirate_enabled=False, \ force_player_id=command_line_arguments.force_player_id) from development.stringpreviewwidget import StringPreviewWidget __string_previewer = StringPreviewWidget(_modules.session) __string_previewer.show() elif command_line_arguments.create_mp_game: _modules.gui.show_main() _modules.gui.show_multi() _modules.gui.create_default_mp_game() elif command_line_arguments.join_mp_game: _modules.gui.show_main() _modules.gui.show_multi() _modules.gui.join_mp_game() else: # no commandline parameter, show main screen _modules.gui.show_main() if not command_line_arguments.nopreload: preloading[0].start() if not startup_worked: # don't start main loop if startup failed return False if command_line_arguments.gamespeed is not None: _modules.session.speed_set(GAME_SPEED.TICKS_PER_SECOND*command_line_arguments.gamespeed) if command_line_arguments.gui_test: from tests.gui import TestRunner TestRunner(fife, command_line_arguments.gui_test) if command_line_arguments.interactive_shell: from horizons.util import interactive_shell interactive_shell.start(fife) fife.run()
def _select_single(self, show): assert show in ('random', 'scenario', 'campaign', 'free_maps') self.hide() event_map = { 'cancel' : Callback.ChainedCallbacks(self._save_player_name, self.show_main), 'okay' : self.start_single, 'scenario' : Callback(self._select_single, show='scenario'), 'campaign' : Callback(self._select_single, show='campaign'), 'random' : Callback(self._select_single, show='random'), 'free_maps' : Callback(self._select_single, show='free_maps') } self.current.mapEvents(event_map) # init gui for subcategory right_side = self.widgets['sp_%s' % show] self.current.findChild(name=show).marked = True self.current.aidata.hide() # hide previous widget, unhide new right side widget if self.active_right_side is not None: self.active_right_side.parent.hideChild(self.active_right_side) right_side.parent.showChild(right_side) self.active_right_side = right_side if show == 'random': self._setup_random_map_selection(right_side) self._setup_game_settings_selection() self._on_random_map_parameter_changed() self.active_right_side.findChild(name="open_random_map_archive").capture(self._open_random_map_archive) self.current.aidata.show() elif show == 'free_maps': self.current.files, maps_display = SavegameManager.get_maps() self.active_right_side.distributeInitialData({ 'maplist' : maps_display, }) # update preview whenever something is selected in the list self.active_right_side.mapEvents({ 'maplist/action': self._update_free_map_infos, }) self._setup_game_settings_selection() if maps_display: # select first entry self.active_right_side.distributeData({'maplist': 0}) self.current.aidata.show() self._update_free_map_infos() elif show == 'campaign': # tell people that we don't have any content text = u"We currently don't have any campaigns available for you. " + \ u"If you are interested in adding campaigns to Unknown Horizons, " + \ u"please contact us via our website (http://www.unknown-horizons.org)!" self.show_popup("No campaigns available yet", text) self.current.files, maps_display = SavegameManager.get_campaigns() self.active_right_side.distributeInitialData({ 'maplist' : maps_display, }) self.active_right_side.mapEvents({ 'maplist/action': self._update_campaign_infos }) if maps_display: # select first entry self.active_right_side.distributeData({'maplist': 0}) self._update_campaign_infos() elif show == 'scenario': self.current.files, maps_display = SavegameManager.get_available_scenarios() # get the map files and their display names. display tutorials on top. prefer_tutorial = lambda x : ('tutorial' not in x, x) maps_display.sort(key=prefer_tutorial) self.current.files.sort(key=prefer_tutorial) #add all locales to lang list, select current locale as default and sort lang_list = self.current.findChild(name="uni_langlist") self.active_right_side.distributeInitialData({ 'maplist' : maps_display, }) if maps_display: # select first entry self.active_right_side.distributeData({'maplist': 0}) lang_list.items = self._get_available_languages() cur_locale = horizons.main.fife.get_locale() if LANGUAGENAMES[cur_locale] in lang_list.items: lang_list.selected = lang_list.items.index(LANGUAGENAMES[cur_locale]) else: lang_list.selected = 0 self.active_right_side.mapEvents({ 'maplist/action': self._update_scenario_infos, 'uni_langlist/action': self._update_scenario_infos, }) self._update_scenario_infos() self.current.show() self.on_escape = self.show_main
def start(_command_line_arguments): """Starts the horizons. Will drop you to the main menu. @param _command_line_arguments: options object from optparse.OptionParser. see run_uh.py. """ global debug, preloading, command_line_arguments command_line_arguments = _command_line_arguments # NOTE: globals are designwise the same thing as singletons. they don't look pretty. # here, we only have globals that are either trivial, or only one instance may ever exist. from engine import Fife # handle commandline globals debug = command_line_arguments.debug if command_line_arguments.restore_settings: # just delete the file, Settings ctor will create a new one os.remove( PATHS.USER_CONFIG_FILE ) if command_line_arguments.mp_master: try: mpieces = command_line_arguments.mp_master.partition(':') NETWORK.SERVER_ADDRESS = mpieces[0] # only change port if port is specified if mpieces[2]: NETWORK.SERVER_PORT = parse_port(mpieces[2]) except ValueError: print "Error: Invalid syntax in --mp-master commandline option. Port must be a number between 1 and 65535." return False # init fife before mp_bind is parsed, since it's needed there horizons.globals.fife = Fife() if command_line_arguments.generate_minimap: # we've been called as subprocess to generate a map preview from horizons.gui.modules.singleplayermenu import generate_random_minimap generate_random_minimap( * json.loads( command_line_arguments.generate_minimap ) ) sys.exit(0) if debug: # also True if a specific module is logged (but not 'fife') if not (command_line_arguments.debug_module and 'fife' not in command_line_arguments.debug_module): horizons.globals.fife._log.logToPrompt = True if command_line_arguments.debug_log_only: # This is a workaround to not show fife logs in the shell even if # (due to the way the fife logger works) these logs will not be # redirected to the UH logfile and instead written to a file fife.log # in the current directory. See #1782 for background information. horizons.globals.fife._log.logToPrompt = False horizons.globals.fife._log.logToFile = True if horizons.globals.fife.get_uh_setting("DebugLog"): set_debug_log(True, startup=True) if command_line_arguments.mp_bind: try: mpieces = command_line_arguments.mp_bind.partition(':') NETWORK.CLIENT_ADDRESS = mpieces[0] horizons.globals.fife.set_uh_setting("NetworkPort", parse_port(mpieces[2])) except ValueError: print "Error: Invalid syntax in --mp-bind commandline option. Port must be a number between 1 and 65535." return False if command_line_arguments.ai_highlights: AI.HIGHLIGHT_PLANS = True if command_line_arguments.ai_combat_highlights: AI.HIGHLIGHT_COMBAT = True if command_line_arguments.human_ai: AI.HUMAN_AI = True # set MAX_TICKS if command_line_arguments.max_ticks: GAME.MAX_TICKS = command_line_arguments.max_ticks atlas_generator = None horizons_path = os.path.dirname(horizons.__file__) if VERSION.IS_DEV_VERSION and horizons.globals.fife.get_uh_setting('AtlasesEnabled') \ and horizons.globals.fife.get_uh_setting('AtlasGenerationEnabled') \ and command_line_arguments.atlas_generation \ and not command_line_arguments.gui_test: args = [sys.executable, os.path.join(horizons_path, 'engine', 'generate_atlases.py'), str(horizons.globals.fife.get_uh_setting('MaxAtlasSize'))] atlas_generator = subprocess.Popen(args, stdout=None, stderr=subprocess.STDOUT) # init game parts # Install gui logger, needs to be done before instantiating Gui, otherwise we miss # the events of the main menu buttons if command_line_arguments.log_gui: if command_line_arguments.gui_test: raise Exception("Logging gui interactions doesn't work when running tests.") try: from tests.gui.logger import setup_gui_logger setup_gui_logger() except ImportError: traceback.print_exc() print print "Gui logging requires code that is only present in the repository and is not being installed." return False # GUI tests always run with sound disabled and SDL (so they can run under xvfb). # Needs to be done before engine is initialized. if command_line_arguments.gui_test: horizons.globals.fife.engine.getSettings().setRenderBackend('SDL') horizons.globals.fife.set_fife_setting('PlaySounds', False) ExtScheduler.create_instance(horizons.globals.fife.pump) horizons.globals.fife.init() if atlas_generator is not None: atlas_generator.wait() assert atlas_generator.returncode is not None if atlas_generator.returncode != 0: print 'Atlas generation failed. Continuing without atlas support.' print 'This just means that the game will run a bit slower.' print 'It will still run fine unless there are other problems.' print GFX.USE_ATLASES = False else: GFX.USE_ATLASES = True PATHS.DB_FILES = PATHS.DB_FILES + (PATHS.ATLAS_DB_PATH, ) elif not VERSION.IS_DEV_VERSION and horizons.globals.fife.get_uh_setting('AtlasesEnabled'): GFX.USE_ATLASES = True PATHS.DB_FILES = PATHS.DB_FILES + (PATHS.ATLAS_DB_PATH, ) horizons.globals.db = _create_main_db() horizons.globals.fife.init_animation_loader(GFX.USE_ATLASES) _modules.gui = Gui() SavegameManager.init() from horizons.entities import Entities Entities.load(horizons.globals.db, load_now=False) # create all references # for preloading game data while in main screen preload_lock = threading.Lock() preload_thread = threading.Thread(target=preload_game_data, args=(preload_lock,)) preloading = (preload_thread, preload_lock) # Singleplayer seed needs to be changed before startup. if command_line_arguments.sp_seed: SINGLEPLAYER.SEED = command_line_arguments.sp_seed SINGLEPLAYER.FREEZE_PROTECTION = command_line_arguments.freeze_protection # start something according to commandline parameters startup_worked = True if command_line_arguments.start_dev_map: startup_worked = _start_map('development', command_line_arguments.ai_players, force_player_id=command_line_arguments.force_player_id, is_map=True) elif command_line_arguments.start_random_map: startup_worked = _start_random_map(command_line_arguments.ai_players, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.start_specific_random_map is not None: startup_worked = _start_random_map(command_line_arguments.ai_players, seed=command_line_arguments.start_specific_random_map, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.start_map is not None: startup_worked = _start_map(command_line_arguments.start_map, command_line_arguments.ai_players, force_player_id=command_line_arguments.force_player_id, is_map=True) elif command_line_arguments.start_scenario is not None: startup_worked = _start_map(command_line_arguments.start_scenario, 0, True, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.load_game is not None: startup_worked = _load_cmd_map(command_line_arguments.load_game, command_line_arguments.ai_players, command_line_arguments.force_player_id) elif command_line_arguments.load_quicksave is not None: startup_worked = _load_last_quicksave() elif command_line_arguments.edit_map is not None: startup_worked = edit_map(command_line_arguments.edit_map) elif command_line_arguments.edit_game_map is not None: startup_worked = edit_game_map(command_line_arguments.edit_game_map) elif command_line_arguments.stringpreview: tiny = [ i for i in SavegameManager.get_maps()[0] if 'tiny' in i ] if not tiny: tiny = SavegameManager.get_map()[0] startup_worked = _start_map(tiny[0], ai_players=0, trader_enabled=False, pirate_enabled=False, force_player_id=command_line_arguments.force_player_id, is_map=True) from development.stringpreviewwidget import StringPreviewWidget __string_previewer = StringPreviewWidget(_modules.session) __string_previewer.show() elif command_line_arguments.create_mp_game: _modules.gui.show_main() _modules.gui.windows.open(_modules.gui.multiplayermenu) _modules.gui.multiplayermenu._create_game() _modules.gui.windows._windows[-1].act() elif command_line_arguments.join_mp_game: _modules.gui.show_main() _modules.gui.windows.open(_modules.gui.multiplayermenu) _modules.gui.multiplayermenu._join_game() else: # no commandline parameter, show main screen # initialize update checker if not command_line_arguments.gui_test: from horizons.util.checkupdates import UpdateInfo, check_for_updates, show_new_version_hint update_info = UpdateInfo() update_check_thread = threading.Thread(target=check_for_updates, args=(update_info,)) update_check_thread.start() def update_info_handler(info): if info.status == UpdateInfo.UNINITIALIZED: ExtScheduler().add_new_object(Callback(update_info_handler, info), info) elif info.status == UpdateInfo.READY: show_new_version_hint(_modules.gui, info) elif info.status == UpdateInfo.INVALID: pass # couldn't retrieve file or nothing relevant in there update_info_handler(update_info) # schedules checks by itself _modules.gui.show_main() if not command_line_arguments.nopreload: preloading[0].start() if not startup_worked: # don't start main loop if startup failed return False if command_line_arguments.gamespeed is not None: if _modules.session is None: print "You can only set the speed via command line in combination with a game start parameter such as --start-map, etc." return False _modules.session.speed_set(GAME_SPEED.TICKS_PER_SECOND*command_line_arguments.gamespeed) if command_line_arguments.gui_test: from tests.gui import TestRunner TestRunner(horizons.globals.fife, command_line_arguments.gui_test) horizons.globals.fife.run()
def start(_command_line_arguments): """Starts the horizons. Will drop you to the main menu. @param _command_line_arguments: options object from optparse.OptionParser. see run_uh.py. """ global debug, preloading, command_line_arguments command_line_arguments = _command_line_arguments # NOTE: globals are designwise the same thing as singletons. they don't look pretty. # here, we only have globals that are either trivial, or only one instance may ever exist. from engine import Fife # handle commandline globals debug = command_line_arguments.debug if command_line_arguments.restore_settings: # just delete the file, Settings ctor will create a new one os.remove(PATHS.USER_CONFIG_FILE) if command_line_arguments.mp_master: try: mpieces = command_line_arguments.mp_master.partition(':') NETWORK.SERVER_ADDRESS = mpieces[0] # only change port if port is specified if mpieces[2]: NETWORK.SERVER_PORT = parse_port(mpieces[2]) except ValueError: print "Error: Invalid syntax in --mp-master commandline option. Port must be a number between 1 and 65535." return False # init fife before mp_bind is parsed, since it's needed there horizons.globals.fife = Fife() if command_line_arguments.generate_minimap: # we've been called as subprocess to generate a map preview from horizons.gui.modules.singleplayermenu import generate_random_minimap generate_random_minimap( *json.loads(command_line_arguments.generate_minimap)) sys.exit(0) if debug: # also True if a specific module is logged (but not 'fife') if not (command_line_arguments.debug_module and 'fife' not in command_line_arguments.debug_module): horizons.globals.fife._log.logToPrompt = True if command_line_arguments.debug_log_only: # This is a workaround to not show fife logs in the shell even if # (due to the way the fife logger works) these logs will not be # redirected to the UH logfile and instead written to a file fife.log # in the current directory. See #1782 for background information. horizons.globals.fife._log.logToPrompt = False horizons.globals.fife._log.logToFile = True if horizons.globals.fife.get_uh_setting("DebugLog"): set_debug_log(True, startup=True) if command_line_arguments.mp_bind: try: mpieces = command_line_arguments.mp_bind.partition(':') NETWORK.CLIENT_ADDRESS = mpieces[0] horizons.globals.fife.set_uh_setting("NetworkPort", parse_port(mpieces[2])) except ValueError: print "Error: Invalid syntax in --mp-bind commandline option. Port must be a number between 1 and 65535." return False if command_line_arguments.ai_highlights: AI.HIGHLIGHT_PLANS = True if command_line_arguments.ai_combat_highlights: AI.HIGHLIGHT_COMBAT = True if command_line_arguments.human_ai: AI.HUMAN_AI = True # set MAX_TICKS if command_line_arguments.max_ticks: GAME.MAX_TICKS = command_line_arguments.max_ticks atlas_generator = None horizons_path = os.path.dirname(horizons.__file__) if VERSION.IS_DEV_VERSION and horizons.globals.fife.get_uh_setting('AtlasesEnabled') \ and horizons.globals.fife.get_uh_setting('AtlasGenerationEnabled') \ and command_line_arguments.atlas_generation \ and not command_line_arguments.gui_test: args = [ sys.executable, os.path.join(horizons_path, 'engine', 'generate_atlases.py'), str(horizons.globals.fife.get_uh_setting('MaxAtlasSize')) ] atlas_generator = subprocess.Popen(args, stdout=None, stderr=subprocess.STDOUT) # init game parts # Install gui logger, needs to be done before instantiating Gui, otherwise we miss # the events of the main menu buttons if command_line_arguments.log_gui: if command_line_arguments.gui_test: raise Exception( "Logging gui interactions doesn't work when running tests.") try: from tests.gui.logger import setup_gui_logger setup_gui_logger() except ImportError: traceback.print_exc() print print "Gui logging requires code that is only present in the repository and is not being installed." return False # GUI tests always run with sound disabled and SDL (so they can run under xvfb). # Needs to be done before engine is initialized. if command_line_arguments.gui_test: horizons.globals.fife.engine.getSettings().setRenderBackend('SDL') horizons.globals.fife.set_fife_setting('PlaySounds', False) ExtScheduler.create_instance(horizons.globals.fife.pump) horizons.globals.fife.init() if atlas_generator is not None: atlas_generator.wait() assert atlas_generator.returncode is not None if atlas_generator.returncode != 0: print 'Atlas generation failed. Continuing without atlas support.' print 'This just means that the game will run a bit slower.' print 'It will still run fine unless there are other problems.' print GFX.USE_ATLASES = False else: GFX.USE_ATLASES = True PATHS.DB_FILES = PATHS.DB_FILES + (PATHS.ATLAS_DB_PATH, ) elif not VERSION.IS_DEV_VERSION and horizons.globals.fife.get_uh_setting( 'AtlasesEnabled'): GFX.USE_ATLASES = True PATHS.DB_FILES = PATHS.DB_FILES + (PATHS.ATLAS_DB_PATH, ) horizons.globals.db = _create_main_db() horizons.globals.fife.init_animation_loader(GFX.USE_ATLASES) _modules.gui = Gui() SavegameManager.init() from horizons.entities import Entities Entities.load(horizons.globals.db, load_now=False) # create all references # for preloading game data while in main screen preload_lock = threading.Lock() preload_thread = threading.Thread(target=preload_game_data, args=(preload_lock, )) preloading = (preload_thread, preload_lock) # Singleplayer seed needs to be changed before startup. if command_line_arguments.sp_seed: SINGLEPLAYER.SEED = command_line_arguments.sp_seed SINGLEPLAYER.FREEZE_PROTECTION = command_line_arguments.freeze_protection # start something according to commandline parameters startup_worked = True if command_line_arguments.start_dev_map: startup_worked = _start_map( 'development', command_line_arguments.ai_players, force_player_id=command_line_arguments.force_player_id, is_map=True) elif command_line_arguments.start_random_map: startup_worked = _start_random_map( command_line_arguments.ai_players, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.start_specific_random_map is not None: startup_worked = _start_random_map( command_line_arguments.ai_players, seed=command_line_arguments.start_specific_random_map, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.start_map is not None: startup_worked = _start_map( command_line_arguments.start_map, command_line_arguments.ai_players, force_player_id=command_line_arguments.force_player_id, is_map=True) elif command_line_arguments.start_scenario is not None: startup_worked = _start_map( command_line_arguments.start_scenario, 0, True, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.load_game is not None: startup_worked = _load_cmd_map(command_line_arguments.load_game, command_line_arguments.ai_players, command_line_arguments.force_player_id) elif command_line_arguments.load_quicksave is not None: startup_worked = _load_last_quicksave() elif command_line_arguments.edit_map is not None: startup_worked = edit_map(command_line_arguments.edit_map) elif command_line_arguments.edit_game_map is not None: startup_worked = edit_game_map(command_line_arguments.edit_game_map) elif command_line_arguments.stringpreview: tiny = [i for i in SavegameManager.get_maps()[0] if 'tiny' in i] if not tiny: tiny = SavegameManager.get_map()[0] startup_worked = _start_map( tiny[0], ai_players=0, trader_enabled=False, pirate_enabled=False, force_player_id=command_line_arguments.force_player_id, is_map=True) from development.stringpreviewwidget import StringPreviewWidget __string_previewer = StringPreviewWidget(_modules.session) __string_previewer.show() elif command_line_arguments.create_mp_game: _modules.gui.show_main() _modules.gui.windows.show(_modules.gui.multiplayermenu) _modules.gui.multiplayermenu._create_game() _modules.gui.windows._windows[-1].act() elif command_line_arguments.join_mp_game: _modules.gui.show_main() _modules.gui.windows.show(_modules.gui.multiplayermenu) _modules.gui.multiplayermenu._join_game() else: # no commandline parameter, show main screen # initialize update checker if not command_line_arguments.gui_test: from horizons.util.checkupdates import UpdateInfo, check_for_updates, show_new_version_hint update_info = UpdateInfo() update_check_thread = threading.Thread(target=check_for_updates, args=(update_info, )) update_check_thread.start() def update_info_handler(info): if info.status == UpdateInfo.UNINITIALIZED: ExtScheduler().add_new_object( Callback(update_info_handler, info), info) elif info.status == UpdateInfo.READY: show_new_version_hint(_modules.gui, info) elif info.status == UpdateInfo.INVALID: pass # couldn't retrieve file or nothing relevant in there update_info_handler(update_info) # schedules checks by itself _modules.gui.show_main() if not command_line_arguments.nopreload: preloading[0].start() if not startup_worked: # don't start main loop if startup failed return False if command_line_arguments.gamespeed is not None: if _modules.session is None: print "You can only set the speed via command line in combination with a game start parameter such as --start-map, etc." return False _modules.session.speed_set(GAME_SPEED.TICKS_PER_SECOND * command_line_arguments.gamespeed) if command_line_arguments.gui_test: from tests.gui import TestRunner TestRunner(horizons.globals.fife, command_line_arguments.gui_test) horizons.globals.fife.run()
def _select_single(self, show): assert show in ('random', 'scenario', 'free_maps') self.hide() event_map = { 'cancel' : Callback.ChainedCallbacks(self._save_player_name, self.mainmenu.show_main), 'okay' : self.start_single, 'scenario' : Callback(self._select_single, show='scenario'), 'random' : Callback(self._select_single, show='random'), 'free_maps' : Callback(self._select_single, show='free_maps') } self.current.mapEvents(event_map) # init gui for subcategory right_side = self.widgets['sp_%s' % show] self.current.findChild(name=show).marked = True self.current.aidata.hide() # hide previous widget, unhide new right side widget if self.active_right_side is not None: self.active_right_side.parent.hideChild(self.active_right_side) right_side.parent.showChild(right_side) self.active_right_side = right_side if show == 'random': self._setup_random_map_selection(right_side) self._setup_game_settings_selection() self._on_random_map_parameter_changed() self.current.aidata.show() elif show == 'free_maps': self.current.files, maps_display = SavegameManager.get_maps() self.active_right_side.distributeInitialData({ 'maplist' : maps_display, }) # update preview whenever something is selected in the list self.active_right_side.mapEvents({ 'maplist/action': self._update_free_map_infos, }) self._setup_game_settings_selection() if maps_display: # select first entry self.active_right_side.distributeData({'maplist': 0}) self.current.aidata.show() self._update_free_map_infos() elif show == 'scenario': self.current.files, maps_display = SavegameManager.get_available_scenarios(hide_test_scenarios=True) # get the map files and their display names. display tutorials on top. prefer_tutorial = lambda x : ('tutorial' not in x, x) maps_display.sort(key=prefer_tutorial) self.current.files.sort(key=prefer_tutorial) #add all locales to lang list, select current locale as default and sort lang_list = self.current.findChild(name="uni_langlist") self.active_right_side.distributeInitialData({ 'maplist' : maps_display, }) if maps_display: # select first entry self.active_right_side.distributeData({'maplist': 0}) lang_list.items = self._get_available_languages() cur_locale = horizons.globals.fife.get_locale() if LANGUAGENAMES[cur_locale] in lang_list.items: lang_list.selected = lang_list.items.index(LANGUAGENAMES[cur_locale]) else: lang_list.selected = 0 self.active_right_side.mapEvents({ 'maplist/action': self._update_scenario_infos, 'uni_langlist/action': self._update_scenario_infos, }) self._update_scenario_infos() self.current.show() self.mainmenu.on_escape = self.mainmenu.show_main
def _select_single(self, show): assert show in ('random', 'scenario', 'campaign', 'free_maps') self.hide() event_map = { 'cancel' : Callback.ChainedCallbacks(self._save_player_name, self.show_main), 'okay' : self.start_single, 'scenario' : Callback(self._select_single, show='scenario'), 'campaign' : Callback(self._select_single, show='campaign'), 'random' : Callback(self._select_single, show='random'), 'free_maps' : Callback(self._select_single, show='free_maps') } # init gui for subcategory del event_map[show] right_side = self.widgets['sp_%s' % show] show_ai_options = False self.current.findChild(name=show).marked = True self.current.aidata.hide() # hide previous widget, unhide new right side widget if self.active_right_side is not None: self.active_right_side.parent.hideChild(self.active_right_side) right_side.parent.showChild(right_side) self.active_right_side = right_side self._current_mode = show if show == 'random': show_ai_options = True self._setup_random_map_selection(right_side) self._setup_game_settings_selection() self._on_random_map_parameter_changed() elif show == 'free_maps': self.current.files, maps_display = SavegameManager.get_maps() self.active_right_side.distributeInitialData({ 'maplist' : maps_display, }) def _update_infos(): number_of_players = SavegameManager.get_recommended_number_of_players( self._get_selected_map() ) #xgettext:python-format self.current.findChild(name="recommended_number_of_players_lbl").text = \ _("Recommended number of players: {number}").format(number=number_of_players) self.map_preview.update_map(self._get_selected_map()) if len(maps_display) > 0: # select first entry self.active_right_side.distributeData({ 'maplist' : 0, }) _update_infos() # update preview whenever somehting is selected in the list self.active_right_side.findChild(name="maplist").mapEvents({ 'maplist/action' : _update_infos, 'maplist/mouseWheelMovedUp' : _update_infos, 'maplist/mouseWheelMovedDown' : _update_infos }) self.active_right_side.findChild(name="maplist").capture(_update_infos, event_name="keyPressed") show_ai_options = True self._setup_game_settings_selection() else: choosable_locales = ['en', horizons.main.fife.get_locale()] if show == 'campaign': self.current.files, maps_display = SavegameManager.get_campaigns() # tell people that we don't have any content text = u"We currently don't have any campaigns available for you. " + \ u"If you are interested in adding campaigns to Unknown Horizons, " + \ u"please contact us via our website (http://www.unknown-horizons.org)!" self.show_popup("No campaigns available yet", text) elif show == 'scenario': self.current.files, maps_display = SavegameManager.get_available_scenarios(locales = choosable_locales) # get the map files and their display names self.active_right_side.distributeInitialData({ 'maplist' : maps_display, }) if len(maps_display) > 0: # select first entry self.active_right_side.distributeData({ 'maplist' : 0, }) if show == 'scenario': # update infos for scenario from horizons.scenario import ScenarioEventHandler, InvalidScenarioFileFormat def _update_infos(): """Fill in infos of selected scenario to label""" try: difficulty = ScenarioEventHandler.get_difficulty_from_file( self._get_selected_map() ) desc = ScenarioEventHandler.get_description_from_file( self._get_selected_map() ) author = ScenarioEventHandler.get_author_from_file( self._get_selected_map() ) except InvalidScenarioFileFormat as e: self._show_invalid_scenario_file_popup(e) return self.current.findChild(name="map_difficulty").text = \ _("Difficulty: {difficulty}").format(difficulty=difficulty) #xgettext:python-format self.current.findChild(name="map_author").text = \ _("Author: {author}").format(author=author) #xgettext:python-format self.current.findChild(name="map_desc").text = \ _("Description: {desc}").format(desc=desc) #xgettext:python-format #self.current.findChild(name="map_desc").parent.adaptLayout() elif show == 'campaign': # update infos for campaign def _update_infos(): """Fill in infos of selected campaign to label""" campaign_info = SavegameManager.get_campaign_info(filename = self._get_selected_map()) if not campaign_info: self._show_invalid_scenario_file_popup("Unknown error") return self.current.findChild(name="map_difficulty").text = \ _("Difficulty: {difficulty}").format(difficulty=campaign_info.get('difficulty', '')) #xgettext:python-format self.current.findChild(name="map_author").text = \ _("Author: {author}").format(author=campaign_info.get('author', '')) #xgettext:python-format self.current.findChild(name="map_desc").text = \ _("Description: {desc}").format(desc=campaign_info.get('description', '')) #xgettext:python-format self.active_right_side.findChild(name="maplist").capture(_update_infos) _update_infos() self.current.mapEvents(event_map) if show_ai_options: self.current.aidata.show() self.current.show() self.on_escape = self.show_main
def _select_single(self, show): assert show in ('random', 'scenario', 'campaign', 'free_maps') self.hide() event_map = { 'cancel' : Callback.ChainedCallbacks(self._save_player_name, self.show_main), 'okay' : self.start_single, 'scenario' : Callback(self._select_single, show='scenario'), 'campaign' : Callback(self._select_single, show='campaign'), 'random' : Callback(self._select_single, show='random'), 'free_maps' : Callback(self._select_single, show='free_maps') } # init gui for subcategory del event_map[show] right_side = self.widgets['sp_%s' % show] show_ai_options = False self.current.findChild(name=show).marked = True self.current.aidata.hide() # hide previous widget, unhide new right side widget if self.active_right_side is not None: self.active_right_side.parent.hideChild(self.active_right_side) right_side.parent.showChild(right_side) self.active_right_side = right_side self._current_mode = show if show == 'random': show_ai_options = True self._setup_random_map_selection(right_side) self._setup_game_settings_selection() self._on_random_map_parameter_changed() self.active_right_side.findChild(name="open_random_map_archive").capture(self._open_random_map_archive) elif show == 'free_maps': self.current.files, maps_display = SavegameManager.get_maps() self.active_right_side.distributeInitialData({ 'maplist' : maps_display, }) def _update_infos(): number_of_players = SavegameManager.get_recommended_number_of_players( self._get_selected_map() ) #xgettext:python-format self.current.findChild(name="recommended_number_of_players_lbl").text = \ _("Recommended number of players: {number}").format(number=number_of_players) self.map_preview.update_map(self._get_selected_map()) if len(maps_display) > 0: # select first entry self.active_right_side.distributeData({ 'maplist' : 0, }) _update_infos() # update preview whenever something is selected in the list self.active_right_side.findChild(name="maplist").mapEvents({ 'maplist/action' : _update_infos }) self.active_right_side.findChild(name="maplist").capture(_update_infos, event_name="keyPressed") show_ai_options = True self._setup_game_settings_selection() else: choosable_locales = ['en', horizons.main.fife.get_locale()] if show == 'campaign': self.current.files, maps_display = SavegameManager.get_campaigns() # tell people that we don't have any content text = u"We currently don't have any campaigns available for you. " + \ u"If you are interested in adding campaigns to Unknown Horizons, " + \ u"please contact us via our website (http://www.unknown-horizons.org)!" self.show_popup("No campaigns available yet", text) elif show == 'scenario': self.current.files, maps_display = SavegameManager.get_available_scenarios() # get the map files and their display names. display tutorials on top. prefer_tutorial = lambda x : ('tutorial' not in x, x) maps_display.sort(key=prefer_tutorial) self.current.files.sort(key=prefer_tutorial) #add all locales to lang list, select current locale as default and sort lang_list = self.current.findChild(name="uni_langlist") self.active_right_side.distributeInitialData({ 'maplist' : maps_display, }) # select first entry self.active_right_side.distributeData({ 'maplist' : 0, }) selectable_languages = [] #show only selectable languages for i in find_available_languages().keys(): if os.path.exists(self._get_selected_map() + '_' + i + '.' + SavegameManager.scenario_extension): selectable_languages.append(LANGUAGENAMES[i]) selectable_languages.sort() lang_list.items = selectable_languages cur_locale = horizons.main.fife.get_locale() if LANGUAGENAMES[cur_locale] in lang_list.items: lang_list.selected = lang_list.items.index(LANGUAGENAMES[cur_locale]) else: lang_list.selected = 0 self.active_right_side.distributeInitialData({ 'maplist' : maps_display, }) if len(maps_display) > 0: # select first entry self.active_right_side.distributeData({ 'maplist' : 0, }) if show == 'scenario': # update infos for scenario from horizons.scenario import ScenarioEventHandler, InvalidScenarioFileFormat def _update_infos(): """Fill in infos of selected scenario to label""" def _find_map_filename(locale = None): """Finds the selected map's filename with its locale.""" this_locale = "" new_map_name = "" if locale is None: this_locale = LANGUAGENAMES.get_by_value(lang_list.selected_item) else: this_locale = locale #check if selected map's file ends with .yaml if self._get_selected_map().find('.yaml') == -1: new_map_name = self._get_selected_map() + '_' + \ this_locale + '.' + \ SavegameManager.scenario_extension #if selected map's file ends with .yaml then get current locale #to remove locale postfix from selected_map's name else: #get current locale to split current map file name current_locale = yamlcache.YamlCache.get_file(self._get_selected_map(), \ game_data=True)['locale'] new_map_name = self._get_selected_map()[:self._get_selected_map().\ find('_' + current_locale)] + '_' + \ this_locale + '.' + \ SavegameManager.scenario_extension return new_map_name cur_selected_language = lang_list.selected_item selectable_languages = [] #show only selectable languages for i in find_available_languages().keys(): if os.path.exists(_find_map_filename(i)): selectable_languages.append(LANGUAGENAMES[i]) selectable_languages.sort() lang_list.items = selectable_languages if cur_selected_language in lang_list.items: lang_list.selected = lang_list.items.index(cur_selected_language) else: lang_list.selected = 0 def _update_translation_infos(new_map_name): """Fill in translation infos of selected scenario to translation label. It gets translation_status from new_map_file. If there is no attribute like translation_status then selected locale is the original locale of the selected scenario. In this case, hide translation_status_label. If there are fuzzy translations, show them as untranslated. This function also sets scenario map name using locale. (e.g. tutorial -> tutorial_en.yaml)""" translation_status_label = self.current.findChild(name="translation_status") try: #get translation status translation_status_message = yamlcache.YamlCache.get_file(new_map_name, \ game_data=True)['translation_status'] #find integers in translation_levels string translation_levels = [int(x) for x in re.findall(r'\d+', translation_status_message)] #if translation_levels' len is 3 it shows us there are fuzzy ones #show them as untranslated if len(translation_levels) == 3: translation_levels[2] += translation_levels[1] #if everything is translated then set untranslated count as 0 if len(translation_levels) == 1: translation_levels.append(0) translation_status_label.text = _("Translation status:") + '\n' + \ _("{translated} translated messages, {untranslated} untranslated messages")\ .format(translated=translation_levels[0], \ untranslated=translation_levels[-1]) #if selected language is english then don't show translation status translation_status_label.show() #if there is no translation_status then hide it except KeyError: translation_status_label.hide() self.current.files[ self.active_right_side.collectData('maplist') ] = new_map_name #Add locale postfix to fix scenario file try: _update_translation_infos(_find_map_filename()) #if there is no scenario with selected locale then select system's default except IOError: default_locale = "" _default_locale, default_encoding = locale.getdefaultlocale() try: default_locale = _default_locale.split('_')[0] except: # If default locale could not be detected use 'EN' as fallback default_locale = "en" #check if default_locale is in list if LANGUAGENAMES[default_locale] in lang_list.items: lang_list.selected = lang_list.items.index(LANGUAGENAMES[default_locale]) #if default locale is not in list then select first one else: lang_list.selected = 0 _update_infos() try: difficulty = ScenarioEventHandler.get_difficulty_from_file( self._get_selected_map() ) desc = ScenarioEventHandler.get_description_from_file( self._get_selected_map() ) author = ScenarioEventHandler.get_author_from_file( self._get_selected_map() ) except InvalidScenarioFileFormat as e: self._show_invalid_scenario_file_popup(e) return self.current.findChild(name="uni_map_difficulty").text = \ _("Difficulty: {difficulty}").format(difficulty=difficulty) #xgettext:python-format self.current.findChild(name="uni_map_author").text = \ _("Author: {author}").format(author=author) #xgettext:python-format self.current.findChild(name="uni_map_desc").text = \ _("Description: {desc}").format(desc=desc) #xgettext:python-format self.active_right_side.findChild(name="uni_langlist").mapEvents({ 'uni_langlist/action': _update_infos }) self.active_right_side.findChild(name="uni_langlist").capture(_update_infos, event_name="keyPressed") _update_infos() #hide and show current window to keep bugs away from us #if we don't do this, translation_label doesn't hide even if #selected language is english or doesn't show if selected #language has translation_status attribute self.current.hide() self.current.show() elif show == 'campaign': # update infos for campaign def _update_infos(): """Fill in infos of selected campaign to label""" campaign_info = SavegameManager.get_campaign_info(filename = self._get_selected_map()) if not campaign_info: self._show_invalid_scenario_file_popup("Unknown error") return self.current.findChild(name="map_difficulty").text = \ _("Difficulty: {difficulty}").format(difficulty=campaign_info.get('difficulty', '')) #xgettext:python-format self.current.findChild(name="map_author").text = \ _("Author: {author}").format(author=campaign_info.get('author', '')) #xgettext:python-format self.current.findChild(name="map_desc").text = \ _("Description: {desc}").format(desc=campaign_info.get('description', '')) #xgettext:python-format self.active_right_side.findChild(name="maplist").mapEvents({ 'maplist/action': _update_infos }) self.active_right_side.findChild(name="maplist").capture(_update_infos, event_name="keyPressed") _update_infos() self.current.mapEvents(event_map) if show_ai_options: self.current.aidata.show() self.current.show() self.on_escape = self.show_main
def _select_single(self, show): assert show in ('random', 'scenario', 'free_maps') self.hide() event_map = { 'cancel': Callback.ChainedCallbacks(self._save_player_name, self.show_main), 'okay': self.start_single, 'scenario': Callback(self._select_single, show='scenario'), 'random': Callback(self._select_single, show='random'), 'free_maps': Callback(self._select_single, show='free_maps') } self.current.mapEvents(event_map) # init gui for subcategory right_side = self.widgets['sp_%s' % show] self.current.findChild(name=show).marked = True self.current.aidata.hide() # hide previous widget, unhide new right side widget if self.active_right_side is not None: self.active_right_side.parent.hideChild(self.active_right_side) right_side.parent.showChild(right_side) self.active_right_side = right_side if show == 'random': self._setup_random_map_selection(right_side) self._setup_game_settings_selection() self._on_random_map_parameter_changed() self.active_right_side.findChild( name="open_random_map_archive").capture( self._open_random_map_archive) self.current.aidata.show() elif show == 'free_maps': self.current.files, maps_display = SavegameManager.get_maps() self.active_right_side.distributeInitialData({ 'maplist': maps_display, }) # update preview whenever something is selected in the list self.active_right_side.mapEvents({ 'maplist/action': self._update_free_map_infos, }) self._setup_game_settings_selection() if maps_display: # select first entry self.active_right_side.distributeData({'maplist': 0}) self.current.aidata.show() self._update_free_map_infos() elif show == 'scenario': self.current.files, maps_display = SavegameManager.get_available_scenarios( hide_test_scenarios=True) # get the map files and their display names. display tutorials on top. prefer_tutorial = lambda x: ('tutorial' not in x, x) maps_display.sort(key=prefer_tutorial) self.current.files.sort(key=prefer_tutorial) #add all locales to lang list, select current locale as default and sort lang_list = self.current.findChild(name="uni_langlist") self.active_right_side.distributeInitialData({ 'maplist': maps_display, }) if maps_display: # select first entry self.active_right_side.distributeData({'maplist': 0}) lang_list.items = self._get_available_languages() cur_locale = horizons.globals.fife.get_locale() if LANGUAGENAMES[cur_locale] in lang_list.items: lang_list.selected = lang_list.items.index( LANGUAGENAMES[cur_locale]) else: lang_list.selected = 0 self.active_right_side.mapEvents({ 'maplist/action': self._update_scenario_infos, 'uni_langlist/action': self._update_scenario_infos, }) self._update_scenario_infos() self.current.show() self.on_escape = self.show_main
def start(_command_line_arguments): """Starts the horizons. Will drop you to the main menu. @param _command_line_arguments: options object from optparse.OptionParser. see run_uh.py. """ global debug, preloading, command_line_arguments command_line_arguments = _command_line_arguments # NOTE: globals are designwise the same thing as singletons. they don't look pretty. # here, we only have globals that are either trivial, or only one instance may ever exist. from engine import Fife # handle commandline globals debug = command_line_arguments.debug if command_line_arguments.enable_atlases: # check if atlas files are outdated if atlases_need_rebuild(): print "Atlases have to be rebuild." if command_line_arguments.restore_settings: # just delete the file, Settings ctor will create a new one os.remove( PATHS.USER_CONFIG_FILE ) if command_line_arguments.mp_master: try: mpieces = command_line_arguments.mp_master.partition(':') NETWORK.SERVER_ADDRESS = mpieces[0] # only change port if port is specified if mpieces[2]: NETWORK.SERVER_PORT = parse_port(mpieces[2]) except ValueError: print "Error: Invalid syntax in --mp-master commandline option. Port must be a number between 1 and 65535." return False if command_line_arguments.generate_minimap: # we've been called as subprocess to generate a map preview from horizons.gui.modules.singleplayermenu import MapPreview MapPreview.generate_minimap( * json.loads( command_line_arguments.generate_minimap ) ) sys.exit(0) # init fife before mp_bind is parsed, since it's needed there horizons.globals.fife = Fife() if debug: # also True if a specific module is logged (but not 'fife') if not (command_line_arguments.debug_module and 'fife' not in command_line_arguments.debug_module): horizons.globals.fife._log.lm.setLogToPrompt(True) # After the next FIFE release, we should use this instead which is possible as of r3960: # horizons.globals.fife._log.logToPrompt = True if command_line_arguments.debug_log_only: # This is a workaround to not show fife logs in the shell even if # (due to the way the fife logger works) these logs will not be # redirected to the UH logfile and instead written to a file fife.log # in the current directory. See #1782 for background information. horizons.globals.fife._log.lm.setLogToPrompt(False) horizons.globals.fife._log.lm.setLogToFile(True) # same as above applies here, use property after next FIFE release if command_line_arguments.mp_bind: try: mpieces = command_line_arguments.mp_bind.partition(':') NETWORK.CLIENT_ADDRESS = mpieces[0] horizons.globals.fife.set_uh_setting("NetworkPort", parse_port(mpieces[2])) except ValueError: print "Error: Invalid syntax in --mp-bind commandline option. Port must be a number between 1 and 65535." return False if command_line_arguments.ai_highlights: AI.HIGHLIGHT_PLANS = True if command_line_arguments.ai_combat_highlights: AI.HIGHLIGHT_COMBAT = True if command_line_arguments.human_ai: AI.HUMAN_AI = True # set MAX_TICKS if command_line_arguments.max_ticks: GAME.MAX_TICKS = command_line_arguments.max_ticks horizons.globals.db = _create_main_db() # init game parts # Install gui logger, needs to be done before instantiating Gui, otherwise we miss # the events of the main menu buttons if command_line_arguments.log_gui: if command_line_arguments.gui_test: raise Exception("Logging gui interactions doesn't work when running tests.") try: from tests.gui.logger import setup_gui_logger setup_gui_logger() except ImportError: traceback.print_exc() print print "Gui logging requires code that is only present in the repository and is not being installed." return False # GUI tests always run with sound disabled and SDL (so they can run under xvfb). # Needs to be done before engine is initialized. if command_line_arguments.gui_test: horizons.globals.fife.engine.getSettings().setRenderBackend('SDL') horizons.globals.fife.set_fife_setting('PlaySounds', False) ExtScheduler.create_instance(horizons.globals.fife.pump) horizons.globals.fife.init() _modules.gui = Gui() SavegameManager.init() from horizons.entities import Entities Entities.load(horizons.globals.db, load_now=False) # create all references # for preloading game data while in main screen preload_lock = threading.Lock() preload_thread = threading.Thread(target=preload_game_data, args=(preload_lock,)) preloading = (preload_thread, preload_lock) # Singleplayer seed needs to be changed before startup. if command_line_arguments.sp_seed: SINGLEPLAYER.SEED = command_line_arguments.sp_seed # start something according to commandline parameters startup_worked = True if command_line_arguments.start_dev_map: startup_worked = _start_dev_map(command_line_arguments.ai_players, command_line_arguments.human_ai, command_line_arguments.force_player_id) elif command_line_arguments.start_random_map: startup_worked = _start_random_map(command_line_arguments.ai_players, command_line_arguments.human_ai, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.start_specific_random_map is not None: startup_worked = _start_random_map(command_line_arguments.ai_players, command_line_arguments.human_ai, seed=command_line_arguments.start_specific_random_map, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.start_map is not None: startup_worked = _start_map(command_line_arguments.start_map, command_line_arguments.ai_players, command_line_arguments.human_ai, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.start_scenario is not None: startup_worked = _start_map(command_line_arguments.start_scenario, 0, False, True, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.start_campaign is not None: startup_worked = _start_campaign(command_line_arguments.start_campaign, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.load_map is not None: startup_worked = _load_map(command_line_arguments.load_map, command_line_arguments.ai_players, command_line_arguments.human_ai, command_line_arguments.force_player_id) elif command_line_arguments.load_quicksave is not None: startup_worked = _load_last_quicksave() elif command_line_arguments.stringpreview: tiny = [ i for i in SavegameManager.get_maps()[0] if 'tiny' in i ] if not tiny: tiny = SavegameManager.get_map()[0] startup_worked = _start_map(tiny[0], ai_players=0, human_ai=False, trader_enabled=False, pirate_enabled=False, force_player_id=command_line_arguments.force_player_id) from development.stringpreviewwidget import StringPreviewWidget __string_previewer = StringPreviewWidget(_modules.session) __string_previewer.show() elif command_line_arguments.create_mp_game: _modules.gui.show_main() _modules.gui.show_multi() _modules.gui.create_default_mp_game() elif command_line_arguments.join_mp_game: _modules.gui.show_main() _modules.gui.show_multi() _modules.gui.join_mp_game() else: # no commandline parameter, show main screen # initalize update checker if not command_line_arguments.gui_test: from horizons.util.checkupdates import UpdateInfo, check_for_updates, show_new_version_hint update_info = UpdateInfo() update_check_thread = threading.Thread(target=check_for_updates, args=(update_info,)) update_check_thread.start() def update_info_handler(info): if info.status == UpdateInfo.UNINITIALISED: ExtScheduler().add_new_object(Callback(update_info_handler, info), info) elif info.status == UpdateInfo.READY: show_new_version_hint(_modules.gui, info) elif info.status == UpdateInfo.INVALID: pass # couldn't retrieve file or nothing relevant in there update_info_handler(update_info) # schedules checks by itself _modules.gui.show_main() if not command_line_arguments.nopreload: preloading[0].start() if not startup_worked: # don't start main loop if startup failed return False if command_line_arguments.gamespeed is not None: if _modules.session is None: print "You can only set the speed via command line in combination with a game start parameter such as --start-map, etc." return False _modules.session.speed_set(GAME_SPEED.TICKS_PER_SECOND*command_line_arguments.gamespeed) if command_line_arguments.gui_test: from tests.gui import TestRunner TestRunner(horizons.globals.fife, command_line_arguments.gui_test) if command_line_arguments.interactive_shell: from horizons.util import interactive_shell interactive_shell.start(horizons.globals.fife) horizons.globals.fife.run()
def _start_dev_map(): # start the development map (it's the first one) first_map = SavegameManager.get_maps()[0][1] load_game(first_map) return True
def show(self): self._map_data = SavegameManager.get_maps() self._gui.distributeInitialData({'map_list': self._map_data[1]}) self._parent_widget.removeAllChildren() self._parent_widget.addChild(self._gui)
def show_single(self, show = 'free_maps'): """ @param show: string, which type of games to show """ assert show in ('random', 'campaign', 'free_maps') self.hide() # reload since the gui is changed at runtime self.widgets.reload('singleplayermenu') self._switch_current_widget('singleplayermenu', center=True) eventMap = { 'cancel' : self.show_main, 'okay' : self.start_single, 'showCampaign' : Callback(self.show_single, show='campaign'), 'showRandom' : Callback(self.show_single, show='random'), 'showMaps' : Callback(self.show_single, show='free_maps') } # init gui for subcategory if show == 'random': del eventMap['showRandom'] self.current.findChild(name="showRandom").marked = True to_remove = self.current.findChild(name="map_list_area") to_remove.parent.removeChild(to_remove) to_remove = self.current.findChild(name="choose_map_lbl") to_remove.parent.removeChild(to_remove) self.show_popup(_('Warning'), \ _('The random map features is still in active development. '+\ 'It is to be considered a pre testing version. Problems are to be expected.')) else: if show == 'free_maps': del eventMap['showMaps'] self.current.findChild(name="showMaps").marked = True self.current.files, maps_display = SavegameManager.get_maps() else: # campaign del eventMap['showCampaign'] self.current.findChild(name="showCampaign").marked = True self.current.files, maps_display = SavegameManager.get_scenarios() # get the map files and their display names self.current.distributeInitialData({ 'maplist' : maps_display, }) if len(maps_display) > 0: # select first entry self.current.distributeData({ 'maplist' : 0, }) if show == 'campaign': # update infos for campaign from horizons.campaign import CampaignEventHandler, InvalidScenarioFileFormat def _update_infos(): """Fill in infos of selected scenario to label""" try: difficulty = CampaignEventHandler.get_difficulty_from_file( self.__get_selected_map() ) desc = CampaignEventHandler.get_description_from_file( self.__get_selected_map() ) author = CampaignEventHandler.get_author_from_file( self.__get_selected_map() ) except InvalidScenarioFileFormat, e: self.__show_invalid_scenario_file_popup(e) return self.current.findChild(name="map_difficulty").text = "Difficulty: " + unicode( difficulty ) self.current.findChild(name="map_author").text = "Author: " + unicode( author ) self.current.findChild(name="map_desc").text = "Description: " + unicode( desc ) self.current.findChild(name="map_desc").parent.adaptLayout() self.current.findChild(name="maplist").capture(_update_infos) _update_infos()
def start(_command_line_arguments): """Starts the horizons. Will drop you to the main menu. @param _command_line_arguments: options object from optparse.OptionParser. see run_uh.py. """ global debug, preloader, command_line_arguments command_line_arguments = _command_line_arguments # NOTE: globals are designwise the same thing as singletons. they don't look pretty. # here, we only have globals that are either trivial, or only one instance may ever exist. from .engine import Fife # handle commandline globals debug = command_line_arguments.debug if command_line_arguments.restore_settings: # just delete the file, Settings ctor will create a new one os.remove(PATHS.USER_CONFIG_FILE) if command_line_arguments.mp_master: try: mpieces = command_line_arguments.mp_master.partition(':') NETWORK.SERVER_ADDRESS = mpieces[0] # only change port if port is specified if mpieces[2]: NETWORK.SERVER_PORT = parse_port(mpieces[2]) except ValueError: print("Error: Invalid syntax in --mp-master commandline option. Port must be a number between 1 and 65535.") return False # init fife before mp_bind is parsed, since it's needed there horizons.globals.fife = Fife() if command_line_arguments.generate_minimap: # we've been called as subprocess to generate a map preview from horizons.gui.modules.singleplayermenu import generate_random_minimap generate_random_minimap(* json.loads( command_line_arguments.generate_minimap )) sys.exit(0) if debug: # also True if a specific module is logged (but not 'fife') setup_debug_mode(command_line_arguments) if horizons.globals.fife.get_uh_setting("DebugLog"): set_debug_log(True, startup=True) if command_line_arguments.mp_bind: try: mpieces = command_line_arguments.mp_bind.partition(':') NETWORK.CLIENT_ADDRESS = mpieces[0] horizons.globals.fife.set_uh_setting("NetworkPort", parse_port(mpieces[2])) except ValueError: print("Error: Invalid syntax in --mp-bind commandline option. Port must be a number between 1 and 65535.") return False setup_AI_settings(command_line_arguments) # set MAX_TICKS if command_line_arguments.max_ticks: GAME.MAX_TICKS = command_line_arguments.max_ticks # Setup atlases if (command_line_arguments.atlas_generation and not command_line_arguments.gui_test and VERSION.IS_DEV_VERSION and horizons.globals.fife.get_uh_setting('AtlasesEnabled') and horizons.globals.fife.get_uh_setting('AtlasGenerationEnabled')): generate_atlases() if not VERSION.IS_DEV_VERSION and horizons.globals.fife.get_uh_setting('AtlasesEnabled'): GFX.USE_ATLASES = True PATHS.DB_FILES = PATHS.DB_FILES + (PATHS.ATLAS_DB_PATH, ) # init game parts if not setup_gui_logger(command_line_arguments): return False # Check if the no-audio flag has been set. if command_line_arguments.no_audio: horizons.globals.fife.set_fife_setting('PlaySounds', False) # GUI tests always run with sound disabled and SDL (so they can run under xvfb). # Needs to be done before engine is initialized. if command_line_arguments.gui_test: horizons.globals.fife.engine.getSettings().setRenderBackend('SDL') horizons.globals.fife.set_fife_setting('PlaySounds', False) ExtScheduler.create_instance(horizons.globals.fife.pump) horizons.globals.fife.init() horizons.globals.db = _create_main_db() _modules.gui = Gui() SavegameManager.init() horizons.globals.fife.init_animation_loader(GFX.USE_ATLASES) from horizons.entities import Entities Entities.load(horizons.globals.db, load_now=False) # create all references # for preloading game data while in main screen preloader = PreloadingThread() # Singleplayer seed needs to be changed before startup. if command_line_arguments.sp_seed: SINGLEPLAYER.SEED = command_line_arguments.sp_seed SINGLEPLAYER.FREEZE_PROTECTION = command_line_arguments.freeze_protection # start something according to commandline parameters startup_worked = True if command_line_arguments.start_dev_map: startup_worked = _start_map('development', command_line_arguments.ai_players, force_player_id=command_line_arguments.force_player_id, is_map=True) elif command_line_arguments.start_random_map: startup_worked = _start_random_map(command_line_arguments.ai_players, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.start_specific_random_map is not None: startup_worked = _start_random_map(command_line_arguments.ai_players, seed=command_line_arguments.start_specific_random_map, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.start_map is not None: startup_worked = _start_map(command_line_arguments.start_map, command_line_arguments.ai_players, force_player_id=command_line_arguments.force_player_id, is_map=True) elif command_line_arguments.start_scenario is not None: startup_worked = _start_map(command_line_arguments.start_scenario, 0, True, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.load_game is not None: startup_worked = _load_cmd_map(command_line_arguments.load_game, command_line_arguments.ai_players, command_line_arguments.force_player_id) elif command_line_arguments.load_quicksave is not None: startup_worked = _load_last_quicksave() elif command_line_arguments.edit_map is not None: startup_worked = edit_map(command_line_arguments.edit_map) elif command_line_arguments.edit_game_map is not None: startup_worked = edit_game_map(command_line_arguments.edit_game_map) elif command_line_arguments.stringpreview: tiny = [i for i in SavegameManager.get_maps()[0] if 'tiny' in i] if not tiny: tiny = SavegameManager.get_map()[0] startup_worked = _start_map(tiny[0], ai_players=0, trader_enabled=False, pirate_enabled=False, force_player_id=command_line_arguments.force_player_id, is_map=True) from development.stringpreviewwidget import StringPreviewWidget __string_previewer = StringPreviewWidget(_modules.session) __string_previewer.show() elif command_line_arguments.create_mp_game: _modules.gui.show_main() _modules.gui.windows.open(_modules.gui.multiplayermenu) _modules.gui.multiplayermenu._create_game() _modules.gui.windows._windows[-1].act() elif command_line_arguments.join_mp_game: _modules.gui.show_main() _modules.gui.windows.open(_modules.gui.multiplayermenu) _modules.gui.multiplayermenu._join_game() else: # no commandline parameter, show main screen # initialize update checker if not command_line_arguments.gui_test: setup_async_update_check() _modules.gui.show_main() if not command_line_arguments.nopreload: preloader.start() if not startup_worked: # don't start main loop if startup failed return False if command_line_arguments.gamespeed is not None: if _modules.session is None: print("You can only set the speed via command line in combination with a game start parameter such as --start-map, etc.") return False _modules.session.speed_set(GAME_SPEED.TICKS_PER_SECOND * command_line_arguments.gamespeed) if command_line_arguments.gui_test: from tests.gui import TestRunner TestRunner(horizons.globals.fife, command_line_arguments.gui_test) horizons.globals.fife.run() return True
def show_single(self, show = 'scenario'): # tutorial """ @param show: string, which type of games to show """ assert show in ('random', 'scenario', 'campaign', 'free_maps') self.hide() # reload since the gui is changed at runtime self.widgets.reload('singleplayermenu') self._switch_current_widget('singleplayermenu', center=True) eventMap = { 'cancel' : self.show_main, 'okay' : self.start_single, 'scenario' : Callback(self.show_single, show='scenario'), 'campaign' : Callback(self.show_single, show='campaign'), 'random' : Callback(self.show_single, show='random'), 'free_maps' : Callback(self.show_single, show='free_maps') } # init gui for subcategory show_ai_options = False del eventMap[show] self.current.findChild(name=show).marked = True right_side = self.widgets['sp_%s' % show] self.current.findChild(name="right_side_box").addChild(right_side) if show == 'random': game_settings = self.widgets['game_settings'] if self.current.findChild(name="game_settings") is None: self.current.findChild(name="game_settings_box").addChild(game_settings) show_ai_options = True elif show == 'free_maps': self.current.files, maps_display = SavegameManager.get_maps() game_settings = self.widgets['game_settings'] if self.current.findChild(name="game_settings") is None: self.current.findChild(name="game_settings_box").addChild(game_settings) self.current.distributeInitialData({ 'maplist' : maps_display, }) if len(maps_display) > 0: # select first entry self.current.distributeData({ 'maplist' : 0, }) show_ai_options = True else: choosable_locales = ['en', horizons.main.fife.get_locale()] if show == 'campaign': self.current.files, maps_display = SavegameManager.get_campaigns() # tell people that we don't have any content text = u"We currently don't have any campaigns available for you. " + \ u"If you are interested in adding campaigns to Unknown Horizons, " + \ u"please contact us via our website (http://www.unknown-horizons.org)!" self.show_popup("No campaigns available yet", text) elif show == 'scenario': self.current.files, maps_display = SavegameManager.get_available_scenarios(locales = choosable_locales) # get the map files and their display names self.current.distributeInitialData({ 'maplist' : maps_display, }) if len(maps_display) > 0: # select first entry self.current.distributeData({ 'maplist' : 0, }) if show == 'scenario': # update infos for scenario from horizons.scenario import ScenarioEventHandler, InvalidScenarioFileFormat def _update_infos(): """Fill in infos of selected scenario to label""" try: difficulty = ScenarioEventHandler.get_difficulty_from_file( self.__get_selected_map() ) desc = ScenarioEventHandler.get_description_from_file( self.__get_selected_map() ) author = ScenarioEventHandler.get_author_from_file( self.__get_selected_map() ) except InvalidScenarioFileFormat, e: self.__show_invalid_scenario_file_popup(e) return self.current.findChild(name="map_difficulty").text = _("Difficulty: ") + unicode( difficulty ) self.current.findChild(name="map_author").text = _("Author: ") + unicode( author ) self.current.findChild(name="map_desc").text = _("Description: ") + unicode( desc ) #self.current.findChild(name="map_desc").parent.adaptLayout() elif show == 'campaign': # update infos for campaign def _update_infos(): """Fill in infos of selected campaign to label""" campaign_info = SavegameManager.get_campaign_info(filename = self.__get_selected_map()) if not campaign_info: # TODO : an "invalid campaign popup" self.__show_invalid_scenario_file_popup(e) return self.current.findChild(name="map_difficulty").text = _("Difficulty: ") + unicode(campaign_info.get('difficulty', '')) self.current.findChild(name="map_author").text = _("Author: ") + unicode(campaign_info.get('author', '')) self.current.findChild(name="map_desc").text = _("Description: ") + unicode(campaign_info.get('description', '')) self.current.findChild(name="maplist").capture(_update_infos) _update_infos()
def show_single(self, show = 'scenario'): # tutorial """ @param show: string, which type of games to show """ assert show in ('random', 'scenario', 'campaign', 'free_maps') self.hide() # reload since the gui is changed at runtime self.widgets.reload('singleplayermenu') self._switch_current_widget('singleplayermenu', center=True) eventMap = { 'cancel' : self.show_main, 'okay' : self.start_single, 'showScenario' : Callback(self.show_single, show='scenario'), 'showCampaign' : Callback(self.show_single, show='campaign'), 'showRandom' : Callback(self.show_single, show='random'), 'showMaps' : Callback(self.show_single, show='free_maps') } adjust_widget_black_background(self.widgets['singleplayermenu']) # init gui for subcategory if show == 'random': del eventMap['showRandom'] self.current.findChild(name="showRandom").marked = True to_remove = self.current.findChild(name="map_list_area") to_remove.parent.removeChild(to_remove) to_remove = self.current.findChild(name="choose_map_lbl") to_remove.parent.removeChild(to_remove) # need to add some options here (generation algo, size, ... ) else: if show == 'free_maps': del eventMap['showMaps'] self.current.findChild(name="showMaps").marked = True self.current.files, maps_display = SavegameManager.get_maps() elif show == 'campaign': del eventMap['showCampaign'] self.current.findChild(name="showCampaign").marked = True self.current.files, maps_display = SavegameManager.get_campaigns() else: # scenario del eventMap['showScenario'] self.current.findChild(name="showScenario").marked = True choosable_locales = ['en',horizons.main.fife.get_locale()] self.current.files, maps_display = SavegameManager.get_available_scenarios(locales = choosable_locales) # get the map files and their display names self.current.distributeInitialData({ 'maplist' : maps_display, }) if len(maps_display) > 0: # select first entry self.current.distributeData({ 'maplist' : 0, }) if show == 'scenario': # update infos for scenario from horizons.scenario import ScenarioEventHandler, InvalidScenarioFileFormat def _update_infos(): """Fill in infos of selected scenario to label""" try: difficulty = ScenarioEventHandler.get_difficulty_from_file( self.__get_selected_map() ) desc = ScenarioEventHandler.get_description_from_file( self.__get_selected_map() ) author = ScenarioEventHandler.get_author_from_file( self.__get_selected_map() ) except InvalidScenarioFileFormat, e: self.__show_invalid_scenario_file_popup(e) return self.current.findChild(name="map_difficulty").text = _("Difficulty: ") + unicode( difficulty ) self.current.findChild(name="map_author").text = _("Author: ") + unicode( author ) self.current.findChild(name="map_desc").text = _("Description: ") + unicode( desc ) #self.current.findChild(name="map_desc").parent.adaptLayout() elif show == 'campaign': # update infos for campaign def _update_infos(): """Fill in infos of selected campaign to label""" campaign_info = SavegameManager.get_campaign_info(file = self.__get_selected_map()) if not campaign_info: # TODO : an "invalid campaign popup" self.__show_invalid_scenario_file_popup(e) return self.current.findChild(name="map_difficulty").text = _("Difficulty: ") + unicode(campaign_info.get('difficulty', '')) self.current.findChild(name="map_author").text = _("Author: ") + unicode(campaign_info.get('author', '')) self.current.findChild(name="map_desc").text = _("Description: ") + unicode(campaign_info.get('description', '')) if show in ('scenario', 'campaign'): self.current.findChild(name="maplist").capture(_update_infos) _update_infos()
def show_single(self, show='scenario'): # tutorial """ @param show: string, which type of games to show """ assert show in ('random', 'scenario', 'campaign', 'free_maps') self.hide() # reload since the gui is changed at runtime self.widgets.reload('singleplayermenu') self._switch_current_widget('singleplayermenu', center=True) eventMap = { 'cancel': self.show_main, 'okay': self.start_single, 'showScenario': Callback(self.show_single, show='scenario'), 'showCampaign': Callback(self.show_single, show='campaign'), 'showRandom': Callback(self.show_single, show='random'), 'showMaps': Callback(self.show_single, show='free_maps') } adjust_widget_black_background(self.widgets['singleplayermenu']) # init gui for subcategory if show == 'random': del eventMap['showRandom'] self.current.findChild(name="showRandom").marked = True to_remove = self.current.findChild(name="map_list_area") to_remove.parent.removeChild(to_remove) to_remove = self.current.findChild(name="choose_map_lbl") to_remove.parent.removeChild(to_remove) # need to add some options here (generation algo, size, ... ) else: if show == 'free_maps': del eventMap['showMaps'] self.current.findChild(name="showMaps").marked = True self.current.files, maps_display = SavegameManager.get_maps() elif show == 'campaign': del eventMap['showCampaign'] self.current.findChild(name="showCampaign").marked = True self.current.files, maps_display = SavegameManager.get_campaigns( ) else: # scenario del eventMap['showScenario'] self.current.findChild(name="showScenario").marked = True choosable_locales = ['en', horizons.main.fife.get_locale()] self.current.files, maps_display = SavegameManager.get_available_scenarios( locales=choosable_locales) # get the map files and their display names self.current.distributeInitialData({ 'maplist': maps_display, }) if len(maps_display) > 0: # select first entry self.current.distributeData({ 'maplist': 0, }) if show == 'scenario': # update infos for scenario from horizons.scenario import ScenarioEventHandler, InvalidScenarioFileFormat def _update_infos(): """Fill in infos of selected scenario to label""" try: difficulty = ScenarioEventHandler.get_difficulty_from_file( self.__get_selected_map()) desc = ScenarioEventHandler.get_description_from_file( self.__get_selected_map()) author = ScenarioEventHandler.get_author_from_file( self.__get_selected_map()) except InvalidScenarioFileFormat, e: self.__show_invalid_scenario_file_popup(e) return self.current.findChild( name="map_difficulty" ).text = _("Difficulty: ") + unicode(difficulty) self.current.findChild( name="map_author" ).text = _("Author: ") + unicode(author) self.current.findChild( name="map_desc" ).text = _("Description: ") + unicode(desc) #self.current.findChild(name="map_desc").parent.adaptLayout() elif show == 'campaign': # update infos for campaign def _update_infos(): """Fill in infos of selected campaign to label""" campaign_info = SavegameManager.get_campaign_info( file=self.__get_selected_map()) if not campaign_info: # TODO : an "invalid campaign popup" self.__show_invalid_scenario_file_popup(e) return self.current.findChild( name="map_difficulty" ).text = _("Difficulty: ") + unicode( campaign_info.get('difficulty', '')) self.current.findChild( name="map_author").text = _("Author: ") + unicode( campaign_info.get('author', '')) self.current.findChild( name="map_desc" ).text = _("Description: ") + unicode( campaign_info.get('description', '')) if show in ('scenario', 'campaign'): self.current.findChild( name="maplist").capture(_update_infos) _update_infos()
def start(_command_line_arguments): """Starts the horizons. Will drop you to the main menu. @param _command_line_arguments: options object from optparse.OptionParser. see run_uh.py. """ global debug, preloading, command_line_arguments command_line_arguments = _command_line_arguments # NOTE: globals are designwise the same thing as singletons. they don't look pretty. # here, we only have globals that are either trivial, or only one instance may ever exist. from engine import Fife # handle commandline globals debug = command_line_arguments.debug if command_line_arguments.restore_settings: # just delete the file, Settings ctor will create a new one os.remove(PATHS.USER_CONFIG_FILE) if command_line_arguments.mp_master: try: mpieces = command_line_arguments.mp_master.partition(':') NETWORK.SERVER_ADDRESS = mpieces[0] # only change port if port is specified if mpieces[2]: NETWORK.SERVER_PORT = parse_port(mpieces[2]) except ValueError: print "Error: Invalid syntax in --mp-master commandline option. Port must be a number between 1 and 65535." return False # init fife before mp_bind is parsed, since it's needed there horizons.globals.fife = Fife() if command_line_arguments.generate_minimap: # we've been called as subprocess to generate a map preview from horizons.gui.modules.singleplayermenu import generate_random_minimap generate_random_minimap( *json.loads(command_line_arguments.generate_minimap)) sys.exit(0) if debug: # also True if a specific module is logged (but not 'fife') setup_debug_mode(command_line_arguments) if horizons.globals.fife.get_uh_setting("DebugLog"): set_debug_log(True, startup=True) if command_line_arguments.mp_bind: try: mpieces = command_line_arguments.mp_bind.partition(':') NETWORK.CLIENT_ADDRESS = mpieces[0] horizons.globals.fife.set_uh_setting("NetworkPort", parse_port(mpieces[2])) except ValueError: print "Error: Invalid syntax in --mp-bind commandline option. Port must be a number between 1 and 65535." return False setup_AI_settings(command_line_arguments) # set MAX_TICKS if command_line_arguments.max_ticks: GAME.MAX_TICKS = command_line_arguments.max_ticks preload_lock = threading.Lock() if command_line_arguments.atlas_generation and not command_line_arguments.gui_test and \ VERSION.IS_DEV_VERSION and horizons.globals.fife.get_uh_setting('AtlasesEnabled') \ and horizons.globals.fife.get_uh_setting('AtlasGenerationEnabled'): atlas_loading_thread = None atlas_loading_thread = AtlasLoadingThread(preload_lock) atlas_loading_thread.start() # show info label about atlas generation try: import Tkinter from PIL import Image, ImageTk import time try: window = Tkinter.Tk() # iconify window instead of closing window.protocol("WM_DELETE_WINDOW", window.iconify) window.wm_withdraw() window.attributes("-topmost", 1) window.title("Unknown Horizons") window.maxsize(300, 150) logo = Image.open(horizons.constants.PATHS.UH_LOGO_FILE) res_logo = logo.resize((116, 99), Image.ANTIALIAS) res_logo_image = ImageTk.PhotoImage(res_logo) logo_label = Tkinter.Label(window, image=res_logo_image) logo_label.pack(side="left") label = Tkinter.Label(window, padx=10, text="Generating atlases!") label.pack(side="right") # wait a second to give the thread time to check if a generation is necessary at all time.sleep(1.0) window.deiconify() while atlas_loading_thread.is_alive(): if not window.state() == "iconic": window.attributes("-topmost", 0) window.update() time.sleep(0.1) window.destroy() except Tkinter.TclError: # catch #2298 atlas_loading_thread.join() except ImportError: # tkinter or PIL may be missing atlas_loading_thread.join() # init game parts if not setup_gui_logger(command_line_arguments): return False # GUI tests always run with sound disabled and SDL (so they can run under xvfb). # Needs to be done before engine is initialized. if command_line_arguments.gui_test: horizons.globals.fife.engine.getSettings().setRenderBackend('SDL') horizons.globals.fife.set_fife_setting('PlaySounds', False) ExtScheduler.create_instance(horizons.globals.fife.pump) horizons.globals.fife.init() if not VERSION.IS_DEV_VERSION and horizons.globals.fife.get_uh_setting( 'AtlasesEnabled'): GFX.USE_ATLASES = True PATHS.DB_FILES = PATHS.DB_FILES + (PATHS.ATLAS_DB_PATH, ) horizons.globals.db = _create_main_db() _modules.gui = Gui() SavegameManager.init() horizons.globals.fife.init_animation_loader(GFX.USE_ATLASES) from horizons.entities import Entities Entities.load(horizons.globals.db, load_now=False) # create all references # for preloading game data while in main screen preload_thread = threading.Thread(target=preload_game_data, args=(preload_lock, )) preloading = (preload_thread, preload_lock) # Singleplayer seed needs to be changed before startup. if command_line_arguments.sp_seed: SINGLEPLAYER.SEED = command_line_arguments.sp_seed SINGLEPLAYER.FREEZE_PROTECTION = command_line_arguments.freeze_protection # start something according to commandline parameters startup_worked = True if command_line_arguments.start_dev_map: startup_worked = _start_map( 'development', command_line_arguments.ai_players, force_player_id=command_line_arguments.force_player_id, is_map=True) elif command_line_arguments.start_random_map: startup_worked = _start_random_map( command_line_arguments.ai_players, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.start_specific_random_map is not None: startup_worked = _start_random_map( command_line_arguments.ai_players, seed=command_line_arguments.start_specific_random_map, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.start_map is not None: startup_worked = _start_map( command_line_arguments.start_map, command_line_arguments.ai_players, force_player_id=command_line_arguments.force_player_id, is_map=True) elif command_line_arguments.start_scenario is not None: startup_worked = _start_map( command_line_arguments.start_scenario, 0, True, force_player_id=command_line_arguments.force_player_id) elif command_line_arguments.load_game is not None: startup_worked = _load_cmd_map(command_line_arguments.load_game, command_line_arguments.ai_players, command_line_arguments.force_player_id) elif command_line_arguments.load_quicksave is not None: startup_worked = _load_last_quicksave() elif command_line_arguments.edit_map is not None: startup_worked = edit_map(command_line_arguments.edit_map) elif command_line_arguments.edit_game_map is not None: startup_worked = edit_game_map(command_line_arguments.edit_game_map) elif command_line_arguments.stringpreview: tiny = [i for i in SavegameManager.get_maps()[0] if 'tiny' in i] if not tiny: tiny = SavegameManager.get_map()[0] startup_worked = _start_map( tiny[0], ai_players=0, trader_enabled=False, pirate_enabled=False, force_player_id=command_line_arguments.force_player_id, is_map=True) from development.stringpreviewwidget import StringPreviewWidget __string_previewer = StringPreviewWidget(_modules.session) __string_previewer.show() elif command_line_arguments.create_mp_game: _modules.gui.show_main() _modules.gui.windows.open(_modules.gui.multiplayermenu) _modules.gui.multiplayermenu._create_game() _modules.gui.windows._windows[-1].act() elif command_line_arguments.join_mp_game: _modules.gui.show_main() _modules.gui.windows.open(_modules.gui.multiplayermenu) _modules.gui.multiplayermenu._join_game() else: # no commandline parameter, show main screen # initialize update checker if not command_line_arguments.gui_test: setup_update_check() _modules.gui.show_main() if not command_line_arguments.nopreload: preloading[0].start() if not startup_worked: # don't start main loop if startup failed return False if command_line_arguments.gamespeed is not None: if _modules.session is None: print "You can only set the speed via command line in combination with a game start parameter such as --start-map, etc." return False _modules.session.speed_set(GAME_SPEED.TICKS_PER_SECOND * command_line_arguments.gamespeed) if command_line_arguments.gui_test: from tests.gui import TestRunner TestRunner(horizons.globals.fife, command_line_arguments.gui_test) horizons.globals.fife.run()