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

Revision 294, 9.5 KB checked in by eliedebrauwer, 10 years ago (diff)

Ticket #: Patch by Elie De Brauwer, fixes the asymmetric main window and the quit button, fixes[s:trac, t:99]

  • 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 fife, time
19import pychan
20from sounds import SoundEngine
21from datetime import date
22from scripts.common.eventlistenerbase import EventListenerBase
23from local_loaders.loaders import loadMapFile
24from sounds import SoundEngine
25from settings import Setting
26from scripts import hud
27from scripts.popups import *
28from pychan.tools import callbackWithArguments as cbwa
29from map import Map
30
31TDS = Setting()
32
33# this file should be the meta-file for all FIFE-related code
34# engine.py handles is our data model, whilst this is our view
35# in order to not replicate data, some of our data model will naturally
36# reside on this side of the fence (PC xpos and ypos, for example).
37# we should aim to never replicate any data as this leads to maintainance
38# issues (and just looks plain bad).
39# however, any logic needed to resolve this should sit in engine.py
40
41class World(EventListenerBase):
42    """World holds the data needed by fife to render the engine
43       The engine keeps a copy of this class"""
44    def __init__(self, engine):
45        """Constructor for engine
46           @type engine: fife.Engine
47           @param engine: A fife.Engine instance
48           @return: None"""
49        super(World, self).__init__(engine, regMouse = True, regKeys = True)
50        # self.engine is a fife.Engine object, not an Engine object
51        self.engine = engine
52        self.eventmanager = engine.getEventManager()
53        self.quitFunction = None
54       
55        # self.data is an engine.Engine object, but is set in run.py
56        self.data = None
57        self.mouseCallback = None
58        self.obj_hash={}
59
60        # self.map is a Map object, set to none here
61        self.activeMap = 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        self.data.save(*args, **kwargs)
93
94    def loadGame(self, *args, **kwargs):
95        """Loads the game state
96           @return: None"""
97        self.data.load(*args, **kwargs)
98
99    def loadMap(self, mapname, filename):
100        """Loads a map an stores it under the given name in the maps list.
101        """
102        map = Map(self.engine, self.data)
103       
104        """Need to set active map before we load it because the map
105        loader uses call backs that expect to find an active map.
106        This needs to be reworked.
107        """
108        self.maps[mapname] = map
109        self.setActiveMap(mapname)
110
111        map.load(filename)
112
113   
114    def setActiveMap(self, mapname):
115        """Sets the active map that is to be rendered.
116        """
117        self.activeMap = self.maps[mapname]
118        self.activeMap.makeActive()
119
120    def displayObjectText(self, obj, text):
121        """Display on screen the text of the object over the object.
122           @type obj: fife.instance
123           @param obj: object to draw over
124           @type text: text
125           @param text: text to display over object
126           @return: None"""
127        obj.say(str(text), 1000)
128
129    # all key / mouse event handling routines go here
130    def keyPressed(self, evt):
131        """Whenever a key is pressed, fife calls this routine.
132           @type evt: fife.event
133           @param evt: The event that fife caught
134           @return: None"""
135        key = evt.getKey()
136        keyval = key.getValue()
137
138        if(keyval == key.Q):
139            # we need to quit the game
140            self.hud.quitGame()
141        if(keyval == key.T):
142            self.activeMap.toggle_renderer('GridRenderer')
143        if(keyval == key.F1):
144            # display the help screen and pause the game
145            self.hud.displayHelp()
146        if(keyval == key.F5):
147            # logic would say we use similar code to above and toggle
148            # logic here does not work, my friend :-(
149            self.cord_render.setEnabled(not self.cord_render.isEnabled())
150        if(keyval == key.F7):
151            # F7 saves a screenshot to fife/clients/parpg/screenshots
152            t = "screenshots/screen-%s-%s.png" % (date.today().strftime('%Y-%m-%d'),
153                                                  time.strftime('%H-%M-%S'))
154            print "PARPG: Saved:",t
155            self.engine.getRenderBackend().captureScreen(t)
156        if(keyval == key.F10):
157            # F10 shows/hides the console
158            self.engine.getGuiManager().getConsole().toggleShowHide()
159        if(keyval == key.I):
160            # I opens and closes the inventory
161            self.hud.toggleInventory()
162        if(keyval == key.A):
163            # A adds a test action to the action box
164            # The test actions will follow this format: Action 1, Action 2, etc.
165            self.hud.addAction("Action " + str(self.action_number))
166            self.action_number += 1
167        if(keyval == key.ESCAPE):
168            # Escape brings up the main menu
169            self.hud.displayMenu()
170            # Hide the quit menu
171            self.hud.quitWindow.hide()
172        if(keyval == key.M):
173            self.sounds.toggleMusic()
174
175    def mouseReleased(self, evt):
176        """If a mouse button is released, fife calls this routine.
177           We want to wait until the button is released, because otherwise
178           pychan captures the release if a menu is opened.
179           @type evt: fife.event
180           @param evt: The event that fife caught
181           @return: None"""
182        self.hud.hideContextMenu() # hide the context menu in case it is displayed
183        scr_point = fife.ScreenPoint(evt.getX(), evt.getY())
184        if(evt.getButton() == fife.MouseEvent.LEFT):
185            self.data.handleMouseClick(self.getCoords(scr_point))     
186        elif(evt.getButton() == fife.MouseEvent.RIGHT):
187            # is there an object here?
188            instances = self.activeMap.cameras['main'].getMatchingInstances(scr_point, self.activeMap.agent_layer)
189            info = None
190            for inst in instances:
191                # check to see if this is an active item
192                if(self.data.objectActive(inst.getId())):           
193                    # yes, get the data
194                    info = self.data.getItemActions(inst.getId())
195                    break
196               
197            # take the menu items returned by the engine or show a default menu if no items   
198            data = info or [["Walk", "Walk here", self.onWalk, self.getCoords(scr_point)]]
199            # show the menu
200            self.hud.showContextMenu(data, (scr_point.x, scr_point.y))
201
202    def onWalk(self, click):
203        """Callback sample for the context menu."""
204        self.hud.hideContainer()
205        self.data.gameState.PC.run(click)
206
207    def mouseMoved(self, evt):
208        """Called when the mouse is moved
209           @type evt: fife.event
210           @param evt: The event that fife caught
211           @return: None"""
212        click = fife.ScreenPoint(evt.getX(), evt.getY())
213        i=self.activeMap.cameras['main'].getMatchingInstances(click, self.activeMap.agent_layer)
214        # no object returns an empty tuple
215        if(i != ()):
216            for obj in i:
217                # check to see if this in our list at all
218                if(self.data.objectActive(obj.getId())):
219                    # yes, so outline
220                    self.activeMap.outline_render.addOutlined(obj, 0, 137, 255, 2)
221                    # get the text
222                    item = self.data.objectActive(obj.getId())
223                    if(item):
224                        self.displayObjectText(obj, item.name)
225        else:
226            # erase the outline
227            self.activeMap.outline_render.removeAllOutlines()
228
229    def getCoords(self, click):
230        """Get the map location x, y cords from the screen co-ords
231           @type click: fife.ScreenPoint
232           @param click: Screen co-ords
233           @rtype: fife.Location
234           @return: The map co-ords"""
235        coord = self.activeMap.cameras["main"].toMapCoordinates(click, False)
236        coord.z = 0
237        location = fife.Location(self.activeMap.agent_layer)
238        location.setMapCoordinates(coord)
239        return location
240
241    def pump(self):
242        """Routine called during each frame. Our main loop is in ./run.py
243           We ignore this main loop (but FIFE complains if it is missing)."""
244        pass
Note: See TracBrowser for help on using the repository browser.