Ejemplo n.º 1
0
	def _upgrade(self):
		# fix import loop
		from horizons.savegamemanager import SavegameManager
		metadata = SavegameManager.get_metadata(self.original_path)
		rev = metadata['savegamerev']
		if rev == 0: # not a regular savegame, usually a map
			self.final_path = self.original_path
		elif rev == VERSION.SAVEGAMEREVISION: # the current version
			self.final_path = self.original_path
		else: # upgrade
			self.using_temp = True
			handle, self.final_path = tempfile.mkstemp(prefix='uh-savegame.' + os.path.basename(os.path.splitext(self.original_path)[0]) + '.', suffix='.sqlite')
			os.close(handle)
			shutil.copyfile(self.original_path, self.final_path)
			db = DbReader(self.final_path)

			if rev < 49:
				self._upgrade_to_rev49(db)
			if rev < 50:
				self._upgrade_to_rev50(db)
			if rev < 51:
				self._upgrade_to_rev51(db)
			if rev < 52:
				self._upgrade_to_rev52(db)


			db.close()
Ejemplo n.º 2
0
	def _upgrade(self):
		# fix import loop
		from horizons.savegamemanager import SavegameManager
		metadata = SavegameManager.get_metadata(self.original_path)
		rev = metadata['savegamerev']
		if rev == 0: # not a regular savegame, usually a map
			self.final_path = self.original_path
		elif rev == VERSION.SAVEGAMEREVISION: # the current version
			self.final_path = self.original_path
		else: # upgrade
			self.using_temp = True
			handle, self.final_path = tempfile.mkstemp(prefix='uh-savegame.' + os.path.basename(os.path.splitext(self.original_path)[0]) + '.', suffix='.sqlite')
			os.close(handle)
			shutil.copyfile(self.original_path, self.final_path)
			db = DbReader(self.final_path)
			db('BEGIN TRANSACTION')

			if rev < 49:
				self._upgrade_to_rev49(db)
			if rev < 50:
				self._upgrade_to_rev50(db)
			if rev < 51:
				self._upgrade_to_rev51(db)
			if rev < 52:
				self._upgrade_to_rev52(db)
			if rev < 53:
				self._upgrade_to_rev53(db)
			if rev < 54:
				self._upgrade_to_rev54(db)
			if rev < 55:
				self._upgrade_to_rev55(db)
			if rev < 56:
				self._upgrade_to_rev56(db)
			if rev < 57:
				self._upgrade_to_rev57(db)
			if rev < 58:
				self._upgrade_to_rev58(db)
			if rev < 59:
				self._upgrade_to_rev59(db)
			if rev < 60:
				self._upgrade_to_rev60(db)
			if rev < 61:
				self._upgrade_to_rev61(db)
			if rev < 62:
				self._upgrade_to_rev62(db)
			if rev < 63:
				self._upgrade_to_rev63(db)
			if rev < 64:
				self._upgrade_to_rev64(db)
			if rev < 65:
				self._upgrade_to_rev65(db)
			if rev < 66:
				self._upgrade_to_rev66(db)
			if rev < 67:
				self._upgrade_to_rev67(db)

			db('COMMIT')
			db.close()
Ejemplo n.º 3
0
        def tmp_show_details():
            """Fetches details of selected savegame and displays it"""
            box = gui.findChild(name="savegamedetails_box")
            old_label = box.findChild(name="savegamedetails_lbl")
            if old_label is not None:
                box.removeChild(old_label)
            map_file = None
            try:
                map_file = map_files[gui.collectData(savegamelist)]
            except IndexError:
                # this was a click in the savegame list, but not on an element
                # it happens when the savegame list is empty
                return
            savegame_info = SavegameManager.get_metadata(map_file)
            details_label = pychan.widgets.Label(min_size=(140, 0), max_size=(140, 290), wrap_text=True)
            details_label.name = "savegamedetails_lbl"
            details_label.text = u""
            if savegame_info["timestamp"] == -1:
                details_label.text += _("Unknown savedate\n")
            else:
                details_label.text += _("Saved at %s\n") % time.strftime(
                    "%H:%M, %A, %B %d", time.localtime(savegame_info["timestamp"])
                )
            counter = savegame_info["savecounter"]
            # N_ takes care of plural forms for different languages
            details_label.text += N_("Saved %(counter)d time\n", "Saved %(counter)d times\n", counter) % {
                "counter": counter
            }
            details_label.stylize("book_t")

            from horizons.constants import VERSION

            try:
                if savegame_info["savegamerev"] == VERSION.SAVEGAMEREVISION:
                    details_label.text += _("Savegame ver. %d") % (savegame_info["savegamerev"])
                else:
                    details_label.text += _("WARNING: Incompatible ver. %(ver)d!\nNeed ver. %(need)d!") % {
                        "ver": savegame_info["savegamerev"],
                        "need": VERSION.SAVEGAMEREVISION,
                    }
            except KeyError:
                details_label.text += _("INCOMPATIBLE VERSION\n")

            box.addChild(details_label)

            """
			if savegame_info['screenshot']:
				fd, filename = tempfile.mkstemp()
				os.fdopen(fd, "w").write(savegame_info['screenshot'])
				box.addChild( pychan.widgets.Icon(image=filename) )
			"""

            gui.adaptLayout()
