def __init__(self, setting=None): if setting: self._setting = setting else: self._setting = Setting(app_name="", settings_file="./settings.xml") self.engine = fife.Engine() self.initLogging() self.loadSettings() self.engine.init() """ we are giving users a valid screen resolution option that is supported """ screen_modes = self.engine.getDeviceCaps().getSupportedScreenModes() resolutions = list( set([(mode.getWidth(), mode.getHeight()) for mode in screen_modes])) resolutions = [ "{0}x{1}".format(item[0], item[1]) for item in sorted(resolutions)[1:] ] self._setting.setValidResolutions(resolutions) self.quitRequested = False self.breakRequested = False self.returnValues = []
def _setup_settings(self): self._setting = Setting(app_name="unknownhorizons", settings_file=PATHS.USER_CONFIG_FILE, settings_gui_xml="content/gui/settings.xml", changes_gui_xml="content/gui/requirerestart.xml") self._setting.setGuiStyle("book") #self.createAndAddEntry(self, module, name, widgetname, applyfunction=None, initialdata=None, requiresrestart=False) self._setting.createAndAddEntry(UH_MODULE, "AutosaveInterval", "autosaveinterval", initialdata=range(0, 60, 2)) self._setting.createAndAddEntry(UH_MODULE, "AutosaveMaxCount", "autosavemaxcount", initialdata=range(1, 30)) self._setting.createAndAddEntry(UH_MODULE, "QuicksaveMaxCount", "quicksavemaxcount", initialdata=range(1, 30)) self._setting.createAndAddEntry(FIFE_MODULE, "BitsPerPixel", "screen_bpp", initialdata=[0, 16, 32], requiresrestart=True) languages_map = dict(find_available_languages()) languages_map[_('System default')] = '' self._setting.createAndAddEntry(UH_MODULE, "Language", "language", applyfunction=self.update_languages, initialdata= [LANGUAGENAMES[x] for x in sorted(languages_map.keys())]) self._setting.createAndAddEntry(UH_MODULE, "VolumeMusic", "volume_music", applyfunction=lambda x: self.set_volume_music(x)) self._setting.createAndAddEntry(UH_MODULE, "VolumeEffects", "volume_effects", applyfunction=lambda x: self.set_volume_effects(x)) self._setting.entries[FIFE_MODULE]['PlaySounds'].applyfunction = lambda x: self.setup_sound() self._setting.entries[FIFE_MODULE]['PlaySounds'].requiresrestart = False
def __init__(self, setting=None): if setting: self._setting = setting else: self._setting = Setting(app_name="", settings_file="./settings.xml") self.engine = fife.Engine() self.initLogging() self.loadSettings() self.engine.init() """ we are giving users a valid screen resolution option that is supported """ screen_modes = self.engine.getDeviceCaps().getSupportedScreenModes() resolutions = list(set([(mode.getWidth(), mode.getHeight()) for mode in screen_modes])) resolutions = ["{0}x{1}".format(item[0], item[1]) for item in sorted(resolutions)[1:]] self._setting.setValidResolutions(resolutions) self.quitRequested = False self.breakRequested = False self.returnValues = []
def __init__(self, setting=None): if setting: self._setting = setting else: self._setting = Setting(app_name="", settings_file="./settings.xml", settings_gui_xml="") self.engine = fife.Engine() self.loadSettings() self.initLogging() self.engine.init() self._animationloader = XMLAnimationLoader(self.engine.getImagePool(), self.engine.getVFS()) self.engine.getAnimationPool().addResourceLoader(self._animationloader) pychan.init(self.engine, debug=self._setting.get("FIFE", "PychanDebug", False)) pychan.setupModalExecution(self.mainLoop, self.breakFromMainLoop) self.quitRequested = False self.breakRequested = False self.returnValues = []
import sys, os, re, math, random, shutil fife_path = os.path.join('..','..','engine','python') if os.path.isdir(fife_path) and fife_path not in sys.path: sys.path.insert(0,fife_path) from fife import fife print "Using the FIFE python module found here: ", os.path.dirname(fife.__file__) from fife.extensions.fife_settings import Setting from scripts.rpg import RPGApplication TDS = Setting(app_name="rpg", settings_file="./settings.xml", settings_gui_xml="") def main(): app = RPGApplication(TDS) app.run() if __name__ == '__main__': if TDS.get("FIFE", "ProfilingOn"): import hotshot, hotshot.stats print "Starting profiler" prof = hotshot.Profile("fife.prof") prof.runcall(main) prof.close() print "analysing profiling results" stats = hotshot.stats.load("fife.prof")
# Import the main FIFE module from fife import fife # Import the FIFE Setting extension from fife.extensions.fife_settings import Setting # Import our Tutorial1Application class from scripts.tutorial1 import Tutorial1Application # This is required in order to use the ApplicationBase framework provided # in the fife.extensions module. app_name is the name of your application, # settings_file is what to call your settings file. If you don't provide # a settings-dist.xml file a blank settings file will be created for you by # the Setting extension. settings = Setting(app_name="tutorial1", settings_file="./settings.xml", settings_gui_xml="") def main(): # This creates an instance of Tutorial1Application and passes it the # Setting instance you created above. The ApplicationBase will # automatically create and configure an instance of the FIFE engine. app = Tutorial1Application(settings) # Start the application app.run() if __name__ == '__main__': main()
class ApplicationBase(object): """ ApplicationBase is an extendable class that provides a basic environment for a FIFE-based client. This kind of application base does not offer GUI support. The unextended application reads in and initializes engine settings, sets up a simple event listener, and pumps the engine while listening for a quit message. Specialized applications can modify settings.py to change initial engine settings. They can provide their own event listener by overriding L{createListener}. And they can override the L{_pump} method to define runtime behavior of the application. """ def __init__(self, setting=None): if setting: self._setting = setting else: self._setting = Setting(app_name="", settings_file="./settings.xml") self.engine = fife.Engine() self.initLogging() self.loadSettings() self.engine.init() """ we are giving users a valid screen resolution option that is supported """ screen_modes = self.engine.getDeviceCaps().getSupportedScreenModes() resolutions = list(set([(mode.getWidth(), mode.getHeight()) for mode in screen_modes])) resolutions = ["{0}x{1}".format(item[0], item[1]) for item in sorted(resolutions)[1:]] self._setting.setValidResolutions(resolutions) self.quitRequested = False self.breakRequested = False self.returnValues = [] def loadSettings(self): """ Load the settings from a python file and load them into the engine. Called in the ApplicationBase constructor. """ # get finalSetting (from the xml file, or if absent the default value) self._finalSetting = self._setting.getSettingsFromFile("FIFE", self._log) engineSetting = self.engine.getSettings() engineSetting.setDefaultFontGlyphs(self._finalSetting['FontGlyphs']) engineSetting.setDefaultFontPath(self._finalSetting['Font']) engineSetting.setDefaultFontSize(self._finalSetting['DefaultFontSize']) engineSetting.setBitsPerPixel(self._finalSetting['BitsPerPixel']) engineSetting.setInitialVolume(self._finalSetting['InitialVolume']) engineSetting.setSDLRemoveFakeAlpha(self._finalSetting['SDLRemoveFakeAlpha']) engineSetting.setGLCompressImages(self._finalSetting['GLCompressImages']) engineSetting.setGLUseFramebuffer(self._finalSetting['GLUseFramebuffer']) engineSetting.setGLUseNPOT(self._finalSetting['GLUseNPOT']) engineSetting.setGLUseMipmapping(self._finalSetting['GLUseMipmapping']) engineSetting.setGLUseMonochrome(self._finalSetting['GLUseMonochrome']) engineSetting.setGLUseDepthBuffer(self._finalSetting['GLUseDepthBuffer']) engineSetting.setGLAlphaTestValue(self._finalSetting['GLAlphaTestValue']) if self._finalSetting['GLTextureFiltering'] == 'None': engineSetting.setGLTextureFiltering(fife.TEXTURE_FILTER_NONE) elif self._finalSetting['GLTextureFiltering'] == 'Bilinear': engineSetting.setGLTextureFiltering(fife.TEXTURE_FILTER_BILINEAR) elif self._finalSetting['GLTextureFiltering'] == 'Trilinear': engineSetting.setGLTextureFiltering(fife.TEXTURE_FILTER_TRILINEAR) elif self._finalSetting['GLTextureFiltering'] == 'Anisotropic': engineSetting.setGLTextureFiltering(fife.TEXTURE_FILTER_ANISOTROPIC) (width, height) = self._finalSetting['ScreenResolution'].split('x') engineSetting.setScreenWidth(int(width)) engineSetting.setScreenHeight(int(height)) engineSetting.setRenderBackend(self._finalSetting['RenderBackend']) engineSetting.setFullScreen(self._finalSetting['FullScreen']) engineSetting.setRefreshRate(self._finalSetting['RefreshRate']) engineSetting.setDisplay(self._finalSetting['Display']) engineSetting.setVSync(self._finalSetting['VSync']) engineSetting.setVideoDriver(self._finalSetting['VideoDriver']) engineSetting.setSDLDriver(self._finalSetting['RenderDriver']) engineSetting.setLightingModel(self._finalSetting['Lighting']) try: engineSetting.setColorKeyEnabled(self._finalSetting['ColorKeyEnabled']) except: pass try: engineSetting.setColorKey(self._finalSetting['ColorKey'][0],self._finalSetting['ColorKey'][1],self._finalSetting['ColorKey'][2]) except: pass try: engineSetting.setWindowTitle(self._finalSetting['WindowTitle']) engineSetting.setWindowIcon(self._finalSetting['WindowIcon']) except: pass try: engineSetting.setFrameLimitEnabled(self._finalSetting['FrameLimitEnabled']) engineSetting.setFrameLimit(self._finalSetting['FrameLimit']) except: pass try: engineSetting.setMouseSensitivity(self._finalSetting['MouseSensitivity']) except: pass try: engineSetting.setMouseAccelerationEnabled(self._finalSetting['MouseAcceleration']) except: pass def initLogging(self): """ Initialize the LogManager. """ engineSetting = self.engine.getSettings() logmodules = self._setting.get("FIFE", "LogModules", ["controller"]) #log to both the console and log file self._log = fifelog.LogManager(self.engine, self._setting.get("FIFE", "LogToPrompt", False), self._setting.get("FIFE", "LogToFile", False)) self._log.setLevelFilter(self._setting.get("FIFE", "LogLevelFilter", fife.LogManager.LEVEL_DEBUG)) if logmodules: self._log.setVisibleModules(*logmodules) def createListener(self): """ This creates a default event listener, which will just close the program after pressing ESC. You should override this method to provide your own event handling. """ return ExitEventListener(self) def run(self): """ Initialize the event listener and event loop - and start it. """ eventlistener = self.createListener() self.engine.initializePumping() retval = self.mainLoop() self.engine.finalizePumping() self.engine.destroy() return retval def mainLoop(self): """ The programs main loop. Do not override this, instead provide your own L{_pump} method. You can call this recursively, e.g. to provide synchronous Dialogs :-) and break out of the current mainLoop by calling L{breakFromMainLoop}. It will return the argument passed to L{breakFromMainLoop}. """ self.returnValues.append(None) while not self.quitRequested: try: self.engine.pump() except RuntimeError, e: print str(e) self.quitRequested = True except:
class ApplicationBase(object): """ ApplicationBase is an extendable class that provides a basic environment for a FIFE-based client. This kind of application base does not offer GUI support. The unextended application reads in and initializes engine settings, sets up a simple event listener, and pumps the engine while listening for a quit message. Specialized applications can modify settings.py to change initial engine settings. They can provide their own event listener by overriding L{createListener}. And they can override the L{_pump} method to define runtime behavior of the application. """ def __init__(self, setting=None): if setting: self._setting = setting else: self._setting = Setting(app_name="", settings_file="./settings.xml") self.engine = fife.Engine() self.initLogging() self.loadSettings() self.engine.init() """ we are giving users a valid screen resolution option that is supported """ screen_modes = self.engine.getDeviceCaps().getSupportedScreenModes() resolutions = list( set([(mode.getWidth(), mode.getHeight()) for mode in screen_modes])) resolutions = [ "{0}x{1}".format(item[0], item[1]) for item in sorted(resolutions)[1:] ] self._setting.setValidResolutions(resolutions) self.quitRequested = False self.breakRequested = False self.returnValues = [] def loadSettings(self): """ Load the settings from a python file and load them into the engine. Called in the ApplicationBase constructor. """ # get finalSetting (from the xml file, or if absent the default value) self._finalSetting = self._setting.getSettingsFromFile( "FIFE", self._log) engineSetting = self.engine.getSettings() engineSetting.setDefaultFontGlyphs(self._finalSetting['FontGlyphs']) engineSetting.setDefaultFontPath(self._finalSetting['Font']) engineSetting.setDefaultFontSize(self._finalSetting['DefaultFontSize']) engineSetting.setBitsPerPixel(self._finalSetting['BitsPerPixel']) engineSetting.setInitialVolume(self._finalSetting['InitialVolume']) engineSetting.setSDLRemoveFakeAlpha( self._finalSetting['SDLRemoveFakeAlpha']) engineSetting.setGLCompressImages( self._finalSetting['GLCompressImages']) engineSetting.setGLUseFramebuffer( self._finalSetting['GLUseFramebuffer']) engineSetting.setGLUseNPOT(self._finalSetting['GLUseNPOT']) engineSetting.setGLUseMipmapping(self._finalSetting['GLUseMipmapping']) engineSetting.setGLUseMonochrome(self._finalSetting['GLUseMonochrome']) engineSetting.setGLUseDepthBuffer( self._finalSetting['GLUseDepthBuffer']) engineSetting.setGLAlphaTestValue( self._finalSetting['GLAlphaTestValue']) if self._finalSetting['GLTextureFiltering'] == 'None': engineSetting.setGLTextureFiltering(fife.TEXTURE_FILTER_NONE) elif self._finalSetting['GLTextureFiltering'] == 'Bilinear': engineSetting.setGLTextureFiltering(fife.TEXTURE_FILTER_BILINEAR) elif self._finalSetting['GLTextureFiltering'] == 'Trilinear': engineSetting.setGLTextureFiltering(fife.TEXTURE_FILTER_TRILINEAR) elif self._finalSetting['GLTextureFiltering'] == 'Anisotropic': engineSetting.setGLTextureFiltering( fife.TEXTURE_FILTER_ANISOTROPIC) (width, height) = self._finalSetting['ScreenResolution'].split('x') engineSetting.setScreenWidth(int(width)) engineSetting.setScreenHeight(int(height)) engineSetting.setRenderBackend(self._finalSetting['RenderBackend']) engineSetting.setFullScreen(self._finalSetting['FullScreen']) engineSetting.setRefreshRate(self._finalSetting['RefreshRate']) engineSetting.setDisplay(self._finalSetting['Display']) engineSetting.setVSync(self._finalSetting['VSync']) engineSetting.setVideoDriver(self._finalSetting['VideoDriver']) engineSetting.setSDLDriver(self._finalSetting['RenderDriver']) engineSetting.setLightingModel(self._finalSetting['Lighting']) engineSetting.setNativeImageCursorEnabled( self._finalSetting['NativeImageCursor']) engineSetting.setJoystickSupport(self._finalSetting['JoystickSupport']) try: engineSetting.setColorKeyEnabled( self._finalSetting['ColorKeyEnabled']) except: pass try: engineSetting.setColorKey(self._finalSetting['ColorKey'][0], self._finalSetting['ColorKey'][1], self._finalSetting['ColorKey'][2]) except: pass try: engineSetting.setWindowTitle(self._finalSetting['WindowTitle']) engineSetting.setWindowIcon(self._finalSetting['WindowIcon']) except: pass try: engineSetting.setFrameLimitEnabled( self._finalSetting['FrameLimitEnabled']) engineSetting.setFrameLimit(self._finalSetting['FrameLimit']) except: pass try: engineSetting.setMouseSensitivity( self._finalSetting['MouseSensitivity']) except: pass try: engineSetting.setMouseAccelerationEnabled( self._finalSetting['MouseAcceleration']) except: pass def initLogging(self): """ Initialize the LogManager. """ engineSetting = self.engine.getSettings() logmodules = self._setting.get("FIFE", "LogModules", ["controller"]) #log to both the console and log file self._log = fifelog.LogManager( self.engine, self._setting.get("FIFE", "LogToPrompt", False), self._setting.get("FIFE", "LogToFile", False)) self._log.setLevelFilter( self._setting.get("FIFE", "LogLevelFilter", fife.LogManager.LEVEL_DEBUG)) if logmodules: self._log.setVisibleModules(*logmodules) def createListener(self): """ This creates a default event listener, which will just close the program after pressing ESC. You should override this method to provide your own event handling. """ return ExitEventListener(self) def run(self): """ Initialize the event listener and event loop - and start it. """ eventlistener = self.createListener() self.engine.initializePumping() retval = self.mainLoop() self.engine.finalizePumping() self.engine.destroy() return retval def mainLoop(self): """ The programs main loop. Do not override this, instead provide your own L{_pump} method. You can call this recursively, e.g. to provide synchronous Dialogs :-) and break out of the current mainLoop by calling L{breakFromMainLoop}. It will return the argument passed to L{breakFromMainLoop}. """ self.returnValues.append(None) while not self.quitRequested: try: self.engine.pump() except fife.Exception as e: print(str(e)) self.quitRequested = True self._pump() if self.breakRequested: self.breakRequested = False break return self.returnValues.pop() def breakFromMainLoop(self, returnValue): """ Break from the currently running L{mainLoop}. The passed argument will be returned by the mainLoop. """ self.returnValues[-1] = returnValue self.breakRequested = True def _pump(self): """ Application pump. Derived classes can specialize this for unique behavior. This is called every frame. """ def quit(self): """ Quit the application. Really! """ self.quitRequested = True
import os, sys fife_path = os.path.join('..', 'fifengine', 'engine', 'python') if os.path.isdir(fife_path) and fife_path not in sys.path: sys.path.insert(0, fife_path) from fife.extensions.fife_settings import Setting from fife.extensions.basicapplication import ApplicationBase from scripts.common import eventlistenerbase from scripts.world import World settings = Setting(app_name="zombies", settings_file='settings.xml') class ApplicationListener(eventlistenerbase.EventListenerBase): def __init__(self, engine, world): super(ApplicationListener, self).__init__(engine, regKeys=True) self.engine = engine self.world = world class ZombiesApplication(ApplicationBase): def __init__(self, settings): super(ZombiesApplication, self).__init__(settings) self.world = World(self.engine) self.listener = ApplicationListener(self.engine, self.world) self.world.load('maps/country.xml') def main():
class ApplicationBase(object): """ ApplicationBase is an extendable class that provides a basic environment for a FIFE-based client. The unextended application reads in and initializes engine settings, sets up a simple event listener, and pumps the engine while listening for a quit message. Specialized applications can modify settings.py to change initial engine settings. They can provide their own event listener by overriding L{createListener}. And they can override the L{_pump} method to define runtime behavior of the application. """ def __init__(self, setting=None): if setting: self._setting = setting else: self._setting = Setting(app_name="", settings_file="./settings.xml", settings_gui_xml="") self.engine = fife.Engine() self.loadSettings() self.initLogging() self.engine.init() self._animationloader = XMLAnimationLoader(self.engine.getImagePool(), self.engine.getVFS()) self.engine.getAnimationPool().addResourceLoader(self._animationloader) pychan.init(self.engine, debug=self._setting.get("FIFE", "PychanDebug", False)) pychan.setupModalExecution(self.mainLoop, self.breakFromMainLoop) self.quitRequested = False self.breakRequested = False self.returnValues = [] def loadSettings(self): """ Load the settings from a python file and load them into the engine. Called in the ApplicationBase constructor. """ glyphDft = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?-+/():;%&`'*#=[]\\\"" engineSetting = self.engine.getSettings() engineSetting.setDefaultFontGlyphs(self._setting.get("FIFE", "FontGlyphs", glyphDft)) engineSetting.setDefaultFontPath(self._setting.get("FIFE", "Font", "fonts/FreeSans.ttf")) engineSetting.setDefaultFontSize(self._setting.get("FIFE", "DefaultFontSize", 12)) engineSetting.setBitsPerPixel(self._setting.get("FIFE", "BitsPerPixel", 0)) engineSetting.setInitialVolume(self._setting.get("FIFE", "InitialVolume", 5.0)) engineSetting.setSDLRemoveFakeAlpha(self._setting.get("FIFE", "SDLRemoveFakeAlpha", 1)) (width, height) = self._setting.get("FIFE", "ScreenResolution", "1024x768").split("x") engineSetting.setScreenWidth(int(width)) engineSetting.setScreenHeight(int(height)) engineSetting.setRenderBackend(self._setting.get("FIFE", "RenderBackend", "OpenGL")) engineSetting.setFullScreen(self._setting.get("FIFE", "FullScreen", False)) try: engineSetting.setColorKeyEnabled(self._setting.get("FIFE", "ColorKeyEnabled", False)) except: pass try: key = self._setting.get("FIFE", "ColorKey", "255,0,255").split(",") engineSetting.setColorKey(int(key[0]), int(key[1]), int(key[2])) except: pass try: engineSetting.setWindowTitle(self._setting.get("FIFE", "WindowTitle", "No window title set")) engineSetting.setWindowIcon(self._setting.get("FIFE", "WindowIcon", "")) except: pass try: engineSetting.setImageChunkingSize(self._setting.get("FIFE", "ImageChunkSize", 256)) except: pass def initLogging(self): """ Initialize the LogManager. """ engineSetting = self.engine.getSettings() logmodules = self._setting.get("FIFE", "LogModules", ["controller"]) # log to both the console and log file self._log = fifelog.LogManager( self.engine, self._setting.get("FIFE", "LogToPrompt", "0"), self._setting.get("FIFE", "LogToFile", "0") ) self._log.setLevelFilter(self._setting.get("FIFE", "LogLevelFilter", fife.LogManager.LEVEL_DEBUG)) if logmodules: self._log.setVisibleModules(*logmodules) def createListener(self): """ This creates a default event listener, which will just close the program after pressing ESC. You should override this method to provide your own event handling. """ return ExitEventListener(self) def run(self): """ Initialize the event listener and event loop - and start it. """ eventlistener = self.createListener() self.engine.initializePumping() retval = self.mainLoop() self.engine.finalizePumping() self.engine.destroy() return retval def mainLoop(self): """ The programs main loop. Do not override this, instead provide your own L{_pump} method. You can call this recursively, e.g. to provide synchronous Dialogs :-) and break out of the current mainLoop by calling L{breakFromMainLoop}. It will return the argument passed to L{breakFromMainLoop}. """ self.returnValues.append(None) while not self.quitRequested: try: self.engine.pump() except RuntimeError, e: print str(e) self._pump() if self.breakRequested: self.breakRequested = False break return self.returnValues.pop()
from fife import fife from .common.eventlistenerbase import EventListenerBase from agents.hero import Hero from fife.extensions.fife_settings import Setting TDS = Setting(app_name='zombies', settings_file='settings.xml') class MapListener(fife.MapChangeListener): def __init__(self, map): fife.MapChangeListener.__init__(self) map.addChangeListener(self) class World(EventListenerBase): def __init__(self, engine): super(World, self).__init__(engine, regKeys=True) self.engine = engine self.eventmanager = engine.getEventManager() self.model = engine.getModel() # self.filename = '' # self.pump_ctr = 0 # for testing purposis # self.ctrldown = False # self.instancemenu = None self.instance_to_agent = {} # self.dynamic_widgets = {} def load(self, filename): self.filename = filename # self.reset()
from fife.extensions.savers import saveMapFile from fife.extensions.fife_settings import Setting from fife.extensions import pychan from fife.extensions.pychan import widgets from scripts.common.eventlistenerbase import EventListenerBase from scripts.util import line_points from agents.survivor import Survivor from fife.extensions.fife_settings import Setting from controller import Controller from fife.fife import DoublePoint3D from scripts.agents.mob import * from scripts.extscheduler import ExtScheduler TDS = Setting(app_name="zombieswtf") DEFAULT_GLOBAL_LIGHT = { "R" : 0.0, "G" : 0.0, "B" : 0.0, "A" : 0.985 } DEFAULT_SURVIVOR_LIGHT = { "intensity" : 1, "radius" : 100, "subdivs" : 32, "xstretch" : 3, "ystretch" : 2, "R" : 150,
# You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ######################################################################## # Start Zombies WTF import sys, os, re, math, random, shutil from fife import fife print "Using the FIFE python module found here: ", os.path.dirname( fife.__file__) from scripts.application import ZombiesWTF from fife.extensions.fife_settings import Setting TDS = Setting(app_name="zombieswtf") def main(): app = ZombiesWTF() app.run() if __name__ == '__main__': if TDS.get("FIFE", "ProfilingOn"): import hotshot, hotshot.stats print "Starting profiler" prof = hotshot.Profile("fife.prof") prof.runcall(main) prof.close() print "analysing profiling results"
import os import sys fife_path = os.path.join('..', '..', 'engine', 'python', 'fife') if os.path.isdir(fife_path) and fife_path not in sys.path: sys.path.insert(0, fife_path) from fife import fife print("Using the FIFE python module found here: ", os.path.dirname(fife.__file__)) from fife.extensions.fife_settings import Setting from scripts.fife_test import FifeTestApplication TDS = Setting(app_name="fife_test", settings_file="./settings.xml") def main(): app = FifeTestApplication(TDS) app.run() if __name__ == '__main__': if TDS.get("FIFE", "ProfilingOn"): import hotshot import hotshot.stats print("Starting profiler") prof = hotshot.Profile("fife.prof") prof.runcall(main) prof.close()
def main(parser): opts, args = parser.parse_args() levels = {'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL} #TODO: setup formating logging.basicConfig(filename=opts.logfile, level=levels[opts.loglevel]) logger = logging.getLogger('parpg') try: old_path = sys.path if opts.fife_path: sys.path = [opts.fife_path] import fife except ImportError: logger.critical("Could not import fife module. Please install fife or set the --fife-path command line value") parser.print_help() sys.exit(1) finally: sys.path = old_path from fife.extensions.fife_settings import Setting settings = Setting(settings_file="settings.xml") data_dir = abspath(settings.get("parpg","DataPath")) settings.set("parpg", "DataPath", data_dir) settings.set("FIFE", "WindowIcon", data_dir + "/" + settings.get("FIFE", "WindowIcon")) settings.set("FIFE", "Font", data_dir + "/" + settings.get("FIFE", "Font")) from parpg.application import PARPGApplication from parpg.common import utils # enable psyco if available and in settings file try: import psyco psyco_available = True except ImportError: logger.warning('Psyco Acceleration unavailable') psyco_available = False if settings.get("fife", "UsePsyco"): if psyco_available: psyco.full() logger.info('Psyco Acceleration enabled') else: logger.warning('Please install psyco before attempting to use it' 'Psyco Acceleration disabled') else: logger.info('Psycho Acceleration disabled') # run the game app = PARPGApplication(settings) app.run()
def cb_map_loaded(self, game_map): """Callback for when a map was loaded""" fife_map = game_map.fife_map for layer in self.editor.get_layers(fife_map): for instance in layer.getInstances(): filename = instance.getObject().getFilename() map_name = fife_map.getId() self.editor.increase_refcount(filename, map_name) def quit(self): """ Quit the application. Really! """ if self.current_dialog: return if self.editor_gui.ask_save_changed(): self.quitRequested = True if __name__ == '__main__': SETTING = Setting(app_name="frpg-editor", settings_file="./settings.xml") APP = EditorApplication(SETTING) VIEW = GameSceneView(APP) CONTROLLER = EditorController(VIEW, APP) APP.push_mode(CONTROLLER) CONTROLLER.listener.setup_cegui() APP.setup() APP.run()
import math, random from fife.extensions import pychan from fife.extensions.pychan import widgets from fife.extensions.pychan.internal import get_manager from scripts.common.eventlistenerbase import EventListenerBase from fife.extensions.savers import saveMapFile from fife.extensions.soundmanager import SoundManager from agents.hero import Hero from agents.girl import Girl from agents.cloud import Cloud from agents.beekeeper import Beekeeper from agents.agent import create_anonymous_agents from fife.extensions.fife_settings import Setting TDS = Setting(app_name="rio_de_hola") class MapListener(fife.MapChangeListener): def __init__(self, map): fife.MapChangeListener.__init__(self) map.addChangeListener(self) def onMapChanged(self, map, changedLayers): return print "Changes on map ", map.getId() for layer in map.getLayers(): print layer.getId() print " ", ["%s, %x" % (i.getObject().getId(), i.getChangeInfo()) for i in layer.getChangedInstances()] def onLayerCreate(self, map, layer): pass
import os import sys fife_path = os.path.join('..','..','engine','python','fife') if os.path.isdir(fife_path) and fife_path not in sys.path: sys.path.insert(0,fife_path) from fife import fife print "Using the FIFE python module found here: ", os.path.dirname(fife.__file__) from fife.extensions.fife_settings import Setting from scripts.fife_test import FifeTestApplication TDS = Setting(app_name="fife_test", settings_file="./settings.xml") def main(): app = FifeTestApplication(TDS) app.run() if __name__ == '__main__': if TDS.get("FIFE", "ProfilingOn"): import hotshot import hotshot.stats print "Starting profiler" prof = hotshot.Profile("fife.prof") prof.runcall(main) prof.close() print "analysing profiling results"
class Fife(ApplicationBase): """ """ def __init__(self): self.pump = [] self._setup_settings() self.engine = fife.Engine() self.loadSettings() self.engine_settings = self.engine.getSettings() self.pychan = pychan self._doQuit = False self._doBreak = False self._doReturn = None self._gotInited = False self.emitter = {} self.emitter['bgsound'] = None self.emitter['effects'] = None self.emitter['speech'] = None def _setup_settings(self): self._setting = Setting(app_name="unknownhorizons", settings_file=PATHS.USER_CONFIG_FILE, settings_gui_xml="content/gui/settings.xml", changes_gui_xml="content/gui/requirerestart.xml") self._setting.setGuiStyle("book") #self.createAndAddEntry(self, module, name, widgetname, applyfunction=None, initialdata=None, requiresrestart=False) self._setting.createAndAddEntry(UH_MODULE, "AutosaveInterval", "autosaveinterval", initialdata=range(0, 60, 2)) self._setting.createAndAddEntry(UH_MODULE, "AutosaveMaxCount", "autosavemaxcount", initialdata=range(1, 30)) self._setting.createAndAddEntry(UH_MODULE, "QuicksaveMaxCount", "quicksavemaxcount", initialdata=range(1, 30)) self._setting.createAndAddEntry(FIFE_MODULE, "BitsPerPixel", "screen_bpp", initialdata=[0, 16, 32], requiresrestart=True) languages_map = dict(find_available_languages()) languages_map[_('System default')] = '' self._setting.createAndAddEntry(UH_MODULE, "Language", "language", applyfunction=self.update_languages, initialdata= [LANGUAGENAMES[x] for x in sorted(languages_map.keys())]) self._setting.createAndAddEntry(UH_MODULE, "VolumeMusic", "volume_music", applyfunction=lambda x: self.set_volume_music(x)) self._setting.createAndAddEntry(UH_MODULE, "VolumeEffects", "volume_effects", applyfunction=lambda x: self.set_volume_effects(x)) self._setting.entries[FIFE_MODULE]['PlaySounds'].applyfunction = lambda x: self.setup_sound() self._setting.entries[FIFE_MODULE]['PlaySounds'].requiresrestart = False def update_languages(self, data=None): if data is None: data = self._setting.get(UH_MODULE, "Language") languages_map = dict(find_available_languages()) languages_map['System default'] = '' symbol = None if data == unicode('System default'): symbol = 'System default' else: for key, value in LANGUAGENAMES.iteritems(): if value == data: symbol = key assert symbol is not None, "Something went badly wrong with the translation update!" + \ " Searching for: " + str(data) + " in " + str(LANGUAGENAMES) index = sorted(languages_map.keys()).index(symbol) name, position = sorted(languages_map.items())[index] try: if name != 'System default': trans = gettext.translation('unknownhorizons', position, languages=[name]) trans.install(unicode=1) else: gettext.install('unknownhorizons', 'build/mo', unicode=1) name = '' except IOError: print _("Configured language %(lang)s at %(place)s could not be loaded") % {'lang': settings.language.name, 'place': settings.language.position} install('unknownhorizons', 'build/mo', unicode=1) self._setting.set(UH_MODULE, "Language", 'System default') update_all_translations() def init(self): """ """ logToPrompt, logToFile, debugPychan = True, True, False if self._gotInited: return #start modules self.log = fifelog.LogManager(self.engine, 1 if logToPrompt else 0, 1 if logToFile else 0) #self.log.setVisibleModules('all') self.engine.init() #temporarily select a random music file to play. TODO: Replace with proper playlist self.ingame_music = glob.glob('content/audio/music/*.ogg') self.menu_music = glob.glob('content/audio/music/menu/*.ogg') self.initial_menu_music_element = None self.next_menu_music_element = None self.menu_music_played = 0 #init stuff self.eventmanager = self.engine.getEventManager() #self.eventmanager.setNonConsumableKeys([fife.Key.ESCAPE, fife.Key.F10]) self.guimanager = self.engine.getGuiManager() self.console = self.guimanager.getConsole() self.soundmanager = self.engine.getSoundManager() self.soundmanager.init() self.setup_sound() self.imagepool = self.engine.getImagePool() self.animationpool = self.engine.getAnimationPool() self.animationloader = SQLiteAnimationLoader() self.animationpool.addResourceLoader(self.animationloader) #Set game cursor self.cursor = self.engine.getCursor() self.default_cursor_image = self.imagepool.addResourceFromFile('content/gui/images/misc/cursor.png') self.tearing_cursor_image = self.imagepool.addResourceFromFile('content/gui/images/misc/cursor_tear.png') self.cursor.set(fife.CURSOR_IMAGE, self.default_cursor_image) #init pychan self.pychan.init(self.engine, debugPychan) self.pychan.setupModalExecution(self.loop, self.breakLoop) from gui.widgets.inventory import Inventory from gui.widgets.imagefillstatusbutton import ImageFillStatusButton from gui.widgets.progressbar import ProgressBar from gui.widgets.toggleimagebutton import ToggleImageButton from gui.widgets.tooltip import TooltipIcon, TooltipButton, TooltipLabel, TooltipProgressBar pychan.widgets.registerWidget(Inventory) pychan.widgets.registerWidget(ImageFillStatusButton) pychan.widgets.registerWidget(ProgressBar) pychan.widgets.registerWidget(ToggleImageButton) pychan.widgets.registerWidget(TooltipIcon) pychan.widgets.registerWidget(TooltipButton) pychan.widgets.registerWidget(TooltipLabel) pychan.widgets.registerWidget(TooltipProgressBar) for name, stylepart in horizons.gui.style.STYLES.iteritems(): self.pychan.manager.addStyle(name, stylepart) self.pychan.loadFonts("content/fonts/libertine.fontdef") self._gotInited = True def setup_sound(self): if self._setting.get(FIFE_MODULE, "PlaySounds"): self.enable_sound() else: self.disable_sound() def get_fife_setting(self, settingname): return self._setting.get(FIFE_MODULE, settingname) def get_uh_setting(self, settingname): return self._setting.get(UH_MODULE, settingname) def enable_sound(self): """Enable all sound and start playing music.""" if self._setting.get(FIFE_MODULE, "PlaySounds"): # Set up sound if it is enabled self.soundclippool = self.engine.getSoundClipPool() self.emitter['bgsound'] = self.soundmanager.createEmitter() self.emitter['bgsound'].setGain(self._setting.get(UH_MODULE, "VolumeMusic")) self.emitter['bgsound'].setLooping(False) self.emitter['effects'] = self.soundmanager.createEmitter() self.emitter['effects'].setGain(self._setting.get(UH_MODULE, "VolumeEffects")) self.emitter['effects'].setLooping(False) self.emitter['speech'] = self.soundmanager.createEmitter() self.emitter['speech'].setGain(self._setting.get(UH_MODULE, "VolumeEffects")) self.emitter['speech'].setLooping(False) self.emitter['ambient'] = [] self.music_rand_element = random.randint(0, len(self.menu_music) - 1) self.initial_menu_music_element = self.music_rand_element self.check_music() # Start background music ExtScheduler().add_new_object(self.check_music, self, loops=-1) def disable_sound(self): """Disable all sound outputs.""" if self.emitter['bgsound'] is not None: self.emitter['bgsound'].reset() if self.emitter['effects'] is not None: self.emitter['effects'].reset() if self.emitter['speech'] is not None: self.emitter['speech'].reset() ExtScheduler().rem_call(self, self.check_music) def check_music(self): """Used as callback to check if music is still running or if we have to load the next song.""" if self.menu_music_played == 0: if self.initial_menu_music_element == self.next_menu_music_element: self.ingame_music.extend(self.menu_music) self.music = self.ingame_music self.music_rand_element = random.randint(0, len(self.ingame_music) - 1) self.menu_music_played = 1 else: self.music = self.menu_music if hasattr(self, '_bgsound_old_byte_pos') and hasattr(self, '_bgsound_old_sample_pos'): if self._bgsound_old_byte_pos == self.emitter['bgsound'].getCursor(fife.SD_BYTE_POS) and self._bgsound_old_sample_pos == self.emitter['bgsound'].getCursor(fife.SD_SAMPLE_POS): self.music_rand_element = self.music_rand_element + 1 if \ self.music_rand_element + 1 < len(self.music) else 0 self.play_sound('bgsound', self.music[self.music_rand_element]) if self.menu_music_played == 0: self.next_menu_music_element = self.music_rand_element self._bgsound_old_byte_pos, self._bgsound_old_sample_pos = \ self.emitter['bgsound'].getCursor(fife.SD_BYTE_POS), \ self.emitter['bgsound'].getCursor(fife.SD_SAMPLE_POS) def play_sound(self, emitter, soundfile): """Plays a soundfile on the given emitter. @param emitter: string with the emitters name in horizons.main.fife.emitter that is to play the sound @param soundfile: string containing the path to the soundfile""" if self._setting.get(FIFE_MODULE, "PlaySounds"): emitter = self.emitter[emitter] assert emitter is not None, "You need to supply a initialised emitter" assert soundfile is not None, "You need to supply a soundfile" emitter.reset() emitter.setSoundClip(horizons.main.fife.soundclippool.addResourceFromFile(soundfile)) emitter.play() def set_volume(self, emitter_name, value): """Sets the volume on the emitter specified by emitter_name. @param emitter_name: string with the emitters name, used as key for the self.emitter dict @param value: double which value the emitter is to be set to range[0, 1] """ if self._setting.get(FIFE_MODULE, "PlaySounds"): self.emitter[emitter_name].setGain(value) def set_volume_music(self, value): """Sets the volume of the music emitters to 'value'. @param value: double - value that's used to set the emitters gain. """ if self._setting.get(FIFE_MODULE, "PlaySounds"): self.emitter['bgsound'].setGain(value) def set_volume_effects(self, value): """Sets the volume of effects, speech and ambient emitters. @param value: double - value that's used to set the emitters gain. """ if self._setting.get(FIFE_MODULE, "PlaySounds"): self.emitter['effects'].setGain(value) self.emitter['speech'].setGain(value) for e in self.emitter['ambient']: e.setGain(value*2) def run(self): """ """ self.init() self.engine.initializePumping() self.loop() self.engine.finalizePumping() def loop(self): """ """ while not self._doQuit: try: self.engine.pump() except fife.Exception, e: print e.getMessage() break for f in self.pump: f() if self._doBreak: self._doBreak = False return self._doReturn self.__kill_engine()
sys.path.insert(0, fife_path) from fife import fife print "Using the FIFE python module found here: ", os.path.dirname( fife.__file__) from fife.extensions import * from scripts import world from scripts.common import eventlistenerbase from fife.extensions.basicapplication import ApplicationBase from fife.extensions import pychan from fife.extensions.pychan import widgets from fife.extensions.fife_settings import Setting TDS = Setting(app_name="shooter", settings_file="./settings.xml", settings_gui_xml="") TDS.setAvailableScreenResolutions(["1024x768"]) class ApplicationListener(eventlistenerbase.EventListenerBase): def __init__(self, engine, world): super(ApplicationListener, self).__init__(engine, regKeys=True, regCmd=True, regMouse=False, regConsole=True, regWidget=True) self._engine = engine self._world = world
from fife import fife print "Using the FIFE python module found here: ", os.path.dirname( fife.__file__) from fife.extensions import * from scripts import world from scripts.common import eventlistenerbase from fife.extensions.basicapplication import ApplicationBase from fife.extensions import pychan from fife.extensions.pychan import widgets from fife.extensions.pychan.internal import get_manager from fife.extensions.fife_settings import Setting from fife.extensions.fife_utils import getUserDataDirectory TDS = Setting(app_name="rio_de_hola") class ApplicationListener(eventlistenerbase.EventListenerBase): def __init__(self, engine, world): super(ApplicationListener, self).__init__(engine, regKeys=True, regCmd=True, regMouse=False, regConsole=True, regWidget=True) self.engine = engine self.world = world engine.getEventManager().setNonConsumableKeys([ fife.Key.ESCAPE, ])
from fife.extensions import pychan from fife.extensions.pychan.tools import callbackWithArguments as cbwa from fife.extensions.pychan.internal import get_manager from events import * from gui import ToolBar, action from gui.action import Action, ActionGroup from gui.filemanager import FileManager from gui.mainwindow import MainWindow from gui.mapeditor import MapEditor from gui.menubar import Menu, MenuBar from gui.error import ErrorDialog from mapview import MapView from fife.extensions.fife_settings import Setting TDS = Setting(app_name="editor") def getEditor(): """ Returns the Global editor instance """ if Editor.editor is None: Editor(None) return Editor.editor class Editor(ApplicationBase, MainWindow): """ Editor sets up all subsystems and provides access to them """ editor = None def __init__(self, options, mapfile, *args, **kwargs): Editor.editor = self
import sys, os, re fife_path = os.path.join('..', '..', 'engine', 'python') if os.path.isdir(fife_path) and fife_path not in sys.path: sys.path.insert(0, fife_path) from fife import fife from fife.extensions.fife_settings import Setting from fife.extensions.cegui.ceguibasicapplication import CEGUIApplicationBase import PyCEGUI print "Using the FIFE python module found here: ", os.path.dirname( fife.__file__) DemoSettings = Setting(app_name="CEGUI Demo") class CEGUIDemo(CEGUIApplicationBase): def __init__(self, setting=None): super(CEGUIDemo, self).__init__(setting) self._loadSchemes() root = myRoot = PyCEGUI.WindowManager.getSingleton().createWindow( "DefaultWindow", "_MasterRoot") PyCEGUI.System.getSingleton().setGUISheet(myRoot) newWindow = PyCEGUI.WindowManager.getSingleton().loadWindowLayout( "MyConsole.layout", "second_") root.addChildWindow(newWindow)
if os.path.isdir(fife_path) and fife_path not in sys.path: sys.path.insert(0,fife_path) from fife import fife print "Using the FIFE python module found here: ", os.path.dirname(fife.__file__) from fife.extensions import * from scripts import world from scripts.common import eventlistenerbase from fife.extensions.basicapplication import ApplicationBase from fife.extensions import pychan from fife.extensions.pychan import widgets from fife.extensions.fife_settings import Setting TDS = Setting(app_name="shooter", settings_file="./settings.xml", settings_gui_xml="") TDS.setAvailableScreenResolutions(["1024x768"]) class ApplicationListener(eventlistenerbase.EventListenerBase): def __init__(self, engine, world): super(ApplicationListener, self).__init__(engine,regKeys=True,regCmd=True, regMouse=False, regConsole=True, regWidget=True) self._engine = engine self._world = world self._quit = False def keyPressed(self, evt): keyval = evt.getKey().getValue() keystr = evt.getKey().getAsString().lower() consumed = False