source: trunk/PARPG/scripts/world.py @ 63

Revision 63, 7.4 KB checked in by bretzel_parpg, 11 years ago (diff)

Integrated the inventory into the PARPG demo.
Press I to show/hide the inventory.

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
19from datetime import date
20from scripts.common.eventlistenerbase import EventListenerBase
21from loaders import loadMapFile
22from agents.hero import Hero
23from agents.npc import NPC
24from settings import Setting
25from scripts import inventory
26
27TDS = Setting()
28
29# this file should be the meta-file for all FIFE-related code
30# engine.py handles is our data model, whilst this is our view
31# in order to not replicate data, some of our data model will naturally
32# reside on this side of the fence (PC xpos and ypos, for example).
33# we should aim to never replicate any data as this leads to maintainance
34# issues (and just looks plain bad).
35# however, any logic needed to resolve this should sit in engine.py
36
37class MapListener(fife.MapChangeListener):
38    """This class listens to changes happening on the map.
39       Since in theory we initiate these ourselves, do we need this class?"""
40    def __init__(self, map):
41        fife.MapChangeListener.__init__(self)
42
43    def onMapChanged(self, map, changedLayers):
44        pass
45
46    def onLayerCreate(self, map, layer):
47        pass
48
49    def onLayerDelete(self, map, layer):
50        pass
51
52class Map:
53    def __init__(self,fife_map):
54        self.listener=MapListener
55        self.map=fife_map
56
57class World(EventListenerBase):
58    """World holds the data needed by fife to render the engine
59       The engine keeps a copy of this class"""
60    def __init__(self, engine):
61        super(World, self).__init__(engine, regMouse=True, regKeys=True)
62        self.engine=engine
63        self.eventmanager=engine.getEventManager()
64        self.model=engine.getModel()
65        self.view=self.engine.getView()
66        self.quitFunction=None
67        self.inventoryShown = False
68        self.firstInventory = True
69        self.mouseCallback=None
70
71    def reset(self):
72        """Rest the map to default settings"""
73        self.transitions=[]
74        self.PC=None
75        self.npcs=[]
76        self.map,self.agent_layer=None,None
77        self.cameras={}
78        self.PC=None
79        self.npcs=[]
80        self.cur_cam2_x,self.initial_cam2_x,self.cam2_scrolling_right=0,0,True
81        self.target_rotation=0
82
83    def load(self,filename):
84        """Load a map given the filename
85           TODO: a map should only contain static items and floor tiles
86           Everything else should be loaded from the engine, because it
87           is subject to change"""
88        self.reset()
89        self.map=loadMapFile(filename,self.engine)
90        self.maplistener=MapListener(self.map)
91
92        # there must be a PC object on the objects layer!
93        self.agent_layer=self.map.getLayer('ObjectLayer')
94        # it's possible there's no transition layer
95        size=len('TransitionLayer')
96        for layer in self.map.getLayers():
97            # could be many layers, but hopefully no more than 3
98            if(layer.getId()[:size]=='TransitionLayer'):
99                self.transitions.append(self.map.getLayer(layer.getId()))
100
101        # init the camera
102        for cam in self.view.getCameras():
103            self.cameras[cam.getId()] = cam
104        self.view.resetRenderers()
105        self.target_rotation = self.cameras['main'].getRotation()
106        self.cord_render=self.cameras['main'].getRenderer('CoordinateRenderer')
107
108    def addPC(self,agent):
109        """Add the player character to the map"""
110        # actually this is real easy, we just have to
111        # attach the main camera to the PC
112        self.cameras['main'].attach(agent)
113   
114    def addObject(self,xpos,ypos,name):
115        """Add an object or an NPC to the map
116           It makes no difference to fife which is which"""
117        obj=self.agent_layer.createInstance(
118                self.model.getObject(str(name),"PARPG"),
119                fife.ExactModelCoordinate(xpos,ypos,0.0),str(name))
120        obj.setRotation(0)
121        fife.InstanceVisual.create(obj)
122
123    # all key / mouse event handling routines go here
124    def keyPressed(self, evt):
125        """When a key is depressed, fife calls this routine."""
126        key=evt.getKey()
127        keyval = key.getValue()
128
129        if(keyval==key.Q):
130            # we need to quit the game
131            self.quitGame()
132        if(keyval==key.T):
133            self.toggle_renderer('GridRenderer')
134        if(keyval==key.F1):
135            # display the help screen and pause the game
136            self.displayHelp()
137        if(keyval==key.F5):
138            # logic would say we use similar code to above and toggle
139            # logic here does not work, my friend :-(
140            self.cord_render.setEnabled(not self.cord_render.isEnabled())
141        if(keyval==key.F7):
142            # F7 saves a screenshot to fife/clients/parpg/screenshots
143            # TODO: add a time stamp as well as a date stamp
144            t="screenshots/screen-%s.png" % date.today().strftime('%Y-%m-%d')
145            self.engine.getRenderBackend().captureScreen(t)
146        if(keyval==key.I):
147            # show the inventory
148            if (self.firstInventory == True):
149                self.inventory = inventory.Inventory(self.engine)
150                self.firstInventory = False
151                self.inventoryShown = True
152
153            elif ((self.firstInventory == False) and 
154                  (self.inventoryShown == True)):
155                self.inventory.closeInventory()
156                self.inventoryShown = False
157
158            elif ((self.firstInventory == False) and
159                  (self.inventoryShown == False)):
160                self.inventory.showInventory()
161                self.inventoryShown = True
162
163    def mousePressed(self, evt):
164        """If a mouse button is pressed down, fife cals this routine
165           Currently we only check for a left click, and we assume this is on
166           the map"""
167        clickpoint = fife.ScreenPoint(evt.getX(), evt.getY())
168        if (evt.getButton()==fife.MouseEvent.LEFT):
169            target_mapcoord=self.cameras['main'].toMapCoordinates(clickpoint,
170                                                                  False)
171            target_mapcoord.z = 0
172            l=fife.Location(self.agent_layer)
173            l.setMapCoordinates(target_mapcoord)
174            self.mouseCallback(l)
175           
176    def toggle_renderer (self,r_name):
177        """Enable or disable the renderer named `r_name`"""
178        renderer = self.cameras['main'].getRenderer('GridRenderer')
179        renderer.setEnabled(not renderer.isEnabled())
180
181    def displayHelp(self):
182        """Displays the pop-up info and help screen"""
183        print "Help not yet coded"
184
185    def quitGame(self):
186        """Called when user requests to quit game
187           Just calls the ApplicationListener to do the quit"""
188        if(self.quitFunction!=None):
189            self.quitFunction()
190
191    def pump(self):
192        """Routine called during each frame. Our main loop is in ./run.py
193           We ignore this main loop (but FIFE complains if it is missing)"""
194        pass
195
Note: See TracBrowser for help on using the repository browser.