Ejemplo n.º 4
0
	def load(self, savegame, players, is_scenario=False, campaign={}):
		"""Loads a map.
		@param savegame: path to the savegame database.
		@param players: iterable of dictionaries containing id, name, color and local
		@param is_scenario: Bool whether the loaded map is a scenario or not
		"""
		if is_scenario:
			# savegame is a yaml file, that contains reference to actual map file
			self.scenario_eventhandler = ScenarioEventHandler(self, savegame)
			savegame = os.path.join(SavegameManager.maps_dir, \
			                        self.scenario_eventhandler.get_map_file())
		self.campaign = campaign

		self.log.debug("Session: Loading from %s", savegame)
		savegame_db = SavegameAccessor(savegame) # Initialize new dbreader
		try:
			# load how often the game has been saved (used to know the difference between
			# a loaded and a new game)
			self.savecounter = SavegameManager.get_metadata(savegame)['savecounter']
		except KeyError:
			self.savecounter = 0

		self.world = World(self) # Load horizons.world module (check horizons/world/__init__.py)
		self.world._init(savegame_db)
		self.view.load(savegame_db) # load view
		if not self.is_game_loaded():
			# NOTE: this must be sorted before iteration, cause there is no defined order for
			#       iterating a dict, and it must happen in the same order for mp games.
			for i in sorted(players):
				self.world.setup_player(i['id'], i['name'], i['color'], i['local'])
			center = self.world.init_new_world()
			self.view.center(center[0], center[1])
		else:
			# try to load scenario data
			self.scenario_eventhandler.load(savegame_db)
		self.manager.load(savegame_db) # load the manager (there might me old scheduled ticks).
		self.ingame_gui.load(savegame_db) # load the old gui positions and stuff

		for instance_id in savegame_db("SELECT id FROM selected WHERE `group` IS NULL"): # Set old selected instance
			obj = WorldObject.get_object_by_id(instance_id[0])
			self.selected_instances.add(obj)
			obj.select()
		for group in xrange(len(self.selection_groups)): # load user defined unit groups
			for instance_id in savegame_db("SELECT id FROM selected WHERE `group` = ?", group):
				self.selection_groups[group].add(WorldObject.get_object_by_id(instance_id[0]))

		# cursor has to be inited last, else player interacts with a not inited world with it.
		self.cursor = SelectionTool(self)
		self.cursor.apply_select() # Set cursor correctly, menus might need to be opened.

		assert hasattr(self.world, "player"), 'Error: there is no human player'
		"""
Ejemplo n.º 5
0
		def tmp_show_details():
			"""Fetches details of selected savegame and displays it"""
			box = gui.findChild(name="savegamedetails_box")
			old_label = box.findChild(name="savegamedetails_lbl")
			if old_label is not None:
				box.removeChild(old_label)
			map_file = None
			try:
				map_file = map_files[gui.collectData(savegamelist)]
			except IndexError:
				# this was a click in the savegame list, but not on an element
				# it happens when the savegame list is empty
				return
			savegame_info = SavegameManager.get_metadata(map_file)
			details_label = pychan.widgets.Label(min_size=(140, 0), max_size=(140, 290), wrap_text=True)
			details_label.name = "savegamedetails_lbl"
			details_label.text = u""
			if savegame_info['timestamp'] == -1:
				details_label.text += _("Unknown savedate\n")
			else:
				details_label.text += _("Saved at %s\n") % \
										time.strftime(_("%H:%M, %A, %B %d"), time.localtime(savegame_info['timestamp']))
			counter = savegame_info['savecounter']
			# N_ takes care of plural forms for different languages
			details_label.text += N_("Saved %(counter)d time\n", \
			                         "Saved %(counter)d times\n", \
			                         counter) % {'counter':counter}
			details_label.stylize('book_t')

			from horizons.constants import VERSION
			try:
				if savegame_info['savegamerev'] == VERSION.SAVEGAMEREVISION:
					details_label.text += _("Savegame ver. %d") % ( savegame_info['savegamerev'] )
				else:
					details_label.text += _("WARNING: Incompatible ver. %(ver)d!\nNeed ver. %(need)d!") \
					             % {'ver' : savegame_info['savegamerev'], 'need' : VERSION.SAVEGAMEREVISION}
			except KeyError:
				details_label.text += _("INCOMPATIBLE VERSION\n")


			box.addChild( details_label )

			"""
			if savegame_info['screenshot']:
				fd, filename = tempfile.mkstemp()
				os.fdopen(fd, "w").write(savegame_info['screenshot'])
				box.addChild( pychan.widgets.Icon(image=filename) )
			"""

			gui.adaptLayout()
Ejemplo n.º 6
0
		def tmp_show_details():
			"""Fetches details of selected savegame and displays it"""
			box = gui.findChild(name="savegamedetails_box")
			old_label = box.findChild(name="savegamedetails_lbl")
			if old_label is not None:
				box.removeChild(old_label)
			savegame_info = SavegameManager.get_metadata(map_files[gui.collectData(savegamelist)])
			details_label = pychan.widgets.Label(min_size=(140, 0), max_size=(140, 290), wrap_text=True)
			details_label.name = "savegamedetails_lbl"
			details_label.text = u""
			if savegame_info['timestamp'] == -1:
				details_label.text += _("Unknown savedate\n")
			else:
				details_label.text += _("Saved at %s\n") % \
										time.strftime(_("%H:%M, %A, %B %d"), time.localtime(savegame_info['timestamp']))
			counter = savegame_info['savecounter']
			# N_ takes care of plural forms for different languages
			details_label.text += N_("Saved %(counter)d time\n", \
			                         "Saved %(counter)d times\n", \
			                         counter) % {'counter':counter}
			details_label.stylize('book_t')

			from horizons.constants import VERSION
			try:
				if savegame_info['savegamerev'] == VERSION.SAVEGAMEREVISION:
					details_label.text += _("Savegame ver. %d") % ( savegame_info['savegamerev'] )
				else:
					details_label.text += _("WARNING: Incompatible ver. %(ver)d!\nNeed ver. %(need)d!") \
					             % {'ver' : savegame_info['savegamerev'], 'need' : VERSION.SAVEGAMEREVISION}
			except KeyError:
				details_label.text += _("INCOMPATIBLE VERSION\n")


			box.addChild( details_label )

			"""
			if savegame_info['screenshot']:
				fd, filename = tempfile.mkstemp()
				os.fdopen(fd, "w").write(savegame_info['screenshot'])
				box.addChild( pychan.widgets.Icon(image=filename) )
			"""

			gui.adaptLayout()
Ejemplo n.º 7
0
		def tmp_show_details():
			"""Fetches details of selected savegame and displays it"""
			box = gui.findChild(name="savegamedetails_box")
			old_label = box.findChild(name="savegamedetails_lbl")
			if old_label is not None:
				box.removeChild(old_label)
			savegame_info = SavegameManager.get_metadata(map_files[gui.collectData(savegamelist)])
			details_label = pychan.widgets.Label(min_size=(140, 0), max_size=(140, 290), wrap_text=True)
			details_label.name = "savegamedetails_lbl"
			details_label.text = u""
			if savegame_info['timestamp'] == -1:
				details_label.text += _("Unknown savedate\n")
			else:
				details_label.text += _("Saved at %s\n") % \
										time.strftime(_("%H:%M, %A, %B %d"), time.localtime(savegame_info['timestamp']))
			if savegame_info['savecounter'] == 1:
				details_label.text += _("Saved 1 time\n")
			else:
				details_label.text += _("Saved %d times\n") % savegame_info['savecounter']
			details_label.stylize('book_t')

			from horizons.constants import VERSION
			try:
				if savegame_info['savegamerev'] == VERSION.SAVEGAMEREVISION:
					details_label.text += _("Savegame ver. %d") % ( savegame_info['savegamerev'] )
				else:
					details_label.text += _("WARNING: Incompatible ver. %(ver)d!\nNeed ver. %(need)d!") \
					             % {'ver' : savegame_info['savegamerev'], 'need' : VERSION.SAVEGAMEREVISION}
			except KeyError:
				details_label.text += _("INCOMPATIBLE VERSION\n")


			box.addChild( details_label )

			"""
			if savegame_info['screenshot']:
				fd, filename = tempfile.mkstemp()
				os.fdopen(fd, "w").write(savegame_info['screenshot'])
				box.addChild( pychan.widgets.Icon(image=filename) )
			"""

			gui.adaptLayout()
Ejemplo n.º 8
0
	def _upgrade(self):
		# fix import loop
		from horizons.savegamemanager import SavegameManager
		metadata = SavegameManager.get_metadata(self.original_path)
		rev = metadata['savegamerev']

		if rev < VERSION.SAVEGAMEREVISION:
			if not SavegameUpgrader.can_upgrade(rev):
				raise SavegameTooOld(revision=rev)

			self.log.warning('Discovered old savegame file, auto-upgrading: {} -> {}'
						     .format(rev, VERSION.SAVEGAMEREVISION))
			db = DbReader(self.final_path)
			db('BEGIN TRANSACTION')

			# placeholder for future upgrade calls
			if rev < 77:
				self._upgrade_to_rev77(db)

			db('COMMIT')
			db.close()
Ejemplo n.º 9
0
		def tmp_show_details():
			"""Fetches details of selected savegame and displays it"""
			box = gui.findChild(name="savegamedetails_box")
			old_label = box.findChild(name="savegamedetails_lbl")
			if old_label is not None:
				box.removeChild(old_label)
			savegame_info = SavegameManager.get_metadata(map_files[gui.collectData(savegamelist)])
			details_label = pychan.widgets.Label(min_size=(140, 0), max_size=(140, 290), wrap_text=True)
			details_label.name = "savegamedetails_lbl"
			details_label.text = u""
			if savegame_info['timestamp'] == -1:
				details_label.text += "Unknown savedate\n"
			else:
				details_label.text += "Saved at %s\n" % \
										 time.strftime("%H:%M, %A, %B %d", time.localtime(savegame_info['timestamp']))
			details_label.text += "Saved %d time%s\n" % (savegame_info['savecounter'], \
			                                             's' if savegame_info['savecounter'] > 1 else '')

			from horizons.constants import VERSION
			try:
				if savegame_info['savegamerev'] == VERSION.SAVEGAMEREVISION:
					details_label.text += u"Savegame ver. %d" % ( savegame_info['savegamerev'] )
				else:
					details_label.text += u"WARNING: Incompatible ver. %d!\nNeed ver. %d!" \
					             % (savegame_info['savegamerev'], VERSION.SAVEGAMEREVISION)
			except KeyError:
				details_label.text += u"INCOMPATIBlE VERSION\n"


			box.addChild( details_label )

			"""
			if savegame_info['screenshot']:
				fd, filename = tempfile.mkstemp()
				os.fdopen(fd, "w").write(savegame_info['screenshot'])
				box.addChild( pychan.widgets.Icon(image=filename) )
			"""

			gui.adaptLayout()
Ejemplo n.º 10
0
	def load(self, savegame, players, trader_enabled, pirate_enabled,
	         natural_resource_multiplier, is_scenario=False, campaign=None,
	         force_player_id=None, disasters_enabled=True, is_multiplayer=False):
		"""Loads a map. Key method for starting a game.
		@param savegame: path to the savegame database.
		@param players: iterable of dictionaries containing id, name, color, local, ai, and difficulty
		@param is_scenario: Bool whether the loaded map is a scenario or not
		@param force_player_id: the worldid of the selected human player or default if None (debug option)
		"""
		"""
		TUTORIAL: Here you see how the vital game elements (and some random things that are also required)
		are initialised.
		"""
		if is_scenario:
			# savegame is a yaml file, that contains reference to actual map file
			self.scenario_eventhandler = ScenarioEventHandler(self, savegame)
			# scenario maps can be normal maps or scenario maps:
			map_filename = self.scenario_eventhandler.get_map_file()
			savegame = os.path.join(SavegameManager.scenario_maps_dir, map_filename)
			if not os.path.exists(savegame):
				savegame = os.path.join(SavegameManager.maps_dir, map_filename)
		self.campaign = {} if not campaign else campaign

		self.log.debug("Session: Loading from %s", savegame)
		savegame_db = SavegameAccessor(savegame) # Initialize new dbreader
		savegame_data = SavegameManager.get_metadata(savegame)

		# load how often the game has been saved (used to know the difference between
		# a loaded and a new game)
		self.savecounter = savegame_data.get('savecounter', 0)

		if savegame_data.get('rng_state', None):
			rng_state_list = json.loads( savegame_data['rng_state'] )
			# json treats tuples as lists, but we need tuples here, so convert back
			def rec_list_to_tuple(x):
				if isinstance(x, list):
					return tuple( rec_list_to_tuple(i) for i in x )
				else:
					return x
			rng_state_tuple = rec_list_to_tuple(rng_state_list)
			# changing the rng is safe for mp, as all players have to have the same map
			self.random.setstate( rng_state_tuple )

		self.world = World(self) # Load horizons.world module (check horizons/world/__init__.py)
		self.world._init(savegame_db, force_player_id, disasters_enabled=disasters_enabled)
		self.view.load(savegame_db) # load view
		if not self.is_game_loaded():
			# NOTE: this must be sorted before iteration, cause there is no defined order for
			#       iterating a dict, and it must happen in the same order for mp games.
			for i in sorted(players, lambda p1, p2: cmp(p1['id'], p2['id'])):
				self.world.setup_player(i['id'], i['name'], i['color'], i['clientid'] if is_multiplayer else None, i['local'], i['ai'], i['difficulty'])
			self.world.set_forced_player(force_player_id)
			center = self.world.init_new_world(trader_enabled, pirate_enabled, natural_resource_multiplier)
			self.view.center(center[0], center[1])
		else:
			# try to load scenario data
			self.scenario_eventhandler.load(savegame_db)
		self.manager.load(savegame_db) # load the manager (there might me old scheduled ticks).
		self.world.init_fish_indexer() # now the fish should exist
		if self.is_game_loaded():
			LastActivePlayerSettlementManager().load(savegame_db) # before ingamegui
		self.ingame_gui.load(savegame_db) # load the old gui positions and stuff

		for instance_id in savegame_db("SELECT id FROM selected WHERE `group` IS NULL"): # Set old selected instance
			obj = WorldObject.get_object_by_id(instance_id[0])
			self.selected_instances.add(obj)
			obj.get_component(SelectableComponent).select()
		for group in xrange(len(self.selection_groups)): # load user defined unit groups
			for instance_id in savegame_db("SELECT id FROM selected WHERE `group` = ?", group):
				self.selection_groups[group].add(WorldObject.get_object_by_id(instance_id[0]))

		# cursor has to be inited last, else player interacts with a not inited world with it.
		self.current_cursor = 'default'
		self.cursor = SelectionTool(self)
		# Set cursor correctly, menus might need to be opened.
		# Open menus later; they may need unit data not yet inited
		self.cursor.apply_select()

		Scheduler().before_ticking()
		savegame_db.close()

		assert hasattr(self.world, "player"), 'Error: there is no human player'
		"""
