source: trunk/game/run.py @ 254

Revision 254, 7.4 KB checked in by tZee_parpg, 10 years ago (diff)

#65 Call of loading function changed.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1#!/usr/bin/python
2
3#   This program is free software: you can redistribute it and/or modify
4#   it under the terms of the GNU General Public License as published by
5#   the Free Software Foundation, either version 3 of the License, or
6#   (at your option) any later version.
7
8#   This program is distributed in the hope that it will be useful,
9#   but WITHOUT ANY WARRANTY; without even the implied warranty of
10#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11#   GNU General Public License for more details.
12
13#   You should have received a copy of the GNU General Public License
14#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
16import sys, os, shutil, re
17
18from scripts.common import utils
19# add paths to the swig extensions
20utils.addPaths ('../../engine/swigwrappers/python', '../../engine/extensions')
21
22if not os.path.exists('settings.xml'):
23    shutil.copyfile('settings-dist.xml', 'settings.xml')
24
25import fife_compat, fife, fifelog
26import pychan
27from scripts import world
28from scripts import engine
29from scripts.engine import Engine
30from scripts.common import eventlistenerbase
31from basicapplication import ApplicationBase
32from settings import Setting
33
34TDS = Setting()
35
36"""This folder holds the main meta-data for PARPG. This file should be
37   minimal, since folding code into the controller with MVC is usually bad
38   All game and logic and data is held held and referenced in /scripts/engine.py
39   All fife stuff goes in /scripts/world.py"""
40
41class ApplicationListener(eventlistenerbase.EventListenerBase):
42    def __init__(self, engine, world, model):
43        """Initialise the instance.
44           @type engine: ???
45           @param engine: ???
46           @type world: ???
47           @param world: ???
48           @type model: engine.Engine
49           @param model: an instance of PARPG's engine"""
50        super(ApplicationListener, self).__init__(engine,
51                                                  regKeys=True,regCmd=True,
52                                                  regMouse=False, 
53                                                  regConsole=True,
54                                                  regWidget=True)
55        self.engine = engine
56        self.world = world
57        self.model = model
58        engine.getEventManager().setNonConsumableKeys([fife.Key.ESCAPE,])
59        self.quit = False
60        self.aboutWindow = None
61
62    def quitGame(self):
63        """Forces a quit game on next cycle.
64           @return: None"""
65        self.quit = True
66
67    def onConsoleCommand(self, command):
68        """
69        Called on every console comand
70        @type command: string
71        @param command: the command to run
72        @return: result
73        """
74        result = None
75
76        if (command.lower() in ('quit', 'exit')):
77            self.quitGame()
78
79        load_regex = re.compile('^load')
80        l_matches = load_regex.match(command.lower())
81        if (l_matches != None):
82            end_load = l_matches.end()
83            try:
84                l_args = command.lower()[end_load+1:].strip()
85                l_path, l_filename = l_args.split(' ')
86                self.model.load(l_path, l_filename)
87                result = "Loaded file: " + l_path + l_filename
88
89            except Exception, l_error:
90                self.engine.getGuiManager().getConsole().println('Error: ' + str(l_error))
91
92        save_regex = re.compile('^save')
93        s_matches = save_regex.match(command.lower())
94        if (s_matches != None):
95            end_save = s_matches.end()
96            try:
97                s_args = command.lower()[end_save+1:].strip()
98                s_path, s_filename = s_args.split(' ')
99                self.model.save(s_path, s_filename)
100                result = "Saved to file: " + s_path + s_filename
101
102            except Exception, s_error:
103                self.engine.getGuiManager().getConsole().println('Error: ' + str(s_error))
104                   
105        else:
106            try:
107                result = str(eval(command))
108            except Exception, e:
109                result = str(e)
110
111        if not result:
112            result = 'no result'
113       
114        return result
115
116    def onCommand(self, command):
117        """Enables the game to be closed via the 'X' button on the window frame
118           @type command: fife.Command
119           @param command: The command to read.
120           @return: None"""
121        if(command.getCommandType() == fife.CMD_QUIT_GAME):
122            self.quit = True
123            command.consume()
124
125class PARPG(ApplicationBase):
126    """Main Application class
127       We use an MVC data model.
128       self.world is our view,self.engine is our model
129       This file is the minimal controller"""
130    def __init__(self):
131        """Initialise the instance.
132           @return: None"""
133        super(PARPG,self).__init__()
134        self.world = world.World(self.engine)
135        self.model = engine.Engine(self.world)
136        self.world.data = self.model
137        self.listener = ApplicationListener(self.engine,self.world,self.model)
138        self.world.quitFunction = self.listener.quitGame
139        self.model.loadMap("main_map", str(TDS.readSetting("MapFile")))   
140        pychan.init(self.engine, debug = True)
141
142    def loadSettings(self):
143        """Load the settings from a python file and load them into the engine.
144           Called in the ApplicationBase constructor.
145           @return: None"""
146        import settings
147        self.settings = settings
148        eSet=self.engine.getSettings()
149        eSet.setDefaultFontGlyphs(str(TDS.readSetting("FontGlyphs",
150                                                      strip=False)))
151        eSet.setDefaultFontPath(str(TDS.readSetting("Font")))
152        eSet.setBitsPerPixel(int(TDS.readSetting("BitsPerPixel")))
153        eSet.setInitialVolume(float(TDS.readSetting("InitialVolume")))
154        eSet.setSDLRemoveFakeAlpha(int(TDS.readSetting("SDLRemoveFakeAlpha")))
155        eSet.setScreenWidth(int(TDS.readSetting("ScreenWidth")))
156        eSet.setScreenHeight(int(TDS.readSetting("ScreenHeight")))
157        eSet.setRenderBackend(str(TDS.readSetting("RenderBackend")))
158        eSet.setFullScreen(int(TDS.readSetting("FullScreen")))
159        try:
160            eSet.setWindowTitle(str(TDS.readSetting("WindowTitle")))
161            eSet.setWindowIcon(str(TDS.readSetting("WindowIcon")))
162        except:
163            pass           
164        try:
165            eSet.setImageChunkingSize(int(TDS.readSetting("ImageChunkSize")))
166        except:
167            pass
168
169    def initLogging(self):
170        """Initialize the LogManager.
171           @return: None"""
172        LogModules = TDS.readSetting("LogModules",type='list')
173        self.log = fifelog.LogManager(self.engine,
174                                      int(TDS.readSetting("LogToPrompt")),
175                                      int(TDS.readSetting("LogToFile")))
176        if(LogModules):
177            self.log.setVisibleModules(*LogModules)
178
179    def createListener(self):
180        """@return: None"""
181        # already created in constructor
182        # but if we don't put one here, Fife gets all fussy :-)
183        pass
184
185    def _pump(self):
186        """Main game loop.
187           There are in fact 2 main loops, this one and the one in World.
188           @return: None"""
189        if self.listener.quit:
190            self.breakRequested = True
191        else:
192            self.model.pump()
193            self.world.pump()
194
195def main():
196    """Application code starts from here"""
197    app = PARPG()
198    app.run()
199
200if __name__ == '__main__':
201    main()
202
Note: See TracBrowser for help on using the repository browser.