source: trunk/game/scripts/world.py @ 326

Revision 326, 10.8 KB checked in by eliedebrauwer, 10 years ago (diff)

Ticket #117: Patch by eliedebrauwer, fixed load/save game callback, due to refactoring (see ticket #2) variable and function names got mixed up. fixes[s:trac, t:117]

  • Property svn:eol-style set to native
Line 
1#!/usr/bin/python
2
3#   This file is part of PARPG.
4
5#   PARPG is free software: you can redistribute it and/or modify
6#   it under the terms of the GNU General Public License as published by
7#   the Free Software Foundation, either version 3 of the License, or
8#   (at your option) any later version.
9
10#   PARPG is distributed in the hope that it will be useful,
11#   but WITHOUT ANY WARRANTY; without even the implied warranty of
12#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13#   GNU General Public License for more details.
14
15#   You should have received a copy of the GNU General Public License
16#   along with PARPG.  If not, see <http://www.gnu.org/licenses/>.
17
18import time
19import fife
20import pychan
21from sounds import SoundEngine
22from datetime import date
23from scripts.common.eventlistenerbase import EventListenerBase
24from local_loaders.loaders import loadMapFile
25from sounds import SoundEngine
26from settings import Setting
27from scripts import hud
28from scripts.popups import *
29from pychan.tools import callbackWithArguments as cbwa
30from map import Map
31
32TDS = Setting()
33
34# this file should be the meta-file for all FIFE-related code
35# engine.py handles is our data model, whilst this is our view
36# in order to not replicate data, some of our data model will naturally
37# reside on this side of the fence (PC xpos and ypos, for example).
38# we should aim to never replicate any data as this leads to maintainance
39# issues (and just looks plain bad).
40# however, any logic needed to resolve this should sit in engine.py
41
42class World(EventListenerBase):
43    """World holds the data needed by fife to render the engine
44       The engine keeps a copy of this class"""
45    def __init__(self, engine):
46        """Constructor for engine
47           @type engine: fife.Engine
48           @param engine: A fife.Engine instance
49           @return: None"""
50        super(World, self).__init__(engine, reg_mouse=True, reg_keys=True)
51        # self.engine is a fife.Engine object, not an Engine object
52        self.engine = engine
53        self.event_manager = engine.getEventManager()
54        self.quitFunction = None
55       
56        # self.data is an engine.Engine object, but is set in run.py
57        self.data = None
58        self.mouseCallback = None
59
60        # self.map is a Map object, set to none here
61        self.active_map = None
62        self.maps = {}
63
64        # setup the inventory model
65        # make slot 'A1' and 'A3' container daggers
66        inv_model = {'A1':'dagger01', 'A3':'dagger01'}
67
68        hud_callbacks = {
69            'saveGame': self.saveGame,
70            'loadGame': self.loadGame,
71            'quitGame': self.quitGame,
72        }
73        self.hud = hud.Hud(self.engine, TDS, inv_model, hud_callbacks)
74        self.action_number = 1
75
76        # init the sound
77        self.sounds = SoundEngine(engine)
78       
79        # don't force restart if skipping to new section
80        if (TDS.readSetting("PlaySounds") == "1"):
81            if(self.sounds.music_init == False):
82                self.sounds.playMusic("/music/preciouswasteland.ogg")
83               
84    def quitGame(self):
85        """Quits the game
86        @return: None"""
87        self.quitFunction()
88
89    def saveGame(self, *args, **kwargs):
90        """Saves the game state
91           @return: None"""
92        print args
93        print kwargs
94        self.data.save(*args, **kwargs)
95
96    def loadGame(self, *args, **kwargs):
97        """Loads the game state
98           @return: None"""
99        print self.data
100        self.data.load(*args, **kwargs)
101       
102    def loadMap(self, map_name, filename):
103        """Loads a map and stores it under the given name in the maps list.
104           @type map_name: text
105           @param map_name: The name of the map to load
106           @type filename: text
107           @param filename: File which contains the map to be loaded
108           @return: None
109        """
110        if not map_name in self.maps:
111            """Need to set active map before we load it because the map
112            loader uses call backs that expect to find an active map.
113            This needs to be reworked.
114            """
115            map = Map(self.engine, self.data)
116            self.maps[map_name] = map       
117            self.setActiveMap(map_name)
118            map.load(filename)
119   
120    def setActiveMap(self, map_name):
121        """Sets the active map that is to be rendered.
122           @type map_name: text
123           @param map_name: The name of the map to load
124           @return: None
125        """
126        self.active_map = self.maps[map_name]
127        self.active_map.makeActive()
128
129    def displayObjectText(self, obj, text):
130        """Display on screen the text of the object over the object.
131           @type obj: fife.instance
132           @param obj: object to draw over
133           @type text: text
134           @param text: text to display over object
135           @return: None"""
136        obj.say(str(text), 1000)
137
138    # all key / mouse event handling routines go here
139    def keyPressed(self, evt):
140        """Whenever a key is pressed, fife calls this routine.
141           @type evt: fife.event
142           @param evt: The event that fife caught
143           @return: None"""
144        key = evt.getKey()
145        key_val = key.getValue()
146
147        if(key_val == key.Q):
148            # we need to quit the game
149            self.hud.quitGame()
150        if(key_val == key.T):
151            self.active_map.toggle_renderer('GridRenderer')
152        if(key_val == key.F1):
153            # display the help screen and pause the game
154            self.hud.displayHelp()
155        if(key_val == key.F5):
156            # logic would say we use similar code to above and toggle
157            # logic here does not work, my friend :-(
158            self.cord_render.setEnabled(not self.cord_render.isEnabled())
159        if(key_val == key.F7):
160            # F7 saves a screenshot to fife/clients/parpg/screenshots
161            t = "screenshots/screen-%s-%s.png" % \
162                    (date.today().strftime('%Y-%m-%d'),\
163                    time.strftime('%H-%M-%S'))
164            print "PARPG: Saved:",t
165            self.engine.getRenderBackend().captureScreen(t)
166        if(key_val == key.F10):
167            # F10 shows/hides the console
168            self.engine.getGuiManager().getConsole().toggleShowHide()
169        if(key_val == key.I):
170            # I opens and closes the inventory
171            self.hud.toggleInventory()
172        if(key_val == key.A):
173            # A adds a test action to the action box
174            # The test actions will follow this format: Action 1,
175            # Action 2, etc.
176            self.hud.addAction("Action " + str(self.action_number))
177            self.action_number += 1
178        if(key_val == key.ESCAPE):
179            # Escape brings up the main menu
180            self.hud.displayMenu()
181            # Hide the quit menu
182            self.hud.quit_window.hide()
183        if(key_val == key.M):
184            self.sounds.toggleMusic()
185
186    def mouseReleased(self, evt):
187        """If a mouse button is released, fife calls this routine.
188           We want to wait until the button is released, because otherwise
189           pychan captures the release if a menu is opened.
190           @type evt: fife.event
191           @param evt: The event that fife caught
192           @return: None"""
193        self.hud.hideContextMenu()
194        scr_point = fife.ScreenPoint(evt.getX(), evt.getY())
195        if(evt.getButton() == fife.MouseEvent.LEFT):
196            self.data.handleMouseClick(self.getCoords(scr_point))     
197        elif(evt.getButton() == fife.MouseEvent.RIGHT):
198            # is there an object here?
199            instances = self.active_map.cameras['main'].\
200                            getMatchingInstances(scr_point, \
201                                                 self.active_map.agent_layer)
202            info = None
203            for inst in instances:
204                # check to see if this is an active item
205                if(self.data.objectActive(inst.getId())):           
206                    # yes, get the data
207                    info = self.data.getItemActions(inst.getId())
208                    break
209               
210            # take the menu items returned by the engine or show a
211            # default menu if no items   
212            data = info or \
213                [["Walk", "Walk here", self.onWalk, self.getCoords(scr_point)]]
214            # show the menu
215            self.hud.showContextMenu(data, (scr_point.x, scr_point.y))
216
217    def onWalk(self, click):
218        """Callback sample for the context menu."""
219        self.hud.hideContainer()
220        self.data.game_state.PC.run(click)
221
222    def teleport(self, position):
223        """Called when a door is used that moves a player to a new
224           location on the same map. the setting of position may want
225           to be created as its own method down the road.
226           
227           @type position: String Tuple
228           @param position: X,Y coordinates passed from enigine.changeMap
229           @return: fife.Location
230        """
231        coord = fife.DoublePoint3D(float(position[0]), float(position[1]), 0)
232        location = fife.Location(self.active_map.agent_layer)
233        location.setMapCoordinates(coord)
234        self.data.game_state.PC.teleport(location)
235
236    def mouseMoved(self, evt):
237        """Called when the mouse is moved
238           @type evt: fife.event
239           @param evt: The event that fife caught
240           @return: None"""
241        click = fife.ScreenPoint(evt.getX(), evt.getY())
242        i=self.active_map.cameras['main'].getMatchingInstances(click, \
243                                                self.active_map.agent_layer)
244        # no object returns an empty tuple
245        if(i != ()):
246            for obj in i:
247                # check to see if this in our list at all
248                if(self.data.objectActive(obj.getId())):
249                    # yes, so outline
250                    self.active_map.outline_render.addOutlined(obj, 0, \
251                                                               137, 255, 2)
252                    # get the text
253                    item = self.data.objectActive(obj.getId())
254                    if(item is not None):
255                        self.displayObjectText(obj, item.name)
256        else:
257            # erase the outline
258            self.active_map.outline_render.removeAllOutlines()
259
260    def getCoords(self, click):
261        """Get the map location x, y cords from the screen co-ords
262           @type click: fife.ScreenPoint
263           @param click: Screen co-ords
264           @rtype: fife.Location
265           @return: The map co-ords"""
266        coord = self.active_map.cameras["main"].toMapCoordinates(click, False)
267        coord.z = 0
268        location = fife.Location(self.active_map.agent_layer)
269        location.setMapCoordinates(coord)
270        return location
271
272    def pump(self):
273        """Routine called during each frame. Our main loop is in ./run.py
274           We ignore this main loop (but FIFE complains if it is missing)."""
275        pass
Note: See TracBrowser for help on using the repository browser.