Ejemplo n.º 11
0
		def tmp_show_details():
			"""Fetches details of selected savegame and displays it"""
			gui.findChild(name="screenshot").image = None
			box = gui.findChild(name="savegamedetails_box")
			old_label = box.findChild(name="savegamedetails_lbl")
			if old_label is not None:
				box.removeChild(old_label)
			map_file = None
			map_file_index = gui.collectData(savegamelist)
			if map_file_index == -1:
				return
			try:
				map_file = map_files[map_file_index]
			except IndexError:
				# this was a click in the savegame list, but not on an element
				# it happens when the savegame list is empty
				return
			savegame_info = SavegameManager.get_metadata(map_file)

			# screenshot (len can be 0 if save failed in a weird way)
			if 'screenshot' in savegame_info and \
			   savegame_info['screenshot'] is not None and \
			   len(savegame_info['screenshot']) > 0:
				# try to find a writeable location, that is accessible via relative paths
				# (required by fife)
				fd, filename = tempfile.mkstemp()
				try:
					path_rel = os.path.relpath(filename)
				except ValueError: # the relative path sometimes doesn't exist on win
					os.close(fd)
					os.unlink(filename)
					# try again in the current dir, it's often writable
					fd, filename = tempfile.mkstemp(dir=os.curdir)
					try:
						path_rel = os.path.relpath(filename)
					except ValueError:
						fd, filename = None, None

				if fd:
					with os.fdopen(fd, "w") as f:
						f.write(savegame_info['screenshot'])
					# fife only supports relative paths
					gui.findChild(name="screenshot").image = path_rel
					os.unlink(filename)

			# savegamedetails
			details_label = pychan.widgets.Label(min_size=(290, 0), max_size=(290, 290), wrap_text=True)
			details_label.name = "savegamedetails_lbl"
			details_label.text = u""
			if savegame_info['timestamp'] == -1:
				details_label.text += _("Unknown savedate")
			else:
				#xgettext:python-format
				details_label.text += _("Saved at {time}").format(
				                         time=time.strftime("%c",
				                         time.localtime(savegame_info['timestamp'])).decode('utf-8'))
			details_label.text += u'\n'
			counter = savegame_info['savecounter']
			# N_ takes care of plural forms for different languages
			#xgettext:python-format
			details_label.text += N_("Saved {amount} time",
			                         "Saved {amount} times",
			                         counter).format(amount=counter)
			details_label.text += u'\n'
			details_label.stylize('book_t')

			from horizons.constants import VERSION
			try:
				#xgettext:python-format
				details_label.text += _("Savegame version {version}").format(
				                         version=savegame_info['savegamerev'])
				if savegame_info['savegamerev'] != VERSION.SAVEGAMEREVISION:
					#xgettext:python-format
					details_label.text += u" " + _("(potentially incompatible)")
			except KeyError:
				# this should only happen for very old savegames, so having this unfriendly
				# error is ok (savegame is quite certainly fully unusable).
				details_label.text += _("Incompatible version")


			box.addChild( details_label )


			gui.adaptLayout()
