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

Revision 56, 6.5 KB checked in by maximinus_parpg, 11 years ago (diff)

Added bhaydens screenshot code.
Added new screenshots folder.
Updated README.

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