def __init__(self, app, engine, setting): super(World, self).__init__(engine, regKeys=True) self._applictaion = app self._engine = engine self._setting = setting self._timemanager = engine.getTimeManager() self._eventmanager = engine.getEventManager() self._model = engine.getModel() self._filename = '' self._keystate = { 'UP': False, 'DOWN': False, 'LEFT': False, 'RIGHT': False, 'CTRL': False, 'SPACE': False, } self._pump_ctr = 0 self._map = None self._scene = None self._paused = True self._pausedtime = 0 self._starttime = 0 self._soundmanager = SoundManager(self._engine) self._mainmenu = MainMenu(self, self._setting) self.showMainMenu() self._hudwindow = HeadsUpDisplay(self) self._hudwindow.hide() self._gameover = GameOverDisplay() self._gameover.hide() self._highscores = HighScores(self) self._highscores.hide() self._winner = WinnerDisplay() self._winner.hide() self._credits = CreditsDisplay(self) self._credits.hide() self._genericrenderer = None self._gamecomplete = False
def __init__(self, engine): super(World, self).__init__(engine, regMouse=True, regKeys=True) self.engine = engine self.eventmanager = engine.getEventManager() self.model = engine.getModel() self.filename = '' self.pump_ctr = 0 # for testing purposis self.ctrldown = False self.instancemenu = None self.instance_to_agent = {} self.dynamic_widgets = {} self.light_intensity = 1 self.light_sources = 0 self.lightmodel = int(TDS.get("FIFE", "Lighting")) self.soundmanager = SoundManager(self.engine) self.music = None
def __init__(self, app, engine, setting): super(World, self).__init__(engine, regKeys=True) self._applictaion = app self._engine = engine self._setting = setting self._timemanager = engine.getTimeManager() self._eventmanager = engine.getEventManager() self._model = engine.getModel() self.obj_loader = XMLObjectLoader( engine.getImagePool(), engine.getAnimationPool(), engine.getModel(), engine.getVFS() ) self._filename = '' self._keystate = { 'UP': False, 'DOWN': False, 'LEFT': False, 'RIGHT': False, 'CTRL': False, 'SPACE': False, } self._pump_ctr = 0 self._map = None self._scene = None self._paused = True self._pausedtime = 0 self._starttime = 0 self._soundmanager = SoundManager(self._engine) self._mainmenu = MainMenu(self, self._setting) self.showMainMenu() self._hudwindow = HeadsUpDisplay(self) self._hudwindow.hide() self._gameover = GameOverDisplay() self._gameover.hide() self._highscores = HighScores(self) self._highscores.hide() self._winner = WinnerDisplay() self._winner.hide() self._credits = CreditsDisplay(self) self._credits.hide() self._genericrenderer = None self._gamecomplete = False
def __init__(self, engine): super(World, self).__init__(engine, regMouse=True, regKeys=True) self.engine = engine self.eventmanager = engine.getEventManager() self.model = engine.getModel() self.filename = '' self.pump_ctr = 0 # for testing purposis self.ctrldown = False self.instancemenu = None self.instance_to_agent = {} self.dynamic_widgets = {} self.gui = None # Overwritten during GUI initialization self.light_intensity = 1 self.light_sources = 0 self.lightmodel = 1 # DK why self.soundmanager = SoundManager(self.engine) self.music = None
class World(EventListenerBase): """ The world! This class handles: setup of map view (cameras ...) loading the map GUI for right clicks handles mouse/key events which aren't handled by the GUI. ( by inheriting from EventlistenerBase ) That's obviously too much, and should get factored out. """ def __init__(self, engine): super(World, self).__init__(engine, regMouse=True, regKeys=True) self.engine = engine self.eventmanager = engine.getEventManager() self.model = engine.getModel() self.filename = '' self.pump_ctr = 0 # for testing purposis self.ctrldown = False self.instancemenu = None self.instance_to_agent = {} self.dynamic_widgets = {} self.gui = None # Overwritten during GUI initialization self.light_intensity = 1 self.light_sources = 0 self.lightmodel = 1 # DK why self.soundmanager = SoundManager(self.engine) self.music = None def show_instancemenu(self, clickpoint, location, instance): """ Build and show a popupmenu for an instance that the player clicked on. The available actions are dynamically added to the menu (and mapped to the onXYZ functions). """ if instance and instance.getFifeId() == self.mainAgent.agent.getFifeId(): # click on yourself return # Create the popup. self.build_instancemenu() self.instancemenu.clickpoint = clickpoint self.instancemenu.location = location self.instancemenu.instance = instance # Add the buttons according to circumstances. if instance: target_distance = self.mainAgent.agent.getLocation().getLayerDistanceTo(instance.getLocation()) else: target_distance = 0 if instance and self.instance_to_agent.has_key(instance.getFifeId()): target_agent = self.instance_to_agent[instance.getFifeId()] else: target_agent = None actionList = self.mainAgent.getActionsList(instance, target_agent, target_distance) for action in actionList: if self.dynamic_widgets.has_key(action): self.instancemenu.addChild(self.dynamic_widgets[action]) else: print "ERROR: no defined action %s for instance menu."%action # self.instancemenu.addChild(self.dynamic_widgets['inspect']) # if target_distance > 3.0: # self.instancemenu.addChild(self.dynamic_widgets['move']) # else: # if self.instance_to_agent.has_key(instance.getFifeId()): # self.instancemenu.addChild(self.dynamic_widgets['talk']) # if self.mainAgent == self.boy: # self.instancemenu.addChild(self.dynamic_widgets['kick']) # And show it :) self.instancemenu.position = (clickpoint.x, clickpoint.y) self.instancemenu.show() def build_instancemenu(self): """ Just loads the menu from an XML file and hooks the events up. The buttons are removed and later re-added if appropiate. """ self.hide_instancemenu() dynamicbuttons = ('move', 'talk', 'open', 'kick', 'inspect', 'pick', 'lay') self.instancemenu = pychan.loadXML('gui/xml/instancemenu.xml') self.instancemenu.mapEvents({ 'move' : lambda: self.onAction('move'), 'talk' : lambda: self.onAction('talk'), 'kick' : lambda: self.onAction('kick'), 'open' : lambda: self.onAction('open'), 'pick' : lambda: self.onAction('pick'), 'lay' : lambda: self.onAction('lay'), 'inspect' : lambda: self.onAction('inspect'), }) for btn in dynamicbuttons: self.dynamic_widgets[btn] = self.instancemenu.findChild(name=btn) self.instancemenu.removeAllChildren() def hide_instancemenu(self): if self.instancemenu: self.instancemenu.hide() def reset(self): """ Clear the agent information and reset the moving secondary camera state. """ if self.music: self.music.stop() self.map, self.agentlayer = None, None self.cameras = {} self.boy, self.girl, self.clouds, self.beekeepers = None, None, [], [] self.cur_cam2_x, self.initial_cam2_x, self.cam2_scrolling_right = 0, 0, True self.target_rotation = 0 self.instance_to_agent = {} def load(self, filename): """ Load a xml map and setup agents and cameras. """ self.filename = filename self.reset() loader = fife.MapLoader(self.engine.getModel(), self.engine.getVFS(), self.engine.getImageManager(), self.engine.getRenderBackend()) if loader.isLoadable(filename): self.map = loader.load(filename) self.initAgents() self.initCameras() #Set background color self.engine.getRenderBackend().setBackgroundColor(80,80,255) # play track as background music self.music = self.soundmanager.createSoundEmitter('music/hang.ogg') self.music.looping = True self.music.gain = 128 if int(Setting(app_name="rio_de_hola").get("FIFE", "PlaySounds")): self.music.play() self.soundActive = True else: self.soundActive = False def loose(self): self.cameras['main'].setOverlayColor(0,0,0,180) self.gui.youLoose() def win(self): self.cameras['main'].setOverlayColor(0,0,255,180) self.gui.youWin() def showItems(self, items): self.gui.showItems(items) def hideItems(self, items): self.gui.hideItems(items) def restart(self): self.model.deleteMaps() self.load(self.filename) def initAgents(self): """ Setup agents. For this techdemo we have a very simple 'active things on the map' model, which is called agents. All rio maps will have a separate layer for them. Note that we keep a mapping from map instances (C++ model of stuff on the map) to the python agents for later reference. """ self.agentlayer = self.map.getLayer('TechdemoMapGroundObjectLayer') self.boy = Boy(TDS, self.model, 'PC', self.agentlayer, self.soundmanager, world = self) self.instance_to_agent[self.boy.agent.getFifeId()] = self.boy self.mainAgent = self.boy self.boy.start() self.girl = Girl(TDS, self.model, 'NPC:girl', self.agentlayer, self.soundmanager, world = self, looseCallback = self.loose, updateLifeCallback = self.gui.girlLifeUpdate) self.instance_to_agent[self.girl.agent.getFifeId()] = self.girl self.girl.start() self.priest = Priest(TDS, self.model, 'priest', self.agentlayer, self.soundmanager, world = self) self.instance_to_agent[self.priest.agent.getFifeId()] = self.priest self.priest.start() self.chemist = Chemist(TDS, self.model, 'chemist', self.agentlayer, self.soundmanager, world = self, winCallback=self.win) self.instance_to_agent[self.chemist.agent.getFifeId()] = self.chemist self.chemist.start() self.bees = [] for i in xrange(num_bees): bee = Bee(TDS, self.model, 'bee' + str(i), self.agentlayer, self.soundmanager, girl = self.girl) self.instance_to_agent[bee.agent.getFifeId()] = bee bee.start() self.bees.append(bee) for i in xrange(12): dynamite = Dynamite(TDS, self.model, 'dyn_' + str(i), self.agentlayer, self.soundmanager, bees=self.bees, girl=self.girl) self.instance_to_agent[dynamite.agent.getFifeId()] = dynamite dynamite.start() self.beekeepers = create_anonymous_agents(TDS, self.model, 'beekeeper', self.agentlayer, Beekeeper, self.soundmanager) for beekeeper in self.beekeepers: self.instance_to_agent[beekeeper.agent.getFifeId()] = beekeeper beekeeper.start() moveObject(self.agentlayer.getInstance('flask0'), x=3.5, y=9.5) moveObject(self.agentlayer.getInstance('coins0'), x=-18, y=-15) moveObject(self.agentlayer.getInstance('coins1'), x=-22.5, y=-14.5) moveObject(self.agentlayer.getInstance('coins2'), x=-18, y=-14.5) def initCameras(self): """ Before we can actually see something on screen we have to specify the render setup. This is done through Camera objects which offer a viewport on the map. For this techdemo two cameras are used. One follows the boy(!) via 'attach' the other one scrolls around a bit (see the pump function). """ camera_prefix = self.filename.rpartition('.')[0] # Remove file extension camera_prefix = camera_prefix.rpartition('/')[2] # Remove path camera_prefix += '_' self.target_rotation = 0 self.cameras = {} for cam in self.map.getCameras(): camera_id = cam.getId().replace(camera_prefix, '') self.cameras[camera_id] = cam cam.resetRenderers() self.cameras['main'].attach(self.mainAgent.agent) # Floating text renderers currntly only support one font. # ... so we set that up. # You'll se that for our demo we use a image font, so we have to specify the font glyphs # for that one. renderer = fife.FloatingTextRenderer.getInstance(self.cameras['main']) textfont = get_manager().createFont('fonts/rpgfont.png', 0, str(TDS.get("FIFE", "FontGlyphs"))); renderer.setFont(textfont) renderer.activateAllLayers(self.map) renderer.setBackground(100, 255, 100, 165) renderer.setBorder(50, 255, 50) renderer.setEnabled(True) # Activate the grid renderer on all layers renderer = self.cameras['main'].getRenderer('GridRenderer') renderer.activateAllLayers(self.map) # The small camera shouldn't be cluttered by the 'humm di dums' of our boy. # So we disable the renderer simply by setting its font to None. renderer = fife.FloatingTextRenderer.getInstance(self.cameras['small']) renderer.setFont(None) # The following renderers are used for debugging. # Note that by default ( that is after calling View.resetRenderers or Camera.resetRenderers ) # renderers will be handed all layers. That's handled here. renderer = fife.CoordinateRenderer.getInstance(self.cameras['main']) renderer.setFont(textfont) renderer.clearActiveLayers() renderer.addActiveLayer(self.map.getLayer(str(TDS.get("rio", "CoordinateLayerName")))) renderer = self.cameras['main'].getRenderer('QuadTreeRenderer') renderer.setEnabled(True) renderer.clearActiveLayers() if str(TDS.get("rio", "QuadTreeLayerName")): renderer.addActiveLayer(self.map.getLayer(str(TDS.get("rio", "QuadTreeLayerName")))) # Fog of War stuff renderer = fife.CellRenderer.getInstance(self.cameras['main']) renderer.setEnabled(True) renderer.clearActiveLayers() renderer.addActiveLayer(self.map.getLayer('TechdemoMapGroundObjectLayer')) concimg = self.engine.getImageManager().load("misc/black_cell.png") maskimg = self.engine.getImageManager().load("misc/mask_cell.png") renderer.setConcealImage(concimg) renderer.setMaskImage(maskimg) renderer.setFogOfWarLayer(self.map.getLayer('TechdemoMapGroundObjectLayer')) #disable FoW by default. Users can turn it on with the 'f' key. renderer.setEnabledFogOfWar(False) # Set up the second camera # NOTE: We need to explicitly call setLocation, there's a bit of a messup in the Camera code. self.cameras['small'].setLocation(self.boy.agent.getLocation()) self.cameras['small'].attach(self.girl.agent) self.cameras['small'].setOverlayColor(100,0,0,100) self.cameras['small'].setEnabled(False) self.target_rotation = self.cameras['main'].getRotation() def save(self, filename): saveMapFile(filename, self.engine, self.map) def getInstancesAt(self, clickpoint): """ Query the main camera for instances on our active(agent) layer. """ return self.cameras['main'].getMatchingInstances(clickpoint, self.agentlayer) def getLocationAt(self, clickpoint): """ Query the main camera for the Map location (on the agent layer) that a screen point refers to. """ target_mapcoord = self.cameras['main'].toMapCoordinates(clickpoint, False) target_mapcoord.z = 0 location = fife.Location(self.agentlayer) location.setMapCoordinates(target_mapcoord) return location def keyPressed(self, evt): if self.girl.dead: return keyval = evt.getKey().getValue() keystr = evt.getKey().getAsString().lower() if keystr == 't': r = self.cameras['main'].getRenderer('GridRenderer') r.setEnabled(not r.isEnabled()) elif keystr == 'c': r = self.cameras['main'].getRenderer('CoordinateRenderer') r.setEnabled(not r.isEnabled()) elif keystr == 's': c = self.cameras['small'] c.setEnabled(not c.isEnabled()) elif keystr == 'r': self.model.deleteMaps() self.load(self.filename) self.gui.girlLifeUpdate(100) self.startTime = datetime.datetime.now() elif keystr == 'f': renderer = fife.CellRenderer.getInstance(self.cameras['main']) renderer.setEnabledFogOfWar(not renderer.isEnabledFogOfWar()) self.cameras['main'].refresh() elif keystr == 'o': self.target_rotation = (self.target_rotation + 90) % 360 elif keystr == '2': self.lightIntensity(0.1) elif keystr == '1': self.lightIntensity(-0.1) elif keystr == '5': self.lightSourceIntensity(25) elif keystr == '4': self.lightSourceIntensity(-25) elif keystr == '0' or keystr == fife.Key.NUM_0: if self.ctrldown: self.cameras['main'].setZoom(1.0) elif keyval in (fife.Key.LEFT_CONTROL, fife.Key.RIGHT_CONTROL): self.ctrldown = True else: self.mainAgent.keyPressed(keyval) def keyReleased(self, evt): if self.girl.dead: return keyval = evt.getKey().getValue() if keyval in (fife.Key.LEFT_CONTROL, fife.Key.RIGHT_CONTROL): self.ctrldown = False def mouseWheelMovedUp(self, evt): if self.girl.dead: return if self.ctrldown: self.cameras['main'].setZoom(self.cameras['main'].getZoom() * 1.05) def mouseWheelMovedDown(self, evt): if self.girl.dead: return if self.ctrldown: self.cameras['main'].setZoom(self.cameras['main'].getZoom() / 1.05) def changeRotation(self): """ Smoothly change the main cameras rotation until the current target rotation is reached. """ if "main" in self.cameras: currot = self.cameras['main'].getRotation() if self.target_rotation != currot: self.cameras['main'].setRotation((currot + 5) % 360) def mousePressed(self, evt): if evt.isConsumedByWidgets() or self.girl.dead: return clickpoint = fife.ScreenPoint(evt.getX(), evt.getY()) if (evt.getButton() == fife.MouseEvent.LEFT): self.hide_instancemenu() self.mainAgent.run(self.getLocationAt(clickpoint) ) if (evt.getButton() == fife.MouseEvent.RIGHT): location = self.getLocationAt(clickpoint) instances = self.getInstancesAt(clickpoint) #print "selected instances on agent layer: ", [i.getObject().getId() for i in instances] if instances: self.show_instancemenu(clickpoint, location, instances[0]) else: self.show_instancemenu(clickpoint, location, None) def mouseMoved(self, evt): if not self.girl or self.girl.dead: return renderer = fife.InstanceRenderer.getInstance(self.cameras['main']) renderer.removeAllOutlines() pt = fife.ScreenPoint(evt.getX(), evt.getY()) instances = self.getInstancesAt(pt); agent_names = set([y.agent.getObject().getId() for _, y in self.instance_to_agent.iteritems()]) agent_names.add('flask_map') agent_names.add('coins_map') for i in instances: aid = i.getObject().getId() me = self.mainAgent.agent.getObject().getId() if aid in agent_names and aid != me: renderer.addOutlined(i, 173, 255, 47, 2) def lightIntensity(self, value): if self.light_intensity+value <= 1 and self.light_intensity+value >= 0: self.light_intensity = self.light_intensity + value if self.lightmodel == 1: self.cameras['main'].setLightingColor(self.light_intensity, self.light_intensity, self.light_intensity) def lightSourceIntensity(self, value): if self.light_sources+value <= 255 and self.light_sources+value >= 0: self.light_sources = self.light_sources+value renderer = fife.LightRenderer.getInstance(self.cameras['main']) renderer.removeAll("beekeeper_simple_light") renderer.removeAll("boy") renderer.removeAll("girl_simple_light") if self.lightmodel == 1: node = fife.RendererNode(self.boy.agent) renderer.addSimpleLight("boy", node, self.light_sources, 64, 32, 1, 1, 255, 255, 255) node = fife.RendererNode(self.girl.agent) renderer.addSimpleLight("girl_simple_light", node, self.light_sources, 64, 32, 1, 1, 255, 255, 255) for beekeeper in self.beekeepers: node = fife.RendererNode(beekeeper.agent) renderer.addSimpleLight("beekeeper_simple_light", node, self.light_sources, 120, 32, 1, 1, 255, 255, 255) def onConsoleCommand(self, command): result = '' try: result = str(eval(command)) except Exception, e: result = str(e) return result
class World(EventListenerBase): """ The world! This class handles: setup of map view (cameras ...) loading the map handles mouse/key events which aren't handled by the GUI. ( by inheriting from EventlistenerBase ) """ def __init__(self, app, engine, setting): super(World, self).__init__(engine, regKeys=True) self._applictaion = app self._engine = engine self._setting = setting self._timemanager = engine.getTimeManager() self._eventmanager = engine.getEventManager() self._model = engine.getModel() self._filename = '' self._keystate = { 'UP': False, 'DOWN': False, 'LEFT': False, 'RIGHT': False, 'CTRL': False, 'SPACE': False, } self._pump_ctr = 0 self._map = None self._scene = None self._paused = True self._pausedtime = 0 self._starttime = 0 self._soundmanager = SoundManager(self._engine) self._mainmenu = MainMenu(self, self._setting) self.showMainMenu() self._hudwindow = HeadsUpDisplay(self) self._hudwindow.hide() self._gameover = GameOverDisplay() self._gameover.hide() self._highscores = HighScores(self) self._highscores.hide() self._winner = WinnerDisplay() self._winner.hide() self._credits = CreditsDisplay(self) self._credits.hide() self._genericrenderer = None self._gamecomplete = False def showMainMenu(self): if self._scene: self._paused = True cont = True else: cont = False self._mainmenu.show(cont) def showCredits(self): self._credits.show() def showHighScores(self): self._highscores.show() def quit(self): self.reset() self._soundmanager.destroy() self._applictaion.requestQuit() def reset(self): if self._map: self._model.deleteMap(self._map) self._map = None self.cameras = {} if self._scene: self._scene.destroyScene() self._scene = None self._gamecomplete = False def loadLevel(self, filename): """ Load a xml map and setup cameras. """ self.resetKeys() self._filename = filename self.reset() loader = fife.MapLoader(self._engine.getModel(), self._engine.getVFS(), self._engine.getImageManager(), self._engine.getRenderBackend()) if loader.isLoadable(self._filename): self._map = loader.load(self._filename) loader.loadImportFile("objects/projectiles/bullet1/object.xml") loader.loadImportFile("objects/projectiles/fireball/object.xml") self._scene = Scene(self, self._engine, self._map.getLayer('objects'), self._soundmanager) self._scene.initScene(self._map) self.initCameras() self._hudwindow.show() self._gameover.hide() self._winner.hide() self._starttime = self._timemanager.getTime() self._genericrenderer = fife.GenericRenderer.getInstance( self.cameras['main']) self._genericrenderer.clearActiveLayers() self._genericrenderer.addActiveLayer(self._map.getLayer('boundingbox')) self._genericrenderer.setEnabled(True) def renderBoundingBox(self, obj): """ Just a hack to render an objects bounding box. """ bbox = copy.copy(obj.boundingbox) #apply the object layer scale bbox.x /= 0.25 bbox.y /= 0.25 bbox.w /= 0.25 bbox.h /= 0.25 obj_topleft = fife.ExactModelCoordinate(bbox.x, bbox.y) obj_topright = fife.ExactModelCoordinate(bbox.x + bbox.w, bbox.y) obj_bottomright = fife.ExactModelCoordinate(bbox.x + bbox.w, bbox.y + bbox.h) obj_bottomleft = fife.ExactModelCoordinate(bbox.x, bbox.y + bbox.h) loc_topleft = fife.Location() loc_topleft.setLayer(self._map.getLayer('boundingbox')) loc_topleft.setExactLayerCoordinates(obj_topleft) loc_topright = fife.Location() loc_topright.setLayer(self._map.getLayer('boundingbox')) loc_topright.setExactLayerCoordinates(obj_topright) loc_bottomright = fife.Location() loc_bottomright.setLayer(self._map.getLayer('boundingbox')) loc_bottomright.setExactLayerCoordinates(obj_bottomright) loc_bottomleft = fife.Location() loc_bottomleft.setLayer(self._map.getLayer('boundingbox')) loc_bottomleft.setExactLayerCoordinates(obj_bottomleft) node_topleft = fife.GenericRendererNode(loc_topleft) node_topright = fife.GenericRendererNode(loc_topright) node_bottomright = fife.GenericRendererNode(loc_bottomright) node_bottomleft = fife.GenericRendererNode(loc_bottomleft) self._genericrenderer.addLine("quads", node_topleft, node_topright, 255, 255, 255) self._genericrenderer.addLine("quads", node_topright, node_bottomright, 255, 255, 255) self._genericrenderer.addLine("quads", node_bottomright, node_bottomleft, 255, 255, 255) self._genericrenderer.addLine("quads", node_bottomleft, node_topleft, 255, 255, 255) #had to do this or it would segfault obj_topleft.thisown = 0 obj_topright.thisown = 0 obj_bottomright.thisown = 0 obj_bottomleft.thisown = 0 loc_topleft.thisown = 0 loc_topright.thisown = 0 loc_bottomright.thisown = 0 loc_bottomleft.thisown = 0 node_topleft.thisown = 0 node_topright.thisown = 0 node_bottomright.thisown = 0 node_bottomleft.thisown = 0 def gameOver(self): self._gameover.show() self._hudwindow.hide() self._gamecomplete = True def endLevel(self): self._paused = True #only one level so the game is over once you complete it. self._gamecomplete = True self._winner.show() self._hudwindow.hide() def saveScore(self): self._gamecomplete = False if self._highscores.isHighScore(self._scene.player.score): score = self._scene.player.score dlg = pychan.loadXML('gui/highscoredialog.xml') dlg.execute({'okay': "Yay!"}) name = dlg.findChild(name='name').text self._highscores.addHighScore(HighScore(name, score)) self._highscores.show() def newGame(self): self.loadLevel("maps/shooter_map1.xml") self._mainmenu.hide() self._paused = False def continueGame(self): self._mainmenu.hide() self._paused = False def pauseGame(self): self._paused = True self._mainmenu.show(True) def initCameras(self): """ Before we can actually see something on screen we have to specify the render setup. This is done through Camera objects which offer a viewport on the map. """ for cam in self._map.getCameras(): if cam.getId() == 'main': self.cameras['main'] = cam #pass the camera to the scene as the scene controls the cameras position self._scene.attachCamera(self.cameras['main']) self.cameras['main'].setZoom(1.0) def resetKeys(self): self._keystate['UP'] = False self._keystate['DOWN'] = False self._keystate['LEFT'] = False self._keystate['RIGHT'] = False self._keystate['SPACE'] = False self._keystate['CTRL'] = False def keyPressed(self, evt): keyval = evt.getKey().getValue() keystr = evt.getKey().getAsString().lower() if keyval == fife.Key.UP: self._keystate['UP'] = True elif keyval == fife.Key.DOWN: self._keystate['DOWN'] = True elif keyval == fife.Key.LEFT: self._keystate['LEFT'] = True elif keyval == fife.Key.RIGHT: self._keystate['RIGHT'] = True elif keyval == fife.Key.SPACE: self._keystate['SPACE'] = True elif keyval == fife.Key.P: self._paused = not self._paused self._pausedtime += self._timemanager.getTime() elif keyval in (fife.Key.LEFT_CONTROL, fife.Key.RIGHT_CONTROL): self._keystate['CTRL'] = True def keyReleased(self, evt): keyval = evt.getKey().getValue() if keyval == fife.Key.UP: self._keystate['UP'] = False elif keyval == fife.Key.DOWN: self._keystate['DOWN'] = False elif keyval == fife.Key.LEFT: self._keystate['LEFT'] = False elif keyval == fife.Key.RIGHT: self._keystate['RIGHT'] = False elif keyval == fife.Key.SPACE: self._keystate['SPACE'] = False elif keyval in (fife.Key.LEFT_CONTROL, fife.Key.RIGHT_CONTROL): self._keystate['CTRL'] = False def pump(self): """ Called every frame. """ if self._genericrenderer: self._genericrenderer.removeAll("quads") #scene hasn't been initialized. Nothing to do. if not self._scene: return #update the scene if not self._paused and not self._gamecomplete: if self._scene.paused: self._scene.unpause(self._timemanager.getTime() - self._starttime) self._scene.update(self._timemanager.getTime() - self._starttime, self._keystate) #update the HUD avgframe = self._timemanager.getAverageFrameTime() if avgframe > 0: fps = 1 / (avgframe / 1000) else: fps = 0 fpstxt = "%3.2f" % fps self._hudwindow.setFPSText(unicode(fpstxt)) player = self._scene.player exactcoords = player.location.getExactLayerCoordinates() pos = "%1.2f" % exactcoords.x + ", %1.2f" % exactcoords.y self._hudwindow.setPositionText(unicode(pos)) vel = "%1.2f" % player.velocity.x + ", %1.2f" % player.velocity.y self._hudwindow.setVelocityText(unicode(vel)) score = unicode(str(player.score)) self._hudwindow.setScoreText(score) ilives = player.lives if ilives < 0: ilives = 0 lives = unicode(str(ilives)) self._hudwindow.setLivesText(lives) else: if not self._scene.paused: self._scene.pause(self._timemanager.getTime() - self._starttime) if self._gamecomplete: self.saveScore() self.reset() self._pump_ctr += 1
class World(EventListenerBase): """ The world! This class handles: setup of map view (cameras ...) loading the map GUI for right clicks handles mouse/key events which aren't handled by the GUI. ( by inheriting from EventlistenerBase ) That's obviously too much, and should get factored out. """ def __init__(self, engine): super(World, self).__init__(engine, regMouse=True, regKeys=True) self.engine = engine self.eventmanager = engine.getEventManager() self.model = engine.getModel() self.filename = '' self.pump_ctr = 0 # for testing purposis self.ctrldown = False self.instancemenu = None self.instance_to_agent = {} self.dynamic_widgets = {} self.light_intensity = 1 self.light_sources = 0 self.lightmodel = int(TDS.get("FIFE", "Lighting")) self.soundmanager = SoundManager(self.engine) self.music = None def show_instancemenu(self, clickpoint, instance): """ Build and show a popupmenu for an instance that the player clicked on. The available actions are dynamically added to the menu (and mapped to the onXYZ functions). """ if instance.getFifeId() == self.hero.agent.getFifeId(): return # Create the popup. self.build_instancemenu() self.instancemenu.clickpoint = clickpoint self.instancemenu.instance = instance # Add the buttons according to circumstances. self.instancemenu.addChild(self.dynamic_widgets['inspectButton']) target_distance = self.hero.agent.getLocationRef().getLayerDistanceTo(instance.getLocationRef()) if target_distance > 3.0: self.instancemenu.addChild(self.dynamic_widgets['moveButton']) else: if self.instance_to_agent.has_key(instance.getFifeId()): self.instancemenu.addChild(self.dynamic_widgets['talkButton']) self.instancemenu.addChild(self.dynamic_widgets['kickButton']) # And show it :) self.instancemenu.position = (clickpoint.x, clickpoint.y) self.instancemenu.show() def build_instancemenu(self): """ Just loads the menu from an XML file and hooks the events up. The buttons are removed and later re-added if appropiate. """ self.hide_instancemenu() dynamicbuttons = ('moveButton', 'talkButton', 'kickButton', 'inspectButton') self.instancemenu = pychan.loadXML('gui/instancemenu.xml') self.instancemenu.mapEvents({ 'moveButton' : self.onMoveButtonPress, 'talkButton' : self.onTalkButtonPress, 'kickButton' : self.onKickButtonPress, 'inspectButton' : self.onInspectButtonPress, }) for btn in dynamicbuttons: self.dynamic_widgets[btn] = self.instancemenu.findChild(name=btn) self.instancemenu.removeAllChildren() def hide_instancemenu(self): if self.instancemenu: self.instancemenu.hide() def reset(self): """ Clear the agent information and reset the moving secondary camera state. """ if self.music: self.music.stop() self.map, self.agentlayer = None, None self.cameras = {} self.hero, self.girl, self.clouds, self.beekeepers = None, None, [], [] self.cur_cam2_x, self.initial_cam2_x, self.cam2_scrolling_right = 0, 0, True self.target_rotation = 0 self.instance_to_agent = {} def load(self, filename): """ Load a xml map and setup agents and cameras. """ self.filename = filename self.reset() loader = fife.MapLoader(self.engine.getModel(), self.engine.getVFS(), self.engine.getImageManager(), self.engine.getRenderBackend()) if loader.isLoadable(filename): self.map = loader.load(filename) self.initAgents() self.initCameras() #Set background color self.engine.getRenderBackend().setBackgroundColor(80,80,255) if int(TDS.get("FIFE", "PlaySounds")): # play track as background music self.music = self.soundmanager.createSoundEmitter('music/rio_de_hola.ogg') self.music.looping = True self.music.gain = 128.0 self.music.play() self.waves = self.soundmanager.createSoundEmitter('sounds/waves.ogg') self.waves.looping = True self.waves.gain = 16.0 self.waves.play() def initAgents(self): """ Setup agents. For this techdemo we have a very simple 'active things on the map' model, which is called agents. All rio maps will have a separate layer for them. Note that we keep a mapping from map instances (C++ model of stuff on the map) to the python agents for later reference. """ self.agentlayer = self.map.getLayer('TechdemoMapGroundObjectLayer') self.hero = Hero(TDS, self.model, 'PC', self.agentlayer) self.instance_to_agent[self.hero.agent.getFifeId()] = self.hero self.hero.start() self.girl = Girl(TDS, self.model, 'NPC:girl', self.agentlayer) self.instance_to_agent[self.girl.agent.getFifeId()] = self.girl self.girl.start() self.beekeepers = create_anonymous_agents(TDS, self.model, 'beekeeper', self.agentlayer, Beekeeper) for beekeeper in self.beekeepers: self.instance_to_agent[beekeeper.agent.getFifeId()] = beekeeper beekeeper.start() # Clouds are currently defunct. cloudlayer = self.map.getLayer('TechdemoMapTileLayer') self.clouds = create_anonymous_agents(TDS, self.model, 'Cloud', cloudlayer, Cloud) for cloud in self.clouds: cloud.start(0.1, 0.05) def initCameras(self): """ Before we can actually see something on screen we have to specify the render setup. This is done through Camera objects which offer a viewport on the map. For this techdemo two cameras are used. One follows the hero(!) via 'attach' the other one scrolls around a bit (see the pump function). """ camera_prefix = self.filename.rpartition('.')[0] # Remove file extension camera_prefix = camera_prefix.rpartition('/')[2] # Remove path camera_prefix += '_' for cam in self.map.getCameras(): camera_id = cam.getId().replace(camera_prefix, '') self.cameras[camera_id] = cam cam.resetRenderers() self.cameras['main'].attach(self.hero.agent) # Floating text renderers currntly only support one font. # ... so we set that up. # You'll se that for our demo we use a image font, so we have to specify the font glyphs # for that one. renderer = fife.FloatingTextRenderer.getInstance(self.cameras['main']) textfont = pychan.manager.hook.guimanager.createFont('fonts/rpgfont.png', 0, str(TDS.get("FIFE", "FontGlyphs"))); renderer.setFont(textfont) renderer.activateAllLayers(self.map) renderer.setBackground(100, 255, 100, 165) renderer.setBorder(50, 255, 50) renderer.setEnabled(True) # Activate the grid renderer on all layers renderer = self.cameras['main'].getRenderer('GridRenderer') renderer.activateAllLayers(self.map) # The small camera shouldn't be cluttered by the 'humm di dums' of our hero. # So we disable the renderer simply by setting its font to None. renderer = fife.FloatingTextRenderer.getInstance(self.cameras['small']) renderer.setFont(None) # The following renderers are used for debugging. # Note that by default ( that is after calling View.resetRenderers or Camera.resetRenderers ) # renderers will be handed all layers. That's handled here. renderer = fife.CoordinateRenderer.getInstance(self.cameras['main']) renderer.setFont(textfont) renderer.clearActiveLayers() renderer.addActiveLayer(self.map.getLayer(str(TDS.get("rio", "CoordinateLayerName")))) renderer = self.cameras['main'].getRenderer('QuadTreeRenderer') renderer.setEnabled(True) renderer.clearActiveLayers() if str(TDS.get("rio", "QuadTreeLayerName")): renderer.addActiveLayer(self.map.getLayer(str(TDS.get("rio", "QuadTreeLayerName")))) # If Light is enabled in settings then init the lightrenderer. if self.lightmodel != 0: renderer = fife.LightRenderer.getInstance(self.cameras['main']) renderer.setEnabled(True) renderer.clearActiveLayers() renderer.addActiveLayer(self.map.getLayer('TechdemoMapGroundObjectLayer')) # Set up the second camera # NOTE: We need to explicitly call setLocation, there's a bit of a messup in the Camera code. self.cameras['small'].setLocation(self.hero.agent.getLocation()) self.cameras['small'].attach(self.girl.agent) self.target_rotation = self.cameras['main'].getRotation() def save(self, filename): saveMapFile(filename, self.engine, self.map) def getInstancesAt(self, clickpoint): """ Query the main camera for instances on our active(agent) layer. """ return self.cameras['main'].getMatchingInstances(clickpoint, self.agentlayer) def getLocationAt(self, clickpoint): """ Query the main camera for the Map location (on the agent layer) that a screen point refers to. """ target_mapcoord = self.cameras['main'].toMapCoordinates(clickpoint, False) target_mapcoord.z = 0 location = fife.Location(self.agentlayer) location.setMapCoordinates(target_mapcoord) return location def keyPressed(self, evt): keyval = evt.getKey().getValue() keystr = evt.getKey().getAsString().lower() if keystr == 't': r = self.cameras['main'].getRenderer('GridRenderer') r.setEnabled(not r.isEnabled()) elif keystr == 'c': r = self.cameras['main'].getRenderer('CoordinateRenderer') r.setEnabled(not r.isEnabled()) elif keystr == 's': c = self.cameras['small'] c.setEnabled(not c.isEnabled()) elif keystr == 'r': self.model.deleteMaps() self.load(self.filename) elif keystr == 'o': self.target_rotation = (self.target_rotation + 90) % 360 elif keystr == '2': self.lightIntensity(0.1) elif keystr == '1': self.lightIntensity(-0.1) elif keystr == '5': self.lightSourceIntensity(25) elif keystr == '4': self.lightSourceIntensity(-25) elif keyval in (fife.Key.LEFT_CONTROL, fife.Key.RIGHT_CONTROL): self.ctrldown = True def keyReleased(self, evt): keyval = evt.getKey().getValue() if keyval in (fife.Key.LEFT_CONTROL, fife.Key.RIGHT_CONTROL): self.ctrldown = False def mouseWheelMovedUp(self, evt): if self.ctrldown: self.cameras['main'].setZoom(self.cameras['main'].getZoom() * 1.05) def mouseWheelMovedDown(self, evt): if self.ctrldown: self.cameras['main'].setZoom(self.cameras['main'].getZoom() / 1.05) def changeRotation(self): """ Smoothly change the main cameras rotation until the current target rotation is reached. """ currot = self.cameras['main'].getRotation() if self.target_rotation != currot: self.cameras['main'].setRotation((currot + 5) % 360) def mousePressed(self, evt): if evt.isConsumedByWidgets(): return clickpoint = fife.ScreenPoint(evt.getX(), evt.getY()) if (evt.getButton() == fife.MouseEvent.LEFT): self.hide_instancemenu() self.hero.run( self.getLocationAt(clickpoint) ) if (evt.getButton() == fife.MouseEvent.RIGHT): instances = self.getInstancesAt(clickpoint) print "selected instances on agent layer: ", [i.getObject().getId() for i in instances] if instances: self.show_instancemenu(clickpoint, instances[0]) def mouseMoved(self, evt): renderer = fife.InstanceRenderer.getInstance(self.cameras['main']) renderer.removeAllOutlines() pt = fife.ScreenPoint(evt.getX(), evt.getY()) instances = self.getInstancesAt(pt); for i in instances: if i.getObject().getId() in ('girl', 'beekeeper'): renderer.addOutlined(i, 173, 255, 47, 2) def lightIntensity(self, value): if self.light_intensity+value <= 1 and self.light_intensity+value >= 0: self.light_intensity = self.light_intensity + value if self.lightmodel == 1: self.cameras['main'].setLightingColor(self.light_intensity, self.light_intensity, self.light_intensity) def lightSourceIntensity(self, value): if self.light_sources+value <= 255 and self.light_sources+value >= 0: self.light_sources = self.light_sources+value renderer = fife.LightRenderer.getInstance(self.cameras['main']) renderer.removeAll("beekeeper_simple_light") renderer.removeAll("hero_simple_light") renderer.removeAll("girl_simple_light") if self.lightmodel == 1: node = fife.RendererNode(self.hero.agent) renderer.addSimpleLight("hero_simple_light", node, self.light_sources, 64, 32, 1, 1, 255, 255, 255) node = fife.RendererNode(self.girl.agent) renderer.addSimpleLight("girl_simple_light", node, self.light_sources, 64, 32, 1, 1, 255, 255, 255) for beekeeper in self.beekeepers: node = fife.RendererNode(beekeeper.agent) renderer.addSimpleLight("beekeeper_simple_light", node, self.light_sources, 120, 32, 1, 1, 255, 255, 255) def onConsoleCommand(self, command): result = '' try: result = str(eval(command)) except Exception, e: result = str(e) return result
class World(EventListenerBase): """ The world! This class handles: setup of map view (cameras ...) loading the map GUI for right clicks handles mouse/key events which aren't handled by the GUI. ( by inheriting from EventlistenerBase ) That's obviously too much, and should get factored out. """ def __init__(self, engine): super(World, self).__init__(engine, regMouse=True, regKeys=True) self.engine = engine self.eventmanager = engine.getEventManager() self.model = engine.getModel() self.filename = '' self.pump_ctr = 0 # for testing purposis self.ctrldown = False self.instancemenu = None self.instance_to_agent = {} self.dynamic_widgets = {} self.light_intensity = 1 self.light_sources = 0 self.lightmodel = int(TDS.get("FIFE", "Lighting")) self.soundmanager = SoundManager(self.engine) self.music = None def show_instancemenu(self, clickpoint, instance): """ Build and show a popupmenu for an instance that the player clicked on. The available actions are dynamically added to the menu (and mapped to the onXYZ functions). """ if instance.getFifeId() == self.hero.agent.getFifeId(): return # Create the popup. self.build_instancemenu() self.instancemenu.clickpoint = clickpoint self.instancemenu.instance = instance # Add the buttons according to circumstances. self.instancemenu.addChild(self.dynamic_widgets['inspectButton']) target_distance = self.hero.agent.getLocationRef().getLayerDistanceTo(instance.getLocationRef()) if target_distance > 3.0: self.instancemenu.addChild(self.dynamic_widgets['moveButton']) else: if self.instance_to_agent.has_key(instance.getFifeId()): self.instancemenu.addChild(self.dynamic_widgets['talkButton']) self.instancemenu.addChild(self.dynamic_widgets['kickButton']) # And show it :) self.instancemenu.position = (clickpoint.x, clickpoint.y) self.instancemenu.show() def build_instancemenu(self): """ Just loads the menu from an XML file and hooks the events up. The buttons are removed and later re-added if appropiate. """ self.hide_instancemenu() dynamicbuttons = ('moveButton', 'talkButton', 'kickButton', 'inspectButton') self.instancemenu = pychan.loadXML('gui/instancemenu.xml') self.instancemenu.mapEvents({ 'moveButton' : self.onMoveButtonPress, 'talkButton' : self.onTalkButtonPress, 'kickButton' : self.onKickButtonPress, 'inspectButton' : self.onInspectButtonPress, }) for btn in dynamicbuttons: self.dynamic_widgets[btn] = self.instancemenu.findChild(name=btn) self.instancemenu.removeAllChildren() def hide_instancemenu(self): if self.instancemenu: self.instancemenu.hide() def reset(self): """ Clear the agent information and reset the moving secondary camera state. """ if self.music: self.music.stop() self.map, self.agentlayer = None, None self.cameras = {} self.hero, self.girl, self.clouds, self.beekeepers = None, None, [], [] self.cur_cam2_x, self.initial_cam2_x, self.cam2_scrolling_right = 0, 0, True self.target_rotation = 0 self.instance_to_agent = {} def load(self, filename): """ Load a xml map and setup agents and cameras. """ self.filename = filename self.reset() loader = fife.MapLoader(self.engine.getModel(), self.engine.getVFS(), self.engine.getImageManager(), self.engine.getRenderBackend()) if loader.isLoadable(filename): self.map = loader.load(filename) self.initAgents() self.initCameras() #Set background color self.engine.getRenderBackend().setBackgroundColor(80,80,255) if int(TDS.get("FIFE", "PlaySounds")): # play track as background music self.music = self.soundmanager.createSoundEmitter('music/rio_de_hola.ogg') self.music.looping = True self.music.gain = 128.0 self.music.play() self.waves = self.soundmanager.createSoundEmitter('sounds/waves.ogg') self.waves.looping = True self.waves.gain = 16.0 self.waves.play() def initAgents(self): """ Setup agents. For this techdemo we have a very simple 'active things on the map' model, which is called agents. All rio maps will have a separate layer for them. Note that we keep a mapping from map instances (C++ model of stuff on the map) to the python agents for later reference. """ self.agentlayer = self.map.getLayer('TechdemoMapGroundObjectLayer') self.hero = Hero(TDS, self.model, 'PC', self.agentlayer) self.instance_to_agent[self.hero.agent.getFifeId()] = self.hero self.hero.start() self.girl = Girl(TDS, self.model, 'NPC:girl', self.agentlayer) self.instance_to_agent[self.girl.agent.getFifeId()] = self.girl self.girl.start() # Fog of War stuff #self.hero.agent.setVisitor(True) #self.hero.agent.setVisitorRadius(2) #self.girl.agent.setVisitor(True) #self.girl.agent.setVisitorRadius(1) self.beekeepers = create_anonymous_agents(TDS, self.model, 'beekeeper', self.agentlayer, Beekeeper) for beekeeper in self.beekeepers: self.instance_to_agent[beekeeper.agent.getFifeId()] = beekeeper beekeeper.start() # Clouds are currently defunct. cloudlayer = self.map.getLayer('TechdemoMapTileLayer') self.clouds = create_anonymous_agents(TDS, self.model, 'Cloud', cloudlayer, Cloud) for cloud in self.clouds: cloud.start(0.1, 0.05) def initCameras(self): """ Before we can actually see something on screen we have to specify the render setup. This is done through Camera objects which offer a viewport on the map. For this techdemo two cameras are used. One follows the hero(!) via 'attach' the other one scrolls around a bit (see the pump function). """ camera_prefix = self.filename.rpartition('.')[0] # Remove file extension camera_prefix = camera_prefix.rpartition('/')[2] # Remove path camera_prefix += '_' for cam in self.map.getCameras(): camera_id = cam.getId().replace(camera_prefix, '') self.cameras[camera_id] = cam cam.resetRenderers() self.cameras['main'].attach(self.hero.agent) # Floating text renderers currntly only support one font. # ... so we set that up. # You'll se that for our demo we use a image font, so we have to specify the font glyphs # for that one. renderer = fife.FloatingTextRenderer.getInstance(self.cameras['main']) textfont = get_manager().createFont('fonts/rpgfont.png', 0, str(TDS.get("FIFE", "FontGlyphs"))); renderer.setFont(textfont) renderer.activateAllLayers(self.map) renderer.setBackground(100, 255, 100, 165) renderer.setBorder(50, 255, 50) renderer.setEnabled(True) # Activate the grid renderer on all layers renderer = self.cameras['main'].getRenderer('GridRenderer') renderer.activateAllLayers(self.map) # The small camera shouldn't be cluttered by the 'humm di dums' of our hero. # So we disable the renderer simply by setting its font to None. renderer = fife.FloatingTextRenderer.getInstance(self.cameras['small']) renderer.setFont(None) # The following renderers are used for debugging. # Note that by default ( that is after calling View.resetRenderers or Camera.resetRenderers ) # renderers will be handed all layers. That's handled here. renderer = fife.CoordinateRenderer.getInstance(self.cameras['main']) renderer.setFont(textfont) renderer.clearActiveLayers() renderer.addActiveLayer(self.map.getLayer(str(TDS.get("rio", "CoordinateLayerName")))) renderer = self.cameras['main'].getRenderer('QuadTreeRenderer') renderer.setEnabled(True) renderer.clearActiveLayers() if str(TDS.get("rio", "QuadTreeLayerName")): renderer.addActiveLayer(self.map.getLayer(str(TDS.get("rio", "QuadTreeLayerName")))) # If Light is enabled in settings then init the lightrenderer. if self.lightmodel != 0: renderer = fife.LightRenderer.getInstance(self.cameras['main']) renderer.setEnabled(True) renderer.clearActiveLayers() renderer.addActiveLayer(self.map.getLayer('TechdemoMapGroundObjectLayer')) # Fog of War stuff renderer = fife.CellRenderer.getInstance(self.cameras['main']) renderer.setEnabled(True) renderer.clearActiveLayers() renderer.addActiveLayer(self.map.getLayer('TechdemoMapGroundObjectLayer')) concimg = self.engine.getImageManager().load("misc/black_cell.png") maskimg = self.engine.getImageManager().load("misc/mask_cell.png") renderer.setConcealImage(concimg) renderer.setMaskImage(maskimg) renderer.setFogOfWarLayer(self.map.getLayer('TechdemoMapGroundObjectLayer')) #disable FoW by default. Users can turn it on with the 'f' key. renderer.setEnabledFogOfWar(False) #renderer.setEnabledBlocking(True) # Set up the second camera # NOTE: We need to explicitly call setLocation, there's a bit of a messup in the Camera code. self.cameras['small'].setLocation(self.hero.agent.getLocation()) self.cameras['small'].attach(self.girl.agent) self.target_rotation = self.cameras['main'].getRotation() def save(self, filename): saveMapFile(filename, self.engine, self.map) def getInstancesAt(self, clickpoint): """ Query the main camera for instances on our active(agent) layer. """ return self.cameras['main'].getMatchingInstances(clickpoint, self.agentlayer) def getLocationAt(self, clickpoint): """ Query the main camera for the Map location (on the agent layer) that a screen point refers to. """ target_mapcoord = self.cameras['main'].toMapCoordinates(clickpoint, False) target_mapcoord.z = 0 location = fife.Location(self.agentlayer) location.setMapCoordinates(target_mapcoord) return location def keyPressed(self, evt): keyval = evt.getKey().getValue() keystr = evt.getKey().getAsString().lower() if keystr == 't': r = self.cameras['main'].getRenderer('GridRenderer') r.setEnabled(not r.isEnabled()) elif keystr == 'c': r = self.cameras['main'].getRenderer('CoordinateRenderer') r.setEnabled(not r.isEnabled()) elif keystr == 's': c = self.cameras['small'] c.setEnabled(not c.isEnabled()) elif keystr == 'r': self.model.deleteMaps() self.load(self.filename) elif keystr == 'f': renderer = fife.CellRenderer.getInstance(self.cameras['main']) renderer.setEnabledFogOfWar(not renderer.isEnabledFogOfWar()) self.cameras['main'].refresh() elif keystr == 'o': self.target_rotation = (self.target_rotation + 90) % 360 elif keystr == '2': self.lightIntensity(0.1) elif keystr == '1': self.lightIntensity(-0.1) elif keystr == '5': self.lightSourceIntensity(25) elif keystr == '4': self.lightSourceIntensity(-25) elif keystr == '0' or keystr == fife.Key.NUM_0: if self.ctrldown: self.cameras['main'].setZoom(1.0) elif keyval in (fife.Key.LEFT_CONTROL, fife.Key.RIGHT_CONTROL): self.ctrldown = True def keyReleased(self, evt): keyval = evt.getKey().getValue() if keyval in (fife.Key.LEFT_CONTROL, fife.Key.RIGHT_CONTROL): self.ctrldown = False def mouseWheelMovedUp(self, evt): if self.ctrldown: self.cameras['main'].setZoom(self.cameras['main'].getZoom() * 1.05) def mouseWheelMovedDown(self, evt): if self.ctrldown: self.cameras['main'].setZoom(self.cameras['main'].getZoom() / 1.05) def changeRotation(self): """ Smoothly change the main cameras rotation until the current target rotation is reached. """ currot = self.cameras['main'].getRotation() if self.target_rotation != currot: self.cameras['main'].setRotation((currot + 5) % 360) def mousePressed(self, evt): if evt.isConsumedByWidgets(): return clickpoint = fife.ScreenPoint(evt.getX(), evt.getY()) if (evt.getButton() == fife.MouseEvent.LEFT): self.hide_instancemenu() self.hero.run( self.getLocationAt(clickpoint) ) if (evt.getButton() == fife.MouseEvent.RIGHT): instances = self.getInstancesAt(clickpoint) print "selected instances on agent layer: ", [i.getObject().getId() for i in instances] if instances: self.show_instancemenu(clickpoint, instances[0]) def mouseMoved(self, evt): renderer = fife.InstanceRenderer.getInstance(self.cameras['main']) renderer.removeAllOutlines() pt = fife.ScreenPoint(evt.getX(), evt.getY()) instances = self.getInstancesAt(pt); for i in instances: if i.getObject().getId() in ('girl', 'beekeeper'): renderer.addOutlined(i, 173, 255, 47, 2) def lightIntensity(self, value): if self.light_intensity+value <= 1 and self.light_intensity+value >= 0: self.light_intensity = self.light_intensity + value if self.lightmodel == 1: self.cameras['main'].setLightingColor(self.light_intensity, self.light_intensity, self.light_intensity) def lightSourceIntensity(self, value): if self.light_sources+value <= 255 and self.light_sources+value >= 0: self.light_sources = self.light_sources+value renderer = fife.LightRenderer.getInstance(self.cameras['main']) renderer.removeAll("beekeeper_simple_light") renderer.removeAll("hero_simple_light") renderer.removeAll("girl_simple_light") if self.lightmodel == 1: node = fife.RendererNode(self.hero.agent) renderer.addSimpleLight("hero_simple_light", node, self.light_sources, 64, 32, 1, 1, 255, 255, 255) node = fife.RendererNode(self.girl.agent) renderer.addSimpleLight("girl_simple_light", node, self.light_sources, 64, 32, 1, 1, 255, 255, 255) for beekeeper in self.beekeepers: node = fife.RendererNode(beekeeper.agent) renderer.addSimpleLight("beekeeper_simple_light", node, self.light_sources, 120, 32, 1, 1, 255, 255, 255) def onConsoleCommand(self, command): result = '' try: result = str(eval(command)) except Exception, e: result = str(e) return result
class World(EventListenerBase): """ The world! This class handles: setup of map view (cameras ...) loading the map handles mouse/key events which aren't handled by the GUI. ( by inheriting from EventlistenerBase ) """ def __init__(self, app, engine, setting): super(World, self).__init__(engine, regKeys=True) self._applictaion = app self._engine = engine self._setting = setting self._timemanager = engine.getTimeManager() self._eventmanager = engine.getEventManager() self._model = engine.getModel() self._filename = '' self._keystate = { 'UP': False, 'DOWN': False, 'LEFT': False, 'RIGHT': False, 'CTRL': False, 'SPACE': False, } self._pump_ctr = 0 self._map = None self._scene = None self._paused = True self._pausedtime = 0 self._starttime = 0 self._soundmanager = SoundManager(self._engine) self._mainmenu = MainMenu(self, self._setting) self.showMainMenu() self._hudwindow = HeadsUpDisplay(self) self._hudwindow.hide() self._gameover = GameOverDisplay() self._gameover.hide() self._highscores = HighScores(self) self._highscores.hide() self._winner = WinnerDisplay() self._winner.hide() self._credits = CreditsDisplay(self) self._credits.hide() self._genericrenderer = None self._gamecomplete = False def showMainMenu(self): if self._scene: self._paused = True cont = True else: cont = False self._mainmenu.show(cont) def showCredits(self): self._credits.show() def showHighScores(self): self._highscores.show() def quit(self): self.reset() self._soundmanager.destroy() self._applictaion.requestQuit() def reset(self): if self._map: self._model.deleteMap(self._map) self._map = None self.cameras = {} if self._scene: self._scene.destroyScene() self._scene = None self._gamecomplete = False def loadLevel(self, filename): """ Load a xml map and setup cameras. """ self.resetKeys() self._filename = filename self.reset() loader = fife.MapLoader(self._engine.getModel(), self._engine.getVFS(), self._engine.getImageManager(), self._engine.getRenderBackend()) if loader.isLoadable(self._filename): self._map = loader.load(self._filename) loader.loadImportFile("objects/projectiles/bullet1/object.xml") loader.loadImportFile("objects/projectiles/fireball/object.xml") self._scene = Scene(self, self._engine, self._map.getLayer('objects'), self._soundmanager) self._scene.initScene(self._map) self.initCameras() self._hudwindow.show() self._gameover.hide() self._winner.hide() self._starttime = self._timemanager.getTime() self._genericrenderer = fife.GenericRenderer.getInstance(self.cameras['main']) self._genericrenderer.clearActiveLayers() self._genericrenderer.addActiveLayer(self._map.getLayer('boundingbox')) self._genericrenderer.setEnabled(True) def renderBoundingBox(self, obj): """ Just a hack to render an objects bounding box. """ bbox = copy.copy(obj.boundingbox) #apply the object layer scale bbox.x /= 0.25 bbox.y /= 0.25 bbox.w /= 0.25 bbox.h /= 0.25 obj_topleft = fife.ExactModelCoordinate(bbox.x, bbox.y) obj_topright = fife.ExactModelCoordinate(bbox.x + bbox.w, bbox.y) obj_bottomright = fife.ExactModelCoordinate(bbox.x + bbox.w, bbox.y + bbox.h) obj_bottomleft = fife.ExactModelCoordinate(bbox.x, bbox.y + bbox.h) loc_topleft = fife.Location() loc_topleft.setLayer(self._map.getLayer('boundingbox')) loc_topleft.setExactLayerCoordinates(obj_topleft) loc_topright = fife.Location() loc_topright.setLayer(self._map.getLayer('boundingbox')) loc_topright.setExactLayerCoordinates(obj_topright) loc_bottomright = fife.Location() loc_bottomright.setLayer(self._map.getLayer('boundingbox')) loc_bottomright.setExactLayerCoordinates(obj_bottomright) loc_bottomleft = fife.Location() loc_bottomleft.setLayer(self._map.getLayer('boundingbox')) loc_bottomleft.setExactLayerCoordinates(obj_bottomleft) node_topleft = fife.GenericRendererNode(loc_topleft) node_topright = fife.GenericRendererNode(loc_topright) node_bottomright = fife.GenericRendererNode(loc_bottomright) node_bottomleft = fife.GenericRendererNode(loc_bottomleft) self._genericrenderer.addLine("quads", node_topleft, node_topright, 255, 255, 255) self._genericrenderer.addLine("quads", node_topright, node_bottomright, 255, 255, 255) self._genericrenderer.addLine("quads", node_bottomright, node_bottomleft, 255, 255, 255) self._genericrenderer.addLine("quads", node_bottomleft, node_topleft, 255, 255, 255) #had to do this or it would segfault obj_topleft.thisown = 0 obj_topright.thisown = 0 obj_bottomright.thisown = 0 obj_bottomleft.thisown = 0 loc_topleft.thisown = 0 loc_topright.thisown = 0 loc_bottomright.thisown = 0 loc_bottomleft.thisown = 0 node_topleft.thisown = 0 node_topright.thisown = 0 node_bottomright.thisown = 0 node_bottomleft.thisown = 0 def gameOver(self): self._gameover.show() self._hudwindow.hide() self._gamecomplete = True def endLevel(self): self._paused = True #only one level so the game is over once you complete it. self._gamecomplete = True self._winner.show() self._hudwindow.hide() def saveScore(self): self._gamecomplete = False if self._highscores.isHighScore(self._scene.player.score): score = self._scene.player.score dlg = pychan.loadXML('gui/highscoredialog.xml') dlg.execute({ 'okay' : "Yay!" }) name = dlg.findChild(name='name').text self._highscores.addHighScore(HighScore(name, score)) self._highscores.show() def newGame(self): self.loadLevel("maps/shooter_map1.xml") self._mainmenu.hide() self._paused = False def continueGame(self): self._mainmenu.hide() self._paused = False def pauseGame(self): self._paused = True self._mainmenu.show(True) def initCameras(self): """ Before we can actually see something on screen we have to specify the render setup. This is done through Camera objects which offer a viewport on the map. """ for cam in self._map.getCameras(): if cam.getId() == 'main': self.cameras['main'] = cam #pass the camera to the scene as the scene controls the cameras position self._scene.attachCamera(self.cameras['main']) self.cameras['main'].setZoom(1.0) def resetKeys(self): self._keystate['UP'] = False self._keystate['DOWN'] = False self._keystate['LEFT'] = False self._keystate['RIGHT'] = False self._keystate['SPACE'] = False self._keystate['CTRL'] = False def keyPressed(self, evt): keyval = evt.getKey().getValue() keystr = evt.getKey().getAsString().lower() if keyval == fife.Key.UP: self._keystate['UP'] = True elif keyval == fife.Key.DOWN: self._keystate['DOWN'] = True elif keyval == fife.Key.LEFT: self._keystate['LEFT'] = True elif keyval == fife.Key.RIGHT: self._keystate['RIGHT'] = True elif keyval == fife.Key.SPACE: self._keystate['SPACE'] = True elif keyval == fife.Key.P: self._paused = not self._paused self._pausedtime += self._timemanager.getTime() elif keyval in (fife.Key.LEFT_CONTROL, fife.Key.RIGHT_CONTROL): self._keystate['CTRL'] = True def keyReleased(self, evt): keyval = evt.getKey().getValue() if keyval == fife.Key.UP: self._keystate['UP'] = False elif keyval == fife.Key.DOWN: self._keystate['DOWN'] = False elif keyval == fife.Key.LEFT: self._keystate['LEFT'] = False elif keyval == fife.Key.RIGHT: self._keystate['RIGHT'] = False elif keyval == fife.Key.SPACE: self._keystate['SPACE'] = False elif keyval in (fife.Key.LEFT_CONTROL, fife.Key.RIGHT_CONTROL): self._keystate['CTRL'] = False def pump(self): """ Called every frame. """ if self._genericrenderer: self._genericrenderer.removeAll("quads") #scene hasn't been initialized. Nothing to do. if not self._scene: return #update the scene if not self._paused and not self._gamecomplete: if self._scene.paused: self._scene.unpause(self._timemanager.getTime() - self._starttime) self._scene.update(self._timemanager.getTime() - self._starttime, self._keystate) #update the HUD avgframe = self._timemanager.getAverageFrameTime() if avgframe > 0: fps = 1 / (avgframe / 1000) else: fps = 0 fpstxt = "%3.2f" % fps self._hudwindow.setFPSText(unicode(fpstxt)) player = self._scene.player exactcoords = player.location.getExactLayerCoordinates() pos = "%1.2f" % exactcoords.x + ", %1.2f" % exactcoords.y self._hudwindow.setPositionText(unicode(pos)) vel = "%1.2f" % player.velocity.x + ", %1.2f" % player.velocity.y self._hudwindow.setVelocityText(unicode(vel)) score = unicode(str(player.score)) self._hudwindow.setScoreText(score) ilives = player.lives if ilives < 0: ilives = 0 lives = unicode(str(ilives)) self._hudwindow.setLivesText(lives) else: if not self._scene.paused: self._scene.pause(self._timemanager.getTime() - self._starttime) if self._gamecomplete: self.saveScore() self.reset() self._pump_ctr += 1
def __init__(self, settings): print "* Initializing application..." super(TacticsApplication, self).__init__(settings) self.settings = settings self.model = self.engine.getModel() self.mapLoader = fife.MapLoader(self.model, self.engine.getVFS(), self.engine.getImageManager(), self.engine.getRenderBackend()) self.objectLoader = fife.ObjectLoader( self.model, self.engine.getVFS(), self.engine.getImageManager(), self.engine.getAnimationManager()) self.atlasLoader = fife.AtlasLoader(self.model, self.engine.getVFS(), self.engine.getImageManager(), self.engine.getAnimationManager()) self.map = None self.view = None self.eventmanager = self.engine.getEventManager() self.mouselistener = TacticsMouseListener(self) self.keylistener = TacticsKeyListener(self) self.eventmanager.addMouseListenerFront(self.mouselistener) self.eventmanager.addKeyListenerFront(self.keylistener) self.soundmanager = SoundManager(self.engine) self.fifesoundmanager = self.engine.getSoundManager() print "* Application initialized!" self.combat_actions = CombatActions() self.gui = TacticsGUI(self) self.real_timeline = RealTimeline() self.engine.getTimeManager().registerEvent(self.real_timeline) self.pather = TacticsPather(self) self.engine.getTimeManager().registerEvent(self.pather) self.loadObject("objects/tile.xml") self.loadObject("objects/boy/object.xml") self.loadObject("objects/dot_red.xml") self.loadObject("objects/shadow.xml") self.loadObject("objects/effects/fire.xml") self.loadObject("objects/effects/explosion.xml") self.loadObject("objects/effects/freeze.xml") self.loadObject("objects/projectiles/stone.xml") self.loadObject("objects/projectiles/fireball.xml") self.loadObject("objects/projectiles/tarball.xml") self.loadAtlas("objects/nature.xml") self.loadObject("objects/caltrops.xml") self.loadObject("objects/tar.xml") self.loadObject("objects/ice.xml") self.loadObject("objects/water_under.xml") self.loadObject("objects/water.xml") self.loadObject("objects/block_gray.xml") self.loadObject("objects/block_grass.xml") self.music = self.soundmanager.createSoundEmitter("music/music1.ogg") self.sound_attack = self.soundmanager.createSoundEmitter( "sfx/attack-1.ogg") self.sound_fire = self.soundmanager.createSoundEmitter( "sfx/fire-1.ogg") self.music.looping = True if not self.settings.get("FIFE", "PlaySounds"): self.fifesoundmanager.setVolume(0.0) self.music.play() self.unloadMap()
class TacticsApplication(CEGUIApplicationBase, PychanApplicationBase): def __init__(self, settings): print "* Initializing application..." super(TacticsApplication, self).__init__(settings) self.settings = settings self.model = self.engine.getModel() self.mapLoader = fife.MapLoader(self.model, self.engine.getVFS(), self.engine.getImageManager(), self.engine.getRenderBackend()) self.objectLoader = fife.ObjectLoader( self.model, self.engine.getVFS(), self.engine.getImageManager(), self.engine.getAnimationManager()) self.atlasLoader = fife.AtlasLoader(self.model, self.engine.getVFS(), self.engine.getImageManager(), self.engine.getAnimationManager()) self.map = None self.view = None self.eventmanager = self.engine.getEventManager() self.mouselistener = TacticsMouseListener(self) self.keylistener = TacticsKeyListener(self) self.eventmanager.addMouseListenerFront(self.mouselistener) self.eventmanager.addKeyListenerFront(self.keylistener) self.soundmanager = SoundManager(self.engine) self.fifesoundmanager = self.engine.getSoundManager() print "* Application initialized!" self.combat_actions = CombatActions() self.gui = TacticsGUI(self) self.real_timeline = RealTimeline() self.engine.getTimeManager().registerEvent(self.real_timeline) self.pather = TacticsPather(self) self.engine.getTimeManager().registerEvent(self.pather) self.loadObject("objects/tile.xml") self.loadObject("objects/boy/object.xml") self.loadObject("objects/dot_red.xml") self.loadObject("objects/shadow.xml") self.loadObject("objects/effects/fire.xml") self.loadObject("objects/effects/explosion.xml") self.loadObject("objects/effects/freeze.xml") self.loadObject("objects/projectiles/stone.xml") self.loadObject("objects/projectiles/fireball.xml") self.loadObject("objects/projectiles/tarball.xml") self.loadAtlas("objects/nature.xml") self.loadObject("objects/caltrops.xml") self.loadObject("objects/tar.xml") self.loadObject("objects/ice.xml") self.loadObject("objects/water_under.xml") self.loadObject("objects/water.xml") self.loadObject("objects/block_gray.xml") self.loadObject("objects/block_grass.xml") self.music = self.soundmanager.createSoundEmitter("music/music1.ogg") self.sound_attack = self.soundmanager.createSoundEmitter( "sfx/attack-1.ogg") self.sound_fire = self.soundmanager.createSoundEmitter( "sfx/fire-1.ogg") self.music.looping = True if not self.settings.get("FIFE", "PlaySounds"): self.fifesoundmanager.setVolume(0.0) self.music.play() self.unloadMap() def createListener(self): self._listener = TacticsListener(self) return self._listener def loadObject(self, filename): if self.objectLoader.isLoadable(filename): self.objectLoader.load(filename) else: print "can't load ", filename def loadAtlas(self, filename): if self.atlasLoader.isLoadable(filename): self.atlasLoader.load(filename) else: print "can't load ", filename def loadMap(self, map_name): filename = "maps/" + map_name + ".xml" if self.mapLoader.isLoadable(filename): print "* Loading map " + map_name self.map = self.mapLoader.load(filename) self.camera = self.map.getCamera("camera1") self.maplayer = self.map.getLayer("layer1") print "* Map loaded!" else: print "can't load map" def unloadMap(self): if self.map: self.model.deleteMap(self.map) self.map = None self.world = None self.view = None self.animations = [] self.replaying = False self.ai_play = False self.selected_action = None def newGame(self): print "* Starting new game..." self.unloadMap() self.loadMap("map1") self.world = World(self, self.maplayer) self.world.visual = WorldVisual() self.world.visual.initFromMap(self, self.maplayer, self.world) self.battle_controller = BattleController(self, self.world) self.ai = AI(self, self.world) self.view = TacticsView(self) self.gui.showHUD() def saveGame(self, save_name): serializer.save(self.world, "saves/" + save_name + ".sav") self.gui.combat_log.printMessage("Game saved.") def loadGame(self, save_name): self.unloadMap() self.world = serializer.load("saves/" + save_name + ".sav") self.world.application = self self.battle_controller = BattleController(self, self.world) self.ai = AI(self, self.world) self.createVisual() print "* Game loaded!" def createVisual(self): self.loadMap("empty") self.world.maplayer = self.maplayer self.world.visual = WorldVisual() self.world.visual.initFromWorld(self, self.maplayer, self.world) self.view = TacticsView(self) self.gui.showHUD() def startReplay(self): self.unloadMap() self.replay = Replay() self.world = self.replay.loadWorld() self.world.application = self self.battle_controller = BattleController(self, self.world) self.ai = AI(self, self.world) self.createVisual() self.replay.loadCommands() def selectAction(self, action_name): if self.current_character: self.selected_action = self.combat_actions.getAction(action_name) @LogExceptionDecorator def endTurn(self, args): if self.world.current_character_turn: self.battle_controller.endTurn() def addAnimation(self, animation): self.animations.append(animation) def removeAnimation(self, animation): if self.animations.count(animation): self.animations.remove(animation) if not self.animating() and self.world.current_character_turn: self.world.createMovementGrid( self.world.current_character_turn) def animating(self): return len(self.animations) > 0 @property def current_character(self): return self.world.current_character_turn @property def selected_action(self): if self.current_character: return self._selected_action else: return None @selected_action.setter def selected_action(self, value): self._selected_action = value def AIMove(self): if not self.animating() and self.world.current_character_turn: #cProfile.runctx("self.AI_command = self.ai.getCommand()", globals(), locals(), sort = "cumulative") #self.AI_command = self.ai.getCommand() self.ai_output, ai_input = Pipe(False) #cProfile.runctx("self.ai.getCommand(ai_input)", globals(), locals(), sort = "cumulative") Process(target=self.ai.getCommand, args=(ai_input, )).start() self.addAnimation(self.ai) self.gui.ai_status.show() def startAIPlay(self): self.ai_play = True def _pump(self): if self.world: if not self.animating( ) and self.replaying and self.world.current_character_turn: command = self.replay.getCommand() if command: self.battle_controller.executeCommand(command) else: self.replaying = False elif not self.animating( ) and self.ai_play and self.world.current_character_turn: if len(self.world.getSurvivingTeams()) > 1: self.AIMove() else: self.ai_play = False for character in self.world.characters: if character.cur_HP > 0: self.gui.sayBubble(character.visual.instance, "Victory!") elif not self.animating() and self.world.current_character_turn: if self.world.current_character_turn.cur_AP <= 0: self.battle_controller.endTurn() elif not self.animating( ) and not self.world.current_character_turn: action = self.world.timeline.popAction() if action: action() elif self.animations.count(self.ai) > 0: ai_message = None while self.ai_output.poll(): ai_message = self.ai_output.recv() #print ai_message, type(ai_message) if type(ai_message) == Replay: self.replay = ai_message self.replaying = True self.removeAnimation(self.ai) self.gui.ai_status.window.hide() break if type(ai_message) == float: self.gui.ai_status.progress_bar.setProgress(ai_message) #if not self.world.visual and not self.replaying: # self.createVisual() if self.world.visual: self.gui.pump() self.view.pump() if self._listener.quitrequested: self.quit()
def __init__(self): super(ZombiesWTF, self).__init__(TDS) self.world = world.World(self.engine) self.listener = ApplicationListener(self.engine, self.world) self.soundmanager = SoundManager(self.engine)