Ejemplo n.º 12
0
        def tmp_show_details():
            """Fetches details of selected savegame and displays it"""
            gui.findChild(name="screenshot").image = None
            map_file = None
            map_file_index = gui.collectData(savegamelist)

            savegame_details_box = gui.findChild(name="savegame_details")
            savegame_details_parent = savegame_details_box.parent
            if map_file_index == -1:
                if (Fife.getVersion() >= (0, 4, 0)):
                    savegame_details_parent.hideChild(savegame_details_box)
                else:
                    if savegame_details_box not in savegame_details_parent.hidden_children:
                        savegame_details_parent.hideChild(savegame_details_box)
                return
            else:
                savegame_details_parent.showChild(savegame_details_box)
            try:
                map_file = map_files[map_file_index]
            except IndexError:
                # this was a click in the savegame list, but not on an element
                # it happens when the savegame list is empty
                return
            savegame_info = SavegameManager.get_metadata(map_file)

            if savegame_info.get('screenshot'):
                # try to find a writable location, that is accessible via relative paths
                # (required by fife)
                fd, filename = tempfile.mkstemp()
                try:
                    path_rel = os.path.relpath(filename)
                except ValueError:  # the relative path sometimes doesn't exist on win
                    os.close(fd)
                    os.unlink(filename)
                    # try again in the current dir, it's often writable
                    fd, filename = tempfile.mkstemp(dir=os.curdir)
                    try:
                        path_rel = os.path.relpath(filename)
                    except ValueError:
                        fd, filename = None, None

                if fd:
                    with os.fdopen(fd, "w") as f:
                        f.write(savegame_info['screenshot'])
                    # fife only supports relative paths
                    gui.findChild(name="screenshot").image = path_rel
                    os.unlink(filename)

            # savegamedetails
            details_label = gui.findChild(name="savegamedetails_lbl")
            details_label.text = u""
            if savegame_info['timestamp'] == -1:
                details_label.text += T("Unknown savedate")
            else:
                savetime = time.strftime(
                    "%c", time.localtime(savegame_info['timestamp']))
                details_label.text += T("Saved at {time}").format(
                    time=savetime.decode('utf-8'))
            details_label.text += u'\n'
            counter = savegame_info['savecounter']
            # NT takes care of plural forms for different languages
            details_label.text += NT("Saved {amount} time",
                                     "Saved {amount} times",
                                     counter).format(amount=counter)
            details_label.text += u'\n'

            from horizons.constants import VERSION
            try:
                details_label.text += T("Savegame version {version}").format(
                    version=savegame_info['savegamerev'])
                if savegame_info['savegamerev'] != VERSION.SAVEGAMEREVISION:
                    if not SavegameUpgrader.can_upgrade(
                            savegame_info['savegamerev']):
                        details_label.text += u" " + T(
                            "(probably incompatible)")
            except KeyError:
                # this should only happen for very old savegames, so having this unfriendly
                # error is ok (savegame is quite certainly fully unusable).
                details_label.text += u" " + T("Incompatible version")

            gui.adaptLayout()
