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

Revision 55, 6.1 KB checked in by maximinus_parpg, 11 years ago (diff)

Objects now loaded from seperate XML file.
Cleaned up some small areas in various .py files
Added crate details.
Added some simple documentation in world.py
Removed some remaining RIO code that was not needed.

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