コード例 #1
0
ファイル: main.py プロジェクト: zamronypj/unknown-horizons
def setup_gui_logger(command_line_arguments):
	"""
	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
	return True
コード例 #2
0
ファイル: main.py プロジェクト: JamesOravec/unknown-horizons
def setup_gui_logger(command_line_arguments):
	"""
	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:
			import tests.gui.logger
			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
	return True
コード例 #3
0
ファイル: main.py プロジェクト: aviler/unknown-horizons
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()
コード例 #4
0
ファイル: main.py プロジェクト: Rareson/unknown-horizons
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()
コード例 #5
0
ファイル: main.py プロジェクト: zamronypj/unknown-horizons
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
コード例 #6
0
ファイル: main.py プロジェクト: acieroid/unknown-horizons
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()
コード例 #7
0
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()
コード例 #8
0
ファイル: main.py プロジェクト: squiddy/unknown-horizons
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()
コード例 #9
0
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

	# 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_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()