Ejemplo n.º 13
0
	def load(self, options):
		"""Loads a map. Key method for starting a game."""
		"""
		TUTORIAL: Here you see how the vital game elements (and some random things that are also required)
		are initialized.
		"""
		if options.is_scenario:
			# game_identifier is a yaml file, that contains reference to actual map file
			self.scenario_eventhandler = ScenarioEventHandler(self, options.game_identifier)
			# scenario maps can be normal maps or scenario maps:
			map_filename = self.scenario_eventhandler.get_map_file()
			options.game_identifier = os.path.join(SavegameManager.scenario_maps_dir, map_filename)
			if not os.path.exists(options.game_identifier):
				options.game_identifier = os.path.join(SavegameManager.maps_dir, map_filename)
			options.is_map = True

		self.log.debug("Session: Loading from %s", options.game_identifier)
		savegame_db = SavegameAccessor(options.game_identifier, options.is_map, options) # Initialize new dbreader
		savegame_data = SavegameManager.get_metadata(savegame_db.db_path)
		self.view.resize_layers(savegame_db)

		# load how often the game has been saved (used to know the difference between
		# a loaded and a new game)
		self.savecounter = savegame_data.get('savecounter', 0)

		if savegame_data.get('rng_state', None):
			rng_state_list = json.loads(savegame_data['rng_state'])
			# json treats tuples as lists, but we need tuples here, so convert back
			def rec_list_to_tuple(x):
				if isinstance(x, list):
					return tuple(rec_list_to_tuple(i) for i in x)
				else:
					return x
			rng_state_tuple = rec_list_to_tuple(rng_state_list)
			# changing the rng is safe for mp, as all players have to have the same map
			self.random.setstate(rng_state_tuple)

		LoadingProgress.broadcast(self, 'session_create_world')
		self.world = World(self) # Load horizons.world module (check horizons/world/__init__.py)
		self.world._init(savegame_db, options.force_player_id, disasters_enabled=options.disasters_enabled)
		self.view.load(savegame_db, self.world) # load view
		if not self.is_game_loaded():
			options.init_new_world(self)
		else:
			# try to load scenario data
			self.scenario_eventhandler.load(savegame_db)
		self.manager.load(savegame_db) # load the manager (there might be old scheduled ticks).
		LoadingProgress.broadcast(self, "session_index_fish")
		self.world.init_fish_indexer() # now the fish should exist

		# load the old gui positions and stuff
		# Do this before loading selections, they need the minimap setup
		LoadingProgress.broadcast(self, "session_load_gui")
		self.ingame_gui = self._ingame_gui_class(self)
		self.ingame_gui.load(savegame_db)

		Scheduler().before_ticking()
		savegame_db.close()

		assert hasattr(self.world, "player"), 'Error: there is no human player'
		LoadingProgress.broadcast(self, "session_finish")
		"""
    def _upgrade(self):
        # fix import loop
        from horizons.savegamemanager import SavegameManager

        metadata = SavegameManager.get_metadata(self.original_path)
        rev = metadata["savegamerev"]
        if rev == 0:  # not a regular savegame, usually a map
            self.final_path = self.original_path
        elif rev == VERSION.SAVEGAMEREVISION:  # the current version
            self.final_path = self.original_path
        else:  # upgrade
            self.log.warning("Discovered old savegame file, auto-upgrading: %s -> %s" % (rev, VERSION.SAVEGAMEREVISION))
            self.using_temp = True
            handle, self.final_path = tempfile.mkstemp(
                prefix="uh-savegame." + os.path.basename(os.path.splitext(self.original_path)[0]) + ".",
                suffix=".sqlite",
            )
            os.close(handle)
            shutil.copyfile(self.original_path, self.final_path)
            db = DbReader(self.final_path)
            db("BEGIN TRANSACTION")

            if rev < 49:
                self._upgrade_to_rev49(db)
            if rev < 50:
                self._upgrade_to_rev50(db)
            if rev < 51:
                self._upgrade_to_rev51(db)
            if rev < 52:
                self._upgrade_to_rev52(db)
            if rev < 53:
                self._upgrade_to_rev53(db)
            if rev < 54:
                self._upgrade_to_rev54(db)
            if rev < 55:
                self._upgrade_to_rev55(db)
            if rev < 56:
                self._upgrade_to_rev56(db)
            if rev < 57:
                self._upgrade_to_rev57(db)
            if rev < 58:
                self._upgrade_to_rev58(db)
            if rev < 59:
                self._upgrade_to_rev59(db)
            if rev < 60:
                self._upgrade_to_rev60(db)
            if rev < 61:
                self._upgrade_to_rev61(db)
            if rev < 62:
                self._upgrade_to_rev62(db)
            if rev < 63:
                self._upgrade_to_rev63(db)
            if rev < 64:
                self._upgrade_to_rev64(db)
            if rev < 65:
                self._upgrade_to_rev65(db)
            if rev < 66:
                self._upgrade_to_rev66(db)
            if rev < 67:
                self._upgrade_to_rev67(db)
            if rev < 68:
                self._upgrade_to_rev68(db)
            if rev < 69:
                self._upgrade_to_rev69(db)
            if rev < 70:
                self._upgrade_to_rev70(db)
            if rev < 71:
                self._upgrade_to_rev71(db)
            if rev < 72:
                self._upgrade_to_rev72(db)
            if 70 < rev < 73:
                self._upgrade_to_rev73(db)

            db("COMMIT")
            db.close()
Ejemplo n.º 15
0
	def load(self, options):
		"""Loads a map. Key method for starting a game."""
		"""
		TUTORIAL: Here you see how the vital game elements (and some random things that are also required)
		are initialised.
		"""
		if options.is_scenario:
			# game_identifier is a yaml file, that contains reference to actual map file
			self.scenario_eventhandler = ScenarioEventHandler(self, options.game_identifier)
			# scenario maps can be normal maps or scenario maps:
			map_filename = self.scenario_eventhandler.get_map_file()
			options.game_identifier = os.path.join(SavegameManager.scenario_maps_dir, map_filename)
			if not os.path.exists(options.game_identifier):
				options.game_identifier = os.path.join(SavegameManager.maps_dir, map_filename)
			options.is_map = True

		self.log.debug("Session: Loading from %s", options.game_identifier)
		savegame_db = SavegameAccessor(options.game_identifier, options.is_map) # Initialize new dbreader
		savegame_data = SavegameManager.get_metadata(savegame_db.db_path)
		self.view.resize_layers(savegame_db)

		# load how often the game has been saved (used to know the difference between
		# a loaded and a new game)
		self.savecounter = savegame_data.get('savecounter', 0)

		if savegame_data.get('rng_state', None):
			rng_state_list = json.loads(savegame_data['rng_state'])
			# json treats tuples as lists, but we need tuples here, so convert back
			def rec_list_to_tuple(x):
				if isinstance(x, list):
					return tuple(rec_list_to_tuple(i) for i in x)
				else:
					return x
			rng_state_tuple = rec_list_to_tuple(rng_state_list)
			# changing the rng is safe for mp, as all players have to have the same map
			self.random.setstate(rng_state_tuple)

		self.world = World(self) # Load horizons.world module (check horizons/world/__init__.py)
		self.world._init(savegame_db, options.force_player_id, disasters_enabled=options.disasters_enabled)
		self.view.load(savegame_db) # load view
		if not self.is_game_loaded():
			options.init_new_world(self)
		else:
			# try to load scenario data
			self.scenario_eventhandler.load(savegame_db)
		self.manager.load(savegame_db) # load the manager (there might me old scheduled ticks).
		self.world.init_fish_indexer() # now the fish should exist
		if self.is_game_loaded():
			LastActivePlayerSettlementManager().load(savegame_db) # before ingamegui
		self.ingame_gui.load(savegame_db) # load the old gui positions and stuff

		for instance_id in savegame_db("SELECT id FROM selected WHERE `group` IS NULL"): # Set old selected instance
			obj = WorldObject.get_object_by_id(instance_id[0])
			self.selected_instances.add(obj)
			obj.get_component(SelectableComponent).select()
		for group in xrange(len(self.selection_groups)): # load user defined unit groups
			for instance_id in savegame_db("SELECT id FROM selected WHERE `group` = ?", group):
				self.selection_groups[group].add(WorldObject.get_object_by_id(instance_id[0]))

		# cursor has to be inited last, else player interacts with a not inited world with it.
		self.current_cursor = 'default'
		self.cursor = SelectionTool(self)
		# Set cursor correctly, menus might need to be opened.
		# Open menus later; they may need unit data not yet inited
		self.cursor.apply_select()

		Scheduler().before_ticking()
		savegame_db.close()

		assert hasattr(self.world, "player"), 'Error: there is no human player'
		"""
