source: trunk/game/scripts/engine.py @ 342

Revision 341, 11.8 KB checked in by eliedebrauwer, 10 years ago (diff)

Ticket #128. Fix by octavio, PEP-8 code cleanup. (I plea guilty for the semi-colons). fixes[s:trac, t:128]

  • 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
18# there should be NO references to FIFE here!
19import pickle
20import sys
21from gamestate import GameState
22from objects import *
23from objects.action import *
24
25
26class Engine:
27    """Engine holds the logic for the game.
28       Since some data (object position and so forth) is held in the
29       fife, and would be pointless to replicate, we hold a instance of
30       the fife view here. This also prevents us from just having a
31       function heavy controller."""
32   
33    def __init__(self, view):
34        """Initialize the instance.
35           @type view: world
36           @param view: A world instance
37           @return: None"""
38        # a World object (the fife stuff, essentially)
39        self.view = view
40        self.map_change = False
41        self.load_saver = False
42        self.savegame = None
43        self.game_state = GameState()
44        self.pc_run = 1
45        self.target_position = None
46        self.target_map_name = None
47        self.target_map_file = None
48
49    def save(self, path, filename):
50        """Writes the saver to a file.
51           @type filename: string
52           @param filename: the name of the file to write to
53           @return: None"""
54        fname = '/'.join([path, filename])
55        try:
56            f = open(fname, 'w')
57        except(IOError):
58            sys.stderr.write("Error: Can't find save game: " + fname + "\n")
59            return
60       
61        # can't pickle SwigPyObjects
62        behaviours = {}
63        behaviour_player = self.game_state.PC.behaviour
64        self.game_state.PC.behaviour = None
65       
66        # Backup the behaviours
67        for map_id in self.game_state.objects:
68            behaviours[map_id] = {}
69            for (object_id, npc) in self.game_state.objects[map_id].items():
70                if npc.trueAttr("NPC"):
71                    behaviours[map_id][object_id] = npc.behaviour
72                    npc.behaviour = None
73       
74        # Pickle it
75        pickle.dump(self.game_state, f)
76        f.close()
77       
78        # Restore behaviours
79        for map_id in behaviours:
80            for (object_id, behaviour) in behaviours[map_id].items():
81                self.game_state.objects[map_id][object_id].behaviour = \
82                    behaviours[map_id][object_id]
83               
84        self.game_state.PC.behaviour = behaviour_player
85
86    def load(self, filename):
87        """Loads a saver from a file.
88           @type filename: string
89           @param filename: the name of the file (including path) to load from
90           @return: None"""
91       
92        # TODO
93        # Remove what we are currently working with
94        print "TODO: load"
95        self.view.active_map.view.clearCameras()
96        self.view.active_map.model.deleteMaps()
97       
98        try:
99            f = open(filename, 'r')
100        except(IOError):
101            sys.stderr.write("Error: Can't find save game file\n")
102            return
103        self.game_state = pickle.load(f)
104        f.close()
105       
106        # Make sure we're on the right map
107        if self.game_state.current_map_file:
108            self.loadMap(self.game_state.current_map_name, \
109                         self.game_state.current_map_file) 
110
111    def createObject (self, layer, attributes, instance):
112        """Create an object and add it to the current map.
113           @type layer: fife.Layer
114           @param layer: FIFE layer object exists in
115           @type attributes: Dictionary
116           @param attributes: Dictionary of all object attributes
117           @type instance: fife.Instance
118           @param instance: FIFE instance corresponding to the object
119           @return: None
120        """
121        # create the extra data
122        extra = {}
123        extra['agent_layer'] = layer
124        extra['engine'] = self
125       
126        obj = createObject(attributes, extra)
127       
128        if obj.trueAttr("PC"):
129            self.addPC(layer, obj, instance)
130        else:
131            self.addObject(layer, obj, instance)
132
133       
134
135    def addPC(self, layer, pc, instance):
136        """Add the PC to the map
137           @type layer: fife.Layer
138           @param layer: FIFE layer object exists in
139           @type pc: PlayerCharacter
140           @param pc: PlayerCharacter object
141           @type instance: fife.Instance
142           @param instance: FIFE instance of PC
143           @return: None
144        """
145        # For now we copy the PC, in the future we will need to copy
146        # PC specifics between the different PC's
147        self.game_state.PC = pc
148        self.game_state.PC.setup()
149
150    def addObject(self, layer, obj, instance):
151        """Adds an object to the map.
152           @type layer: fife.Layer
153           @param layer: FIFE layer object exists in
154           @type obj: GameObject
155           @param obj: corresponding object class
156           @type instance: fife.Instance
157           @param instance: FIFE instance of object
158           @return: None
159        """
160
161        ref = self.game_state.getObjectById(obj.ID, \
162                                            self.game_state.current_map_name) 
163        if ref is None:
164            # no, add it to the game state
165            self.game_state.objects[self.game_state.current_map_name][obj.ID] \
166                                                                          = obj
167        else:
168            # yes, use the current game state data
169            obj.X = ref.X
170            obj.Y = ref.Y
171            obj.gfx = ref.gfx 
172             
173        if obj.trueAttr("NPC"):
174            # create the agent
175            obj.setup()
176           
177            # create the PC agent
178            obj.start()
179
180    def objectActive(self, ident):
181        """Given the objects ID, pass back the object if it is active,
182           False if it doesn't exist or not displayed
183           @type ident: string
184           @param ident: ID of object
185           @rtype: boolean
186           @return: Status of result (True/False)"""
187        for i in \
188           self.game_state.getObjectsFromMap(self.game_state.current_map_name):
189            if (i.ID == ident):
190                # we found a match
191                return i
192        # no match
193        return False
194
195    def getItemActions(self, obj_id):
196        """Given the objects ID, return the text strings and callbacks.
197           @type obj_id: string
198           @param obj_id: ID of object
199           @rtype: list
200           @return: List of text and callbacks"""
201        actions = []
202        # note: ALWAYS check NPC's first!
203        obj = self.game_state.getObjectById(obj_id, \
204                                            self.game_state.current_map_name)
205       
206        if obj is not None:
207            if obj.trueAttr("NPC"):
208                # keep it simple for now, None to be replaced by callbacks
209                actions.append(["Talk", "Talk", self.initTalk, obj])
210                actions.append(["Attack", "Attack", self.nullFunc, obj])
211            else:
212                actions.append(["Examine", "Examine", \
213                                self.game_state.PC.approach, [obj.X, obj.Y], \
214                                ExamineBoxAction(self, obj.name, obj.text)])
215                # is it a Door?
216                if obj.trueAttr("door"):
217                    actions.append(["Change Map", "Change Map", \
218                       self.game_state.PC.approach, [obj.X, obj.Y], \
219                            ChangeMapAction(self, obj.target_map_name, \
220                                obj.target_map, obj.target_pos)])
221                # is it a container?
222                if obj.trueAttr("container"):
223                    actions.append(["Open", "Open", 
224                                    self.game_state.PC.approach, \
225                                    [obj.X, obj.Y], \
226                                    OpenBoxAction(self, "Box")])
227                # can you pick it up?
228                if obj.trueAttr("carryable"):
229                    actions.append(["Pick Up", "Pick Up", self.nullFunc, obj])
230
231        return actions
232   
233    def nullFunc(self, userdata):
234        """Sample callback for the context menus."""
235        print userdata
236   
237    def initTalk(self, npcInfo):
238        """ Starts the PC talking to an NPC. """
239        # TODO: work more on this when we get NPCData and HeroData straightened
240        # out
241        npc = self.game_state.getObjectById(npcInfo.ID, \
242                                            self.game_state.current_map_name)
243        self.game_state.PC.approach([npc.getLocation().\
244                                     getLayerCoordinates().x, \
245                                     npc.getLocation().\
246                                     getLayerCoordinates().y], \
247                                     TalkAction(self, npc))
248
249    def loadMap(self, map_name, map_file):
250        """Load a new map.
251           @type map_name: string
252           @param map_name: Name of the map to load
253           @type map_file: string
254           @param map_file: Filename of map file to load
255           @return: None"""
256        self.game_state.current_map_file = map_file
257        self.game_state.current_map_name = map_name
258        self.view.loadMap(map_name, str(map_file))
259
260        # If the map has been loaded, we might need to add some
261        # agents to the PC and NPS
262        for map_id in self.game_state.objects:
263            for (object_id, npc) in self.game_state.objects[map_id].items():
264                if npc.trueAttr("NPC") and npc.behaviour == None:
265                    npc.createBehaviour(self.view.active_map.agent_layer)
266
267        # Fix the player behaviour
268        if self.game_state.PC.behaviour == None:
269            self.game_state.PC.createBehaviour(self.view.active_map.agent_layer)
270
271        # create the PC agent
272        self.view.active_map.addPC()
273        self.game_state.PC.start()
274
275    def handleMouseClick(self, position):
276        """Code called when user left clicks the screen.
277           @type position: fife.ScreenPoint
278           @param position: Screen position of click
279           @return: None"""
280        if(self.pc_run == 1):
281            self.game_state.PC.run(position)
282        else:
283            self.game_state.PC.walk(position)
284
285    def changeMap(self, map_name, map_file, target_position):
286        """Registers for a map change on the next pump().
287           @type name_name: String
288           @param map_name: Id of the map to teleport to
289           @type map_file: String
290           @param map_file: Filename of the map to teleport to
291           @type target_position: Tuple
292           @param target_position: Position of PC on target map.
293           @return None"""
294        # set the parameters for the map change if moving to a new map
295        if map_name != self.game_state.current_map_name:
296            self.target_map_name = map_name
297            self.target_map_file = map_file
298            self.target_position = target_position
299            # issue the map change
300            self.map_change = True
301        else:
302            #set the player position on the current map
303            self.view.teleport(target_position)
304
305    def handleCommands(self):
306        if self.map_change:
307            self.loadMap(self.target_map_name, self.target_map_file)
308            self.view.teleport(self.target_position)
309            self.map_change = False
310       
311        if self.load_saver:
312            self.load(self.savegame)
313            self.load_saver = False
314
315    def pump(self):
316        """Main loop in the engine."""
317        self.handleCommands()
Note: See TracBrowser for help on using the repository browser.