本文整理汇总了Python中horizons.world.World类的典型用法代码示例。如果您正苦于以下问题:Python World类的具体用法?Python World怎么用?Python World使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了World类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_map
def generate_map(self):
"""Generates a map."""
#load map
self.db("ATTACH ':memory:' AS map")
#...
self.world = World(self)
self.world._init(self.db)
#setup view
self.view.center(((self.world.max_x - self.world.min_x) / 2.0), ((self.world.max_y - self.world.min_y) / 2.0))
示例2: load
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'
"""
示例3: load
def load(self, savegame, players):
"""
Stripped version of the original code. We don't need to load selections,
or a scenario, setting up the gui or view.
"""
self.savegame = savegame
self.savegame_db = SavegameAccessor(self.savegame)
self.world = World(self)
self.world._init(self.savegame_db)
for i in sorted(players):
self.world.setup_player(i['id'], i['name'], i['color'], i['local'], i['is_ai'], i['difficulty'])
self.manager.load(self.savegame_db)
示例4: Session
#.........这里部分代码省略.........
self.end_production_finished_icon_manager()
def start(self):
"""Actually starts the game."""
self.timer.activate()
self.reset_autosave()
def reset_autosave(self):
"""(Re-)Set up autosave. Called if autosave interval has been changed."""
# get_uh_setting returns floats like 4.0 and 42.0 since slider stepping is 1.0.
interval = int(horizons.globals.fife.get_uh_setting("AutosaveInterval"))
if interval != self._old_autosave_interval:
self._old_autosave_interval = interval
ExtScheduler().rem_call(self, self.autosave)
if interval != 0: #autosave
self.log.debug("Initing autosave every %s minutes", interval)
ExtScheduler().add_new_object(self.autosave, self, interval * 60, -1)
def create_manager(self):
"""Returns instance of command manager (currently MPManager or SPManager)"""
raise NotImplementedError
def create_rng(self, seed=None):
"""Returns a RNG (random number generator). Must support the python random.Random interface"""
raise NotImplementedError
def create_timer(self):
"""Returns a Timer instance."""
raise NotImplementedError
@classmethod
def _clear_caches(cls):
"""Clear all data caches in global namespace related to a session"""
WorldObject.reset()
NamedComponent.reset()
AIPlayer.clear_caches()
SelectableBuildingComponent.reset()
def end_production_finished_icon_manager(self):
if self.production_finished_icon_manager is not None:
self.production_finished_icon_manager.end()
self.production_finished_icon_manager = None
def end(self):
self.log.debug("Ending session")
self.is_alive = False
self.gui.session = None
# Has to be done here, cause the manager uses Scheduler!
self.end_production_finished_icon_manager()
Scheduler().rem_all_classinst_calls(self)
ExtScheduler().rem_all_classinst_calls(self)
if horizons.globals.fife.get_fife_setting("PlaySounds"):
for emitter in horizons.globals.fife.sound.emitter['ambient'][:]:
emitter.stop()
horizons.globals.fife.sound.emitter['ambient'].remove(emitter)
horizons.globals.fife.sound.emitter['effects'].stop()
horizons.globals.fife.sound.emitter['speech'].stop()
if hasattr(self, "cursor"): # the line below would crash uglily on ^C
self.cursor.remove()
if hasattr(self, 'cursor') and self.cursor is not None:
self.cursor.end()
# these will call end() if the attribute still exists by the LivingObject magic
示例5: load
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'
"""
示例6: load_raw_world
def load_raw_world(map_file):
WorldObject.reset()
world = World(session=None)
world.inited = True
world.load_raw_map(SavegameAccessor(map_file, True), preview=True)
return world
示例7: Session
#.........这里部分代码省略.........
self.reset_autosave()
SettingChanged.subscribe(self._on_setting_changed)
def reset_autosave(self):
"""(Re-)Set up autosave. Called if autosave interval has been changed."""
# get_uh_setting returns floats like 4.0 and 42.0 since slider stepping is 1.0.
interval = int(horizons.globals.fife.get_uh_setting("AutosaveInterval"))
if interval != self._old_autosave_interval:
self._old_autosave_interval = interval
ExtScheduler().rem_call(self, self.autosave)
if interval != 0: #autosave
self.log.debug("Initing autosave every %s minutes", interval)
ExtScheduler().add_new_object(self.autosave, self, interval * 60, -1)
def _on_setting_changed(self, message):
if message.setting_name == 'AutosaveInterval':
self.reset_autosave()
def create_manager(self):
"""Returns instance of command manager (currently MPManager or SPManager)"""
raise NotImplementedError
def create_rng(self, seed=None):
"""Returns a RNG (random number generator). Must support the python random.Random interface"""
raise NotImplementedError
def create_timer(self):
"""Returns a Timer instance."""
raise NotImplementedError
@classmethod
def _clear_caches(cls):
"""Clear all data caches in global namespace related to a session"""
WorldObject.reset()
NamedComponent.reset()
AIPlayer.clear_caches()
SelectableBuildingComponent.reset()
def end(self):
self.log.debug("Ending session")
self.is_alive = False
# Has to be done here, cause the manager uses Scheduler!
Scheduler().rem_all_classinst_calls(self)
ExtScheduler().rem_all_classinst_calls(self)
horizons.globals.fife.sound.end()
# these will call end() if the attribute still exists by the LivingObject magic
self.ingame_gui = None # keep this before world
if hasattr(self, 'world'):
# must be called before the world ref is gone, but may not exist yet while loading
self.world.end()
self.world = None
self.view = None
self.manager = None
self.timer = None
self.scenario_eventhandler = None
Scheduler().end()
Scheduler.destroy_instance()
self.selected_instances = None
self.selection_groups = None
示例8: load
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")
"""
示例9: Session
class Session(LivingObject):
"""Session class represents the games main ingame view and controls cameras and map loading.
This is the most important class if you are going to hack on Unknown Horizons, it provides most of
the important ingame variables.
Here's a small list of commonly used attributes:
* manager - horizons.manager instance. Used to execute commands that need to be tick,
synchronized check the class for more information.
* scheduler - horizons.scheduler instance. Used to execute timed events that do not effect
network games but rather control the local simulation.
* view - horizons.view instance. Used to control the ingame camera.
* ingame_gui - horizons.gui.ingame_gui instance. Used to controll the ingame gui.
* cursor - horizons.gui.{navigation/cursor/selection/building}tool instance. Used to controll
mouse events, check the classes for more info.
* selected_instances - Set that holds the currently selected instances (building, units).
* world - horizons.world instance of the currently running horizons. Stores islands, players,
for later access.
TUTORIAL:
For further digging you should now be checking out the load() function.
"""
timer = livingProperty()
manager = livingProperty()
view = livingProperty()
ingame_gui = livingProperty()
keylistener = livingProperty()
cursor = livingProperty()
world = livingProperty()
scenario_eventhandler = livingProperty()
log = logging.getLogger('session')
def __init__(self, gui, db):
super(Session, self).__init__()
self.log.debug("Initing session")
self.gui = gui # main gui, not ingame gui
self.db = db # main db for game data (game.sqlite)
# this saves how often the current game has been saved
self.savecounter = 0
self.is_alive = True
WorldObject.reset()
NamedObject.reset()
#game
self.random = self.create_rng()
self.timer = Timer()
Scheduler.create_instance(self.timer)
self.manager = self.create_manager()
self.view = View(self, (15, 15))
Entities.load(self.db)
self.scenario_eventhandler = ScenarioEventHandler(self) # dummy handler with no events
self.campaign = {}
#GUI
self.gui.session = self
self.ingame_gui = IngameGui(self, self.gui)
self.keylistener = IngameKeyListener(self)
self.display_speed()
self.selected_instances = set()
self.selection_groups = [set()] * 10 # List of sets that holds the player assigned unit groups.
def start(self):
"""Acctually starts the game."""
self.timer.activate()
def create_manager(self):
"""Returns instance of command manager (currently MPManager or SPManager)"""
raise NotImplementedError
def create_rng(self):
"""Returns a RNG (random number generator). Must support the python random.Random interface"""
raise NotImplementedError
def end(self):
self.log.debug("Ending session")
self.is_alive = False
self.gui.session = None
Scheduler().rem_all_classinst_calls(self)
ExtScheduler().rem_all_classinst_calls(self)
if horizons.main.fife.get_fife_setting("PlaySounds"):
for emitter in horizons.main.fife.emitter['ambient'][:]:
emitter.stop()
horizons.main.fife.emitter['ambient'].remove(emitter)
horizons.main.fife.emitter['effects'].stop()
horizons.main.fife.emitter['speech'].stop()
self.cursor = None
self.world = None
self.keylistener = None
self.ingame_gui = None
self.view = None
self.manager = None
self.timer = None
self.scenario_eventhandler = None
Scheduler.destroy_instance()
#.........这里部分代码省略.........
示例10: load
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'
"""
示例11: test_world_end
def test_world_end(self):
w = World(self.session)
w.end()
示例12: SPTestSession
class SPTestSession(SPSession):
def __init__(self, db, rng_seed=None):
"""
Unfortunately, right now there is no other way to setup Dummy versions of the GUI,
View etc., unless we want to patch the references in the session module.
"""
super(LivingObject, self).__init__()
self.gui = Dummy()
self.db = db
self.savecounter = 0 # this is a new game.
self.is_alive = True
WorldObject.reset()
NamedObject.reset()
AIPlayer.clear_caches()
# Game
self.current_tick = 0
self.random = self.create_rng(rng_seed)
self.timer = self.create_timer()
Scheduler.create_instance(self.timer)
ExtScheduler.create_instance(Dummy)
self.manager = self.create_manager()
self.view = Dummy()
self.view.renderer = Dummy()
Entities.load(self.db)
self.scenario_eventhandler = Dummy()
self.campaign = {}
self.selected_instances = []
# GUI
self.gui.session = self
self.ingame_gui = Dummy()
GAME_SPEED.TICKS_PER_SECOND = 16
def load(self, savegame, players):
"""
Stripped version of the original code. We don't need to load selections,
or a scenario, setting up the gui or view.
"""
self.savegame = savegame
self.savegame_db = SavegameAccessor(self.savegame)
self.world = World(self)
self.world._init(self.savegame_db)
for i in sorted(players):
self.world.setup_player(i['id'], i['name'], i['color'], i['local'], i['is_ai'], i['difficulty'])
self.manager.load(self.savegame_db)
def end(self):
"""
Clean up temporary files.
"""
super(SPTestSession, self).end()
# Find all islands in the map first
random_map = False
for (island_file, ) in self.savegame_db('SELECT file FROM island'):
if island_file[:7] != 'random:': # random islands don't exist as files
os.remove(island_file)
else:
random_map = True
break
# Finally remove savegame
self.savegame_db.close()
if not random_map:
os.remove(self.savegame)
def run(self, ticks=1, seconds=None):
"""
Run the scheduler the given count of ticks or (in-game) seconds. Default is 1 tick,
if seconds are passed, they will overwrite the tick count.
"""
if seconds:
ticks = self.timer.get_ticks(seconds)
for i in range(ticks):
Scheduler().tick(self.current_tick)
self.current_tick += 1
示例13: load
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'
"""
示例14: SPTestSession
class SPTestSession(SPSession):
def __init__(self, db, rng_seed=None):
"""
Unfortunately, right now there is no other way to setup Dummy versions of the GUI,
View etc., unless we want to patch the references in the session module.
"""
super(LivingObject, self).__init__()
self.gui = Dummy()
self.db = db
self.savecounter = 0 # this is a new game.
self.is_alive = True
WorldObject.reset()
NamedComponent.reset()
AIPlayer.clear_caches()
# Game
self.random = self.create_rng(rng_seed)
self.timer = self.create_timer()
Scheduler.create_instance(self.timer)
ExtScheduler.create_instance(Dummy)
self.manager = self.create_manager()
self.view = Dummy()
self.view.renderer = Dummy()
Entities.load(self.db)
self.scenario_eventhandler = Dummy()
self.campaign = {}
self.message_bus = MessageBus()
self.status_icon_manager = StatusIconManager(self)
# GUI
self.gui.session = self
self.ingame_gui = Dummy()
LastActivePlayerSettlementManager.create_instance(self)
self.selected_instances = set()
self.selection_groups = [set()] * 10 # List of sets that holds the player assigned unit groups.
GAME_SPEED.TICKS_PER_SECOND = 16
def save(self, *args, **kwargs):
"""
Wrapper around original save function to fix some things.
"""
# SavegameManager.write_metadata tries to create a screenshot and breaks when
# accessing fife properties
with mock.patch('horizons.spsession.SavegameManager'):
# We need to covert Dummy() objects to a sensible value that can be stored
# in the database
with _dbreader_convert_dummy_objects():
return super(SPTestSession, self).save(*args, **kwargs)
def load(self, savegame, players):
"""
Stripped version of the original code. We don't need to load selections,
or a scenario, setting up the gui or view.
"""
self.savegame = savegame
self.savegame_db = SavegameAccessor(self.savegame)
self.savecounter = 1
self.world = World(self)
self.world._init(self.savegame_db)
for i in sorted(players):
self.world.setup_player(i['id'], i['name'], i['color'], i['local'], i['is_ai'], i['difficulty'])
self.manager.load(self.savegame_db)
def end(self, keep_map=False, remove_savegame=True):
"""
Clean up temporary files.
"""
super(SPTestSession, self).end()
# Find all islands in the map first
if not keep_map:
for (island_file, ) in self.savegame_db('SELECT file FROM island'):
if island_file[:7] != 'random:': # random islands don't exist as files
os.remove(island_file)
self.savegame_db.close()
# Finally remove savegame
if remove_savegame:
os.remove(self.savegame)
@classmethod
def cleanup(cls):
"""
If a test uses manual session management, we cannot be sure that session.end was
called before a crash, leaving the game in an unclean state. This method should
return the game to a valid state.
"""
Scheduler.destroy_instance()
def run(self, ticks=1, seconds=None):
"""
Run the scheduler the given count of ticks or (in-game) seconds. Default is 1 tick,
if seconds are passed, they will overwrite the tick count.
#.........这里部分代码省略.........
示例15: Session
class Session(LivingObject):
"""Session class represents the games main ingame view and controls cameras and map loading.
It is alive as long as a game is running.
Many objects require a reference to this, which makes it a pseudo-global, from what we would
like to move away long-term. This is where we hope the components come into play, which
you will encounter later
This is the most important class if you are going to hack on Unknown Horizons, it provides most of
the important ingame variables.
Here's a small list of commonly used attributes:
* world - horizons.world instance of the currently running horizons. Stores players and islands,
which store settlements, which store buildings, which have productions and collectors.
Therefore world deserves its name, it contains the whole game state.
* scheduler - horizons.scheduler instance. Used to execute timed events. Master of time in UH.
* manager - horizons.manager instance. Used to execute commands (used to apply user interactions).
There is a singleplayer and a multiplayer version. Our mp system works by the mp-manager not
executing the commands directly, but sending them to all players, where they will be executed
at the same tick.
* view - horizons.view instance. Used to control the ingame camera.
* ingame_gui - horizons.gui.ingame_gui instance. Used to control the ingame gui framework.
(This is different from gui, which is the main menu and general session-independent gui)
* cursor - horizons.gui.{navigation/cursor/selection/building}tool instance. Used to handle
mouse events.
* selected_instances - Set that holds the currently selected instances (building, units).
TUTORIAL:
For further digging you should now be checking out the load() function.
"""
timer = livingProperty()
manager = livingProperty()
view = livingProperty()
ingame_gui = livingProperty()
keylistener = livingProperty()
world = livingProperty()
scenario_eventhandler = livingProperty()
log = logging.getLogger('session')
def __init__(self, gui, db, rng_seed=None):
super(Session, self).__init__()
assert isinstance(gui, Gui)
assert isinstance(db, horizons.util.uhdbaccessor.UhDbAccessor)
self.log.debug("Initing session")
self.gui = gui # main gui, not ingame gui
self.db = db # main db for game data (game.sql)
# this saves how often the current game has been saved
self.savecounter = 0
self.is_alive = True
self.message_bus = MessageBus()
# misc
WorldObject.reset()
NamedComponent.reset()
AIPlayer.clear_caches()
#game
self.random = self.create_rng(rng_seed)
assert isinstance(self.random, Random)
self.timer = self.create_timer()
Scheduler.create_instance(self.timer)
self.manager = self.create_manager()
self.view = View(self)
Entities.load(self.db)
self.scenario_eventhandler = ScenarioEventHandler(self) # dummy handler with no events
self.campaign = {}
#GUI
self.gui.session = self
self.ingame_gui = IngameGui(self, self.gui)
self.keylistener = IngameKeyListener(self)
self.coordinates_tooltip = None
self.display_speed()
LastActivePlayerSettlementManager.create_instance(self)
self.status_icon_manager = StatusIconManager(self)
self.selected_instances = set()
self.selection_groups = [set()] * 10 # List of sets that holds the player assigned unit groups.
def start(self):
"""Actually starts the game."""
self.timer.activate()
def create_manager(self):
"""Returns instance of command manager (currently MPManager or SPManager)"""
raise NotImplementedError
def create_rng(self, seed=None):
"""Returns a RNG (random number generator). Must support the python random.Random interface"""
raise NotImplementedError
def create_timer(self):
"""Returns a Timer instance."""
raise NotImplementedError
def end(self):
self.log.debug("Ending session")
#.........这里部分代码省略.........