Ejemplo n.º 16
0
    def load(self, options):
        """Loads a map. Key method for starting a game."""
        """
		TUTORIAL: Here you see how the vital game elements (and some random things that are also required)
		are initialised.
		"""
        if options.is_scenario:
            # game_identifier is a yaml file, that contains reference to actual map file
            self.scenario_eventhandler = ScenarioEventHandler(
                self, options.game_identifier)
            # scenario maps can be normal maps or scenario maps:
            map_filename = self.scenario_eventhandler.get_map_file()
            options.game_identifier = os.path.join(
                SavegameManager.scenario_maps_dir, map_filename)
            if not os.path.exists(options.game_identifier):
                options.game_identifier = os.path.join(
                    SavegameManager.maps_dir, map_filename)
            options.is_map = True

        self.log.debug("Session: Loading from %s", options.game_identifier)
        savegame_db = SavegameAccessor(
            options.game_identifier, options.is_map)  # Initialize new dbreader
        savegame_data = SavegameManager.get_metadata(savegame_db.db_path)
        self.view.resize_layers(savegame_db)

        # load how often the game has been saved (used to know the difference between
        # a loaded and a new game)
        self.savecounter = savegame_data.get('savecounter', 0)

        if savegame_data.get('rng_state', None):
            rng_state_list = json.loads(savegame_data['rng_state'])

            # json treats tuples as lists, but we need tuples here, so convert back
            def rec_list_to_tuple(x):
                if isinstance(x, list):
                    return tuple(rec_list_to_tuple(i) for i in x)
                else:
                    return x

            rng_state_tuple = rec_list_to_tuple(rng_state_list)
            # changing the rng is safe for mp, as all players have to have the same map
            self.random.setstate(rng_state_tuple)

        self.world = World(
            self
        )  # Load horizons.world module (check horizons/world/__init__.py)
        self.world._init(savegame_db,
                         options.force_player_id,
                         disasters_enabled=options.disasters_enabled)
        self.view.load(savegame_db)  # load view
        if not self.is_game_loaded():
            options.init_new_world(self)
        else:
            # try to load scenario data
            self.scenario_eventhandler.load(savegame_db)
        self.manager.load(
            savegame_db
        )  # load the manager (there might me old scheduled ticks).
        self.world.init_fish_indexer()  # now the fish should exist
        if self.is_game_loaded():
            LastActivePlayerSettlementManager().load(
                savegame_db)  # before ingamegui
        self.ingame_gui.load(
            savegame_db)  # load the old gui positions and stuff

        for instance_id in savegame_db(
                "SELECT id FROM selected WHERE `group` IS NULL"
        ):  # Set old selected instance
            obj = WorldObject.get_object_by_id(instance_id[0])
            self.selected_instances.add(obj)
            obj.get_component(SelectableComponent).select()
        for group in xrange(len(
                self.selection_groups)):  # load user defined unit groups
            for instance_id in savegame_db(
                    "SELECT id FROM selected WHERE `group` = ?", group):
                self.selection_groups[group].add(
                    WorldObject.get_object_by_id(instance_id[0]))

        # cursor has to be inited last, else player interacts with a not inited world with it.
        self.current_cursor = 'default'
        self.cursor = SelectionTool(self)
        # Set cursor correctly, menus might need to be opened.
        # Open menus later; they may need unit data not yet inited
        self.cursor.apply_select()

        Scheduler().before_ticking()
        savegame_db.close()

        assert hasattr(self.world, "player"), 'Error: there is no human player'
        """
Ejemplo n.º 17
0
    def _upgrade(self):
        # fix import loop
        from horizons.savegamemanager import SavegameManager
        metadata = SavegameManager.get_metadata(self.original_path)
        rev = metadata['savegamerev']
        if rev == 0:  # not a regular savegame, usually a map
            self.final_path = self.original_path
        elif rev == VERSION.SAVEGAMEREVISION:  # the current version
            self.final_path = self.original_path
        else:  # upgrade
            self.using_temp = True
            handle, self.final_path = tempfile.mkstemp(
                prefix='uh-savegame.' +
                os.path.basename(os.path.splitext(self.original_path)[0]) +
                '.',
                suffix='.sqlite')
            os.close(handle)
            shutil.copyfile(self.original_path, self.final_path)
            db = DbReader(self.final_path)
            db('BEGIN TRANSACTION')

            if rev < 49:
                self._upgrade_to_rev49(db)
            if rev < 50:
                self._upgrade_to_rev50(db)
            if rev < 51:
                self._upgrade_to_rev51(db)
            if rev < 52:
                self._upgrade_to_rev52(db)
            if rev < 53:
                self._upgrade_to_rev53(db)
            if rev < 54:
                self._upgrade_to_rev54(db)
            if rev < 55:
                self._upgrade_to_rev55(db)
            if rev < 56:
                self._upgrade_to_rev56(db)
            if rev < 57:
                self._upgrade_to_rev57(db)
            if rev < 58:
                self._upgrade_to_rev58(db)
            if rev < 59:
                self._upgrade_to_rev59(db)
            if rev < 60:
                self._upgrade_to_rev60(db)
            if rev < 61:
                self._upgrade_to_rev61(db)
            if rev < 62:
                self._upgrade_to_rev62(db)
            if rev < 63:
                self._upgrade_to_rev63(db)
            if rev < 64:
                self._upgrade_to_rev64(db)
            if rev < 65:
                self._upgrade_to_rev65(db)
            if rev < 66:
                self._upgrade_to_rev66(db)
            if rev < 67:
                self._upgrade_to_rev67(db)
            if rev < 68:
                self._upgrade_to_rev68(db)
            if rev < 69:
                self._upgrade_to_rev69(db)
            if rev < 70:
                self._upgrade_to_rev70(db)

            db('COMMIT')
            db.close()
Ejemplo n.º 18
0
    def _upgrade(self):
        # fix import loop
        from horizons.savegamemanager import SavegameManager
        metadata = SavegameManager.get_metadata(self.original_path)
        rev = metadata['savegamerev']

        if rev < VERSION.SAVEGAMEREVISION:
            if not SavegameUpgrader.can_upgrade(rev):
                raise SavegameTooOld(revision=rev)

            self.log.warning('Discovered old savegame file, auto-upgrading: %s -> %s' % \
                    (rev, VERSION.SAVEGAMEREVISION))
            db = DbReader(self.final_path)
            db('BEGIN TRANSACTION')

            if rev < 49:
                self._upgrade_to_rev49(db)
            if rev < 50:
                self._upgrade_to_rev50(db)
            if rev < 51:
                self._upgrade_to_rev51(db)
            if rev < 52:
                self._upgrade_to_rev52(db)
            if rev < 53:
                self._upgrade_to_rev53(db)
            if rev < 54:
                self._upgrade_to_rev54(db)
            if rev < 55:
                self._upgrade_to_rev55(db)
            if rev < 56:
                self._upgrade_to_rev56(db)
            if rev < 57:
                self._upgrade_to_rev57(db)
            if rev < 58:
                self._upgrade_to_rev58(db)
            if rev < 59:
                self._upgrade_to_rev59(db)
            if rev < 60:
                self._upgrade_to_rev60(db)
            if rev < 61:
                self._upgrade_to_rev61(db)
            if rev < 62:
                self._upgrade_to_rev62(db)
            if rev < 63:
                self._upgrade_to_rev63(db)
            if rev < 64:
                self._upgrade_to_rev64(db)
            if rev < 65:
                self._upgrade_to_rev65(db)
            if rev < 66:
                self._upgrade_to_rev66(db)
            if rev < 67:
                self._upgrade_to_rev67(db)
            if rev < 68:
                self._upgrade_to_rev68(db)
            if rev < 69:
                self._upgrade_to_rev69(db)
            if rev < 70:
                self._upgrade_to_rev70(db)
            if rev < 71:
                self._upgrade_to_rev71(db)
            if rev < 72:
                self._upgrade_to_rev72(db)
            if 70 < rev < 73:
                self._upgrade_to_rev73(db)
            if rev < 74:
                self._upgrade_to_rev74(db)
            if rev < 75:
                self._upgrade_to_rev75(db)
            if rev < 76:
                self._upgrade_to_rev76(db)

            db('COMMIT')
            db.close()
Ejemplo n.º 19
0
		def tmp_show_details():
			"""Fetches details of selected savegame and displays it"""
			gui.findChild(name="screenshot").image = None
			map_file = None
			map_file_index = gui.collectData(savegamelist)

			savegame_details_box = gui.findChild(name="savegame_details")
			savegame_details_parent = savegame_details_box.parent
			if map_file_index == -1:
				if savegame_details_box not in savegame_details_parent.hidden_children:
					savegame_details_parent.hideChild(savegame_details_box)
				return
			else:
				savegame_details_parent.showChild(savegame_details_box)
			try:
				map_file = map_files[map_file_index]
			except IndexError:
				# this was a click in the savegame list, but not on an element
				# it happens when the savegame list is empty
				return
			savegame_info = SavegameManager.get_metadata(map_file)

			if savegame_info.get('screenshot'):
				# try to find a writable location, that is accessible via relative paths
				# (required by fife)
				fd, filename = tempfile.mkstemp()
				try:
					path_rel = os.path.relpath(filename)
				except ValueError: # the relative path sometimes doesn't exist on win
					os.close(fd)
					os.unlink(filename)
					# try again in the current dir, it's often writable
					fd, filename = tempfile.mkstemp(dir=os.curdir)
					try:
						path_rel = os.path.relpath(filename)
					except ValueError:
						fd, filename = None, None

				if fd:
					with os.fdopen(fd, "w") as f:
						f.write(savegame_info['screenshot'])
					# fife only supports relative paths
					gui.findChild(name="screenshot").image = path_rel
					os.unlink(filename)

			# savegamedetails
			details_label = gui.findChild(name="savegamedetails_lbl")
			details_label.text = u""
			if savegame_info['timestamp'] == -1:
				details_label.text += _("Unknown savedate")
			else:
				savetime = time.strftime("%c", time.localtime(savegame_info['timestamp']))
				#xgettext:python-format
				details_label.text += _("Saved at {time}").format(time=savetime.decode('utf-8'))
			details_label.text += u'\n'
			counter = savegame_info['savecounter']
			# N_ takes care of plural forms for different languages
			#xgettext:python-format
			details_label.text += N_("Saved {amount} time",
			                         "Saved {amount} times",
			                         counter).format(amount=counter)
			details_label.text += u'\n'

			from horizons.constants import VERSION
			try:
				#xgettext:python-format
				details_label.text += _("Savegame version {version}").format(
				                         version=savegame_info['savegamerev'])
				if savegame_info['savegamerev'] != VERSION.SAVEGAMEREVISION:
					if not SavegameUpgrader.can_upgrade(savegame_info['savegamerev']):
						details_label.text += u" " + _("(probably incompatible)")
			except KeyError:
				# this should only happen for very old savegames, so having this unfriendly
				# error is ok (savegame is quite certainly fully unusable).
				details_label.text += u" " + _("Incompatible version")

			gui.adaptLayout()
Ejemplo n.º 20
0
	def _upgrade(self):
		# fix import loop
		from horizons.savegamemanager import SavegameManager
		metadata = SavegameManager.get_metadata(self.original_path)
		rev = metadata['savegamerev']

		if rev < VERSION.SAVEGAMEREVISION :
			if not SavegameUpgrader.can_upgrade(rev):
				raise SavegameTooOld(revision=rev)
			
			self.log.warning('Discovered old savegame file, auto-upgrading: %s -> %s' % \
						     (rev, VERSION.SAVEGAMEREVISION))
			db = DbReader(self.final_path)
			db('BEGIN TRANSACTION')

			if rev < 49:
				self._upgrade_to_rev49(db)
			if rev < 50:
				self._upgrade_to_rev50(db)
			if rev < 51:
				self._upgrade_to_rev51(db)
			if rev < 52:
				self._upgrade_to_rev52(db)
			if rev < 53:
				self._upgrade_to_rev53(db)
			if rev < 54:
				self._upgrade_to_rev54(db)
			if rev < 55:
				self._upgrade_to_rev55(db)
			if rev < 56:
				self._upgrade_to_rev56(db)
			if rev < 57:
				self._upgrade_to_rev57(db)
			if rev < 58:
				self._upgrade_to_rev58(db)
			if rev < 59:
				self._upgrade_to_rev59(db)
			if rev < 60:
				self._upgrade_to_rev60(db)
			if rev < 61:
				self._upgrade_to_rev61(db)
			if rev < 62:
				self._upgrade_to_rev62(db)
			if rev < 63:
				self._upgrade_to_rev63(db)
			if rev < 64:
				self._upgrade_to_rev64(db)
			if rev < 65:
				self._upgrade_to_rev65(db)
			if rev < 66:
				self._upgrade_to_rev66(db)
			if rev < 67:
				self._upgrade_to_rev67(db)
			if rev < 68:
				self._upgrade_to_rev68(db)
			if rev < 69:
				self._upgrade_to_rev69(db)
			if rev < 70:
				self._upgrade_to_rev70(db)
			if rev < 71:
				self._upgrade_to_rev71(db)
			if rev < 72:
				self._upgrade_to_rev72(db)
			if 70 < rev < 73:
				self._upgrade_to_rev73(db)
			if rev < 74:
				self._upgrade_to_rev74(db)
			if rev < 75:
				self._upgrade_to_rev75(db)

			db('COMMIT')
			db.close()
Ejemplo n.º 21
0
    def load(self, options):
        """Loads a map. Key method for starting a game."""
        """
		TUTORIAL: Here you see how the vital game elements (and some random things that are also required)
		are initialized.
		"""
        if options.is_scenario:
            # game_identifier is a yaml file, that contains reference to actual map file
            self.scenario_eventhandler = ScenarioEventHandler(
                self, options.game_identifier)
            # scenario maps can be normal maps or scenario maps:
            map_filename = self.scenario_eventhandler.get_map_file()
            options.game_identifier = os.path.join(
                SavegameManager.scenario_maps_dir, map_filename)
            if not os.path.exists(options.game_identifier):
                options.game_identifier = os.path.join(
                    SavegameManager.maps_dir, map_filename)
            options.is_map = True

        self.log.debug("Session: Loading from %s", options.game_identifier)
        savegame_db = SavegameAccessor(options.game_identifier, options.is_map,
                                       options)  # Initialize new dbreader
        savegame_data = SavegameManager.get_metadata(savegame_db.db_path)
        self.view.resize_layers(savegame_db)

        # load how often the game has been saved (used to know the difference between
        # a loaded and a new game)
        self.savecounter = savegame_data.get('savecounter', 0)

        if savegame_data.get('rng_state', None):
            rng_state_list = json.loads(savegame_data['rng_state'])

            # json treats tuples as lists, but we need tuples here, so convert back
            def rec_list_to_tuple(x):
                if isinstance(x, list):
                    return tuple(rec_list_to_tuple(i) for i in x)
                else:
                    return x

            rng_state_tuple = rec_list_to_tuple(rng_state_list)
            # changing the rng is safe for mp, as all players have to have the same map
            self.random.setstate(rng_state_tuple)

        LoadingProgress.broadcast(self, 'session_create_world')
        self.world = World(
            self
        )  # Load horizons.world module (check horizons/world/__init__.py)
        self.world._init(savegame_db,
                         options.force_player_id,
                         disasters_enabled=options.disasters_enabled)
        self.view.load(savegame_db, self.world)  # load view
        if not self.is_game_loaded():
            options.init_new_world(self)
        else:
            # try to load scenario data
            self.scenario_eventhandler.load(savegame_db)
        self.manager.load(
            savegame_db
        )  # load the manager (there might be old scheduled ticks).
        LoadingProgress.broadcast(self, "session_index_fish")
        self.world.init_fish_indexer()  # now the fish should exist

        # load the old gui positions and stuff
        # Do this before loading selections, they need the minimap setup
        LoadingProgress.broadcast(self, "session_load_gui")
        self.ingame_gui = self._ingame_gui_class(self)
        self.ingame_gui.load(savegame_db)

        Scheduler().before_ticking()
        savegame_db.close()

        assert hasattr(self.world, "player"), 'Error: there is no human player'
        LoadingProgress.broadcast(self, "session_finish")
        """
Ejemplo n.º 22
0
	def load(self, savegame, players, is_scenario=False, campaign=None):
		"""Loads a map.
		@param savegame: path to the savegame database.
		@param players: iterable of dictionaries containing id, name, color, local, ai, and difficulty
		@param is_scenario: Bool whether the loaded map is a scenario or not
		"""
		if is_scenario:
			# savegame is a yaml file, that contains reference to actual map file
			self.scenario_eventhandler = ScenarioEventHandler(self, savegame)
			savegame = os.path.join(SavegameManager.maps_dir, \
			                        self.scenario_eventhandler.get_map_file())
		self.campaign = {} if not campaign else campaign

		self.log.debug("Session: Loading from %s", savegame)
		savegame_db = SavegameAccessor(savegame) # Initialize new dbreader
		savegame_data = SavegameManager.get_metadata(savegame)

		# load how often the game has been saved (used to know the difference between
		# a loaded and a new game)
		self.savecounter = 0 if not 'savecounter' in savegame_data else savegame_data['savecounter']

		if savegame_data.get('rng_state', None):
			rng_state_list = json.loads( savegame_data['rng_state'] )
			# json treats tuples as lists, but we need tuples here, so convert back
			def rec_list_to_tuple(x):
				if isinstance(x, list):
					return tuple( rec_list_to_tuple(i) for i in x )
				else:
					return x
			rng_state_tuple = rec_list_to_tuple(rng_state_list)
			# changing the rng is safe for mp, as all players have to have the same map
			self.random.setstate( rng_state_tuple )

		self.world = World(self) # Load horizons.world module (check horizons/world/__init__.py)
		self.world._init(savegame_db)
		self.view.load(savegame_db) # load view
		if not self.is_game_loaded():
			# NOTE: this must be sorted before iteration, cause there is no defined order for
			#       iterating a dict, and it must happen in the same order for mp games.
			for i in sorted(players, lambda p1, p2: cmp(p1['id'], p2['id'])):
				self.world.setup_player(i['id'], i['name'], i['color'], i['local'], i['ai'], i['difficulty'])
			center = self.world.init_new_world()
			self.view.center(center[0], center[1])
		else:
			# try to load scenario data
			self.scenario_eventhandler.load(savegame_db)
		self.manager.load(savegame_db) # load the manager (there might me old scheduled ticks).
		self.world.init_fish_indexer() # now the fish should exist
		self.ingame_gui.load(savegame_db) # load the old gui positions and stuff

		for instance_id in savegame_db("SELECT id FROM selected WHERE `group` IS NULL"): # Set old selected instance
			obj = WorldObject.get_object_by_id(instance_id[0])
			self.selected_instances.add(obj)
			obj.select()
		for group in xrange(len(self.selection_groups)): # load user defined unit groups
			for instance_id in savegame_db("SELECT id FROM selected WHERE `group` = ?", group):
				self.selection_groups[group].add(WorldObject.get_object_by_id(instance_id[0]))

		# cursor has to be inited last, else player interacts with a not inited world with it.
		self.cursor = SelectionTool(self)
        # Set cursor correctly, menus might need to be opened.
		# Open menus later, they may need unit data not yet inited
		self.cursor.apply_select()

		assert hasattr(self.world, "player"), 'Error: there is no human player'
		"""