예제 #1
0
class GameManager(FSM):
    def __init__(self, filename):
        FSM.__init__(self, 'Game')

        self.savedGame = PlayerFileParser("save.xml")
        self.playerData = self.savedGame.playerData
        self.playerData.setShip(shipDb[self.playerData.ship.name])

        self.crosshair = MouseCursor()
        self.crosshair.setMode(1)

        self.mainMenu = MainMenu()
        self.mainMenu.hide()
        self.mainMenu.buttons[0]["command"] = self.request
        self.mainMenu.buttons[0]["extraArgs"] = ["Space"]

        self.mainMenu.buttons[1]["command"] = self.request
        self.mainMenu.buttons[1]["extraArgs"] = ["Ground"]

        self.mainMenu.buttons[3]["command"] = self.quit
        self.mainMenu.buttons[3]["extraArgs"] = [0]

        #self.groundGui = GroundGui(self.playerData)
        #self.groundWorldManager = GroundManager(self)

        #self.spaceWorldManager = SpaceOdeWorldManager(self)

        self.prevState = None

        self.trans = Transitions(loader)

        self.request("IntroMainMenu")
        #self.request("Space")

    def quit(self, extraArgs=[]):
        audio3d.detachListener()
        sys.exit()

    def getEscape(self):
        if self.state == "Space":
            if self.spaceWorldManager.camHandler.mode == "turret":
                self.spaceWorldManager.setMode("manual")
            else:
                self.prevState = "Space"
                self.request("IntroMainMenu")

        elif self.state == "Ground":
            self.prevState = "Ground"
            self.request("IntroMainMenu")
        elif self.state == "IntroMainMenu":
            if self.prevState is not None:
                self.request(self.prevState)

    def saveGame(self):
        self.savedGame.save()

    def enterIntroMainMenu(self):
        #print "we entered intro main menu"
        self.mainMenu.show()
        self.trans.fadeIn()

    def exitIntroMainMenu(self):
        #print("we exited intro main menu")
        self.trans.fadeOut()
        self.mainMenu.hide()

    def enterSpace(self):
        #print "we entered space"
        '''
		audio3d = Audio3DManager.Audio3DManager(base.sfxManagerList[0], camera)
		audio3d.setDistanceFactor(100)
		audio3d.setListenerVelocityAuto()
		#audio3d.attachListener(camera)
		'''
        self.trans.fadeIn()
        self.spaceWorldManager = SpaceOdeWorldManager(self)
        self.spaceWorldManager.start()

    def exitSpace(self):
        #print("we exited space")
        self.trans.fadeOut()
        self.spaceWorldManager.destroy()
        del self.spaceWorldManager

    def enterGround(self):
        #print "we entered ground"
        self.trans.fadeIn()
        self.groundWorldManager = GroundManager(self)
        self.groundWorldManager.start()

    def exitGround(self):
        #print("we exited ground")
        self.trans.fadeOut()
        self.groundWorldManager.destroy()
        del self.groundWorldManager
예제 #2
0
class EffectsManager:
    """Manager to control the game visual effects."""

    def __init__(self):
        base.enableParticles()  # noqa: F821
        render.setShaderAuto()  # noqa: F821

        self._explosion_lights = self._set_explosion_lights()

        self._transition = Transitions(loader)  # noqa: F821
        self._transition.setFadeColor(0, 0, 0)

        self.stench_effect = Stench()
        self.love_fog = LoveFog()

        filters = CommonFilters(base.win, base.cam)  # noqa: F821
        filters.setBloom(size="large", mintrigger=0.8, intensity=2.1)

    def _set_explosion_lights(self):
        """Prepare three explosion lights.

        Build a list-pool of light objects to
        be used in different explosions.

        Returns:
            list: List of lights to be used for explosions.
        """
        lights = []
        for num in range(3):
            light = PointLight("explosion_light_" + str(num))
            light.setColor((1, 0.9, 0.55, 1))
            light.setAttenuation((0, 0, 1))
            light_np = render.attachNewNode(light)  # noqa: F821
            light_np.setPos(0, 0, -5)
            render.setLight(light_np)  # noqa: F821
            lights.append(light_np)

        return lights

    def bomb_explosion(self, parent):
        """Prepare a bomb explosion effect for the given object.

        Args:
            parent (object): Must include "model" property.

        Returns:
            BombExplosion: Hand bomb explosion effect object.
        """
        return BombExplosion(parent)

    def burn_smoke(self, parent):
        """Prepare a burning object smoke effect.

        Args:
            parent (object): Must include "id" and "model" properties.

        Returns:
            BurnSmoke: Burning object smoke effect.
        """
        return BurnSmoke(parent)

    def explosion(self, parent):
        """Prepare an explosion effect for the given object.

        Args:
            parent (object): Must include "id" and "model" properties.

        Returns:
            Explosion: Explosion effect object.
        """
        return Explosion(self._explosion_lights, parent, "explode_fire", 0.9)

    def explosion_big(self, parent):
        """Prepare a big explosion effect for the given object.

        Args:
            parent (object): Must include "id" and "model" properties.

        Returns:
            Explosion: Explosion effect object.
        """
        return Explosion(self._explosion_lights, parent, "explode_fire2", 1.9)

    def fade_in_screen(self, task):
        """Smoothly fill the screen with natural colors."""
        self._transition.fadeIn(3)
        return task.done

    def fade_out_screen(self, task):
        """Smoothly fill the screen with black color."""
        self._transition.fadeOut(3)
        return task.done
예제 #3
0
class Game(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        self.cfg = cfgdict("data/default_config.cfg")
        globalClock.setMode(ClockObject.MLimited)
        globalClock.setFrameRate(int(self.cfg["general"]["framerate"]))
        #base.setFrameRateMeter(int(self.cfg["general"]["debug"]))
        self.props = WindowProperties()
        self.props.setSize(tuple(self.cfg["general"]["resolution"]))
        self.props.setFullscreen(int(self.cfg["general"]["fullscreen"]))
        self.props.setCursorHidden(True)
        self.fullscreen = int(self.cfg["general"]["fullscreen"])
        #props.setMouseMode(WindowProperties.M_relative)
        base.win.requestProperties(self.props)
        base.disableMouse()
        base.win.setClearColor((0, 0, 0, 0))
        self.inputs = Inputs(self.cfg["key"])

        #cats=["mainmenu", "parts", "enemies", "items"]
        #for cat in cats: makeWireframe(cat)

        self.hud = HUD(self)

        self.transition = Transitions(loader)
        self.parts_models = getParts("data/models/egg/parts/parts")
        self.enemy_models = getParts("data/models/egg/enemies/enemies")
        self.item_models = getParts("data/models/egg/items/items")

        sounds = [
            "break",
            "error",
            "explosion",
            "hit_a",
            "hit_b",
            "hit_c",
            "scare",
            "select_a",
            "select_b",
            "splurt_a",
            "splurt_b",
            "swallow",
            "step_enemy_a",
            "step_enemy_b",
            "step_enemy_c",
            "step_player",
            "turn",
            "projectile_a",
            "projectile_b",
            "projectile_c",
        ]
        self.sounds = {}
        for sound in sounds:
            self.sounds[sound] = loader.loadSfx("data/sound/" + sound + ".wav")
        self.sounds["step_player"].setVolume(0.3)
        self.act = False
        if self.cfg["general"]["fx"] == 1:
            render.setShaderAuto()
            aspect2d.setShaderAuto()
            filters = CommonFilters(base.win, base.cam)
            filters.setBloom(blend=(0.1, 0.1, 0.1, 0.0),
                             mintrigger=0.0,
                             maxtrigger=0.1,
                             desat=0.0,
                             intensity=0.6,
                             size="small")
        #self.startGame()

    def startGame(self):
        self.hud.output.append("...")
        self.hud.output.append("You wake up, head on the keyboard.")
        self.hud.output.append("Where is everybody?")
        render.node().removeAllChildren()
        self.mode = "game"
        self.delay = 0
        self.map = Map(self, 1)
        self.player = Player(self.map.start[0], self.map.start[1], 2)
        self.transition.setFadeColor(0, 0, 0)
        self.transition.fadeIn(2)
        d = DirectionalLight("d")
        dn = render.attachNewNode(d)
        self.actions = []
        base.camera.setHpr(0, 0, 0)
        base.camera.setPos(0, 0, 0)
        drinks = ["red", "yellow", "orange", "green", "blue", "purple"]
        types = ["health", "cure", "poison", "blind", "improve", "warmth"]
        self.drinks = {}
        for drink in drinks:
            rt = choice(types)
            types.remove(rt)
            self.drinks[drink] = [rt, False]
        render.setLight(dn)

    def nextLevel(self):
        render.node().removeAllChildren()
        render.hide()
        self.transition.setFadeColor(0, 0, 0)
        self.transition.fadeOut(1)
        self.delay = 0
        self.actions = []
        self.map = Map(self, self.map.level + 1)
        self.hud.output.append("You reach the " + str(20 - self.map.level) +
                               "th floor.")
        self.player.place = [self.map.start[0], self.map.start[1] - 1, 2]
        self.player.prev_place = self.player.place[:]
        self.player.pos = [self.map.start[0], self.map.start[1] - 1]
        render.show()
        self.player.camera.node.reparentTo(render)
        d = DirectionalLight("d")
        dn = render.attachNewNode(d)
        render.setLight(dn)
        self.transition.fadeIn(1)
        self.mode = "game"

    def mainMenu(self, task):
        if self.running:
            self.mcp[3] += 1
            self.mcp[2] = 8 + (sin(self.mcp[3] / 50) * 7)
            base.camera.setPos(self.mcp[0], self.mcp[1], self.mcp[2])
            self.buildingmodel["tower"][0].setHpr(self.mcp[3], 0, 0)
            self.buildingmodel["tower"][1].setHpr(self.mcp[3], 0, 0)
            if self.inputs.buttons["quit"]:
                self.running = False
            if self.inputs.buttons["stats"]:
                self.inputs.buttons["stats"] = False
                self.bgsong.stop()
                self.sounds["select_b"].play()
                base.camera.setPos(0, 0, 0)
                self.hud.loadGameHud()
                self.startGame()
                self.bgsong = loader.loadSfx("data/music/LEVEL1.ogg")
                self.bgsong.setVolume(0.3)
                self.bgsong.setLoop(True)
                self.bgsong.play()
                self.taskMgr.add(self.loop, "main_loop")
                return False
            return task.cont
        print("bye!")
        exit()

    def load(self):
        self.running = True
        self.actions = []
        self.bgsong = loader.loadSfx("data/music/THEME.ogg")
        self.bgsong.setVolume(0.5)
        self.bgsong.setLoop(True)
        self.bgsong.play()

        self.buildingmodel = getParts("data/models/egg/mainmenu/mainmenu")
        self.buildingmodel["tower"][0].reparentTo(render)
        self.buildingmodel["tower"][1].reparentTo(render)

        d = DirectionalLight("d")
        dn = render.attachNewNode(d)
        render.setLight(dn)
        self.mcp = [0, -20, 8, 1200]
        self.taskMgr.add(self.mainMenu, "main_menu")

    def loop(self, task):
        if self.running:
            self.hud.update()
            if self.mode == "game":
                if self.inputs.buttons["quit"]:
                    self.running = False
                if self.player.stats.status == "Dying":
                    self.hud.output.append("You died.")
                    self.mode = "gameover"
                    self.sounds["explosion"].play()
                    taskMgr.add(die())
                else:
                    self.delay -= 1
                    if self.delay <= 0:
                        self.delay = 0
                        if len(self.actions) > 0:
                            for action in self.actions:
                                a = action[0](action[1])
                                if a == 1:
                                    self.actions.remove(action)
                        else:
                            self.input()
                        self.update()
            elif self.mode == "gameover":
                base.camera.setH(base.camera.getH() + 2)
                base.camera.setZ(base.camera.getZ() - 0.001)
            # Hud input, choices, etc.
            elif self.mode == "inventory":
                close = False
                if self.inputs.buttons["return"]:
                    close = True
                else:
                    abc = "abcdefghijklmnopqrstuvwxyz0123456789"
                    cc = 100
                    if not self.inputs.raw_key == None:
                        if self.inputs.raw_key in abc:
                            for l, letter in enumerate(abc):
                                if self.inputs.raw_key == letter:
                                    cc = l
                        if cc < len(self.hud.choices):
                            item = self.hud.choices[cc]
                            if self.hud.verb == "inventory":
                                pass
                            elif self.hud.verb == "drop":
                                f = self.player.drop(item)
                                if f: self.act = True
                            elif self.hud.verb == "throw":
                                self.player.throw(item)
                                self.act = True
                            else:
                                f = self.hud.choices[cc].use(self.player)
                                if f: self.act = True
                            close = True
                if close:
                    self.mode = "game"
                    self.hud.inventory[0].setText("")
                    self.hud.choices = []
                    self.inputs.buttons["return"] = False

            elif self.mode == "restart":
                self.startGame()
            self.inputs.raw_key = None
            return task.cont
        print("bye!")
        exit()

    def input(self):
        act = self.act
        tile = self.map.grid[self.player.pos[1]][self.player.pos[0]]
        if act == False:
            if self.inputs.buttons["turn_left"]:
                self.sounds["turn"].play()
                self.player.turn(1)
                self.actions.append((self.player.turn, 1))
            elif self.inputs.buttons["turn_right"]:
                self.sounds["turn"].play()
                self.player.turn(-1)
                self.actions.append((self.player.turn, -1))
            elif self.inputs.buttons["forward"]:
                en = self.player.move(-1)
                if not en == "cancel":
                    if en == "melee":
                        self.delay = 10
                        self.player.stats.attack(self.player.target.stats,
                                                 True)
                        self.player.target.switchFrame("hurt")
                        self.transition.setFadeColor(0.1, 0.1, 0.1)
                        self.transition.fadeOut(0.1)
                        self.transition.fadeIn(0.01)
                        self.hud.update()
                        l = "_a", "_b", "_c"
                        self.sounds["hit" + choice(l)].play()
                        act = True
                    else:
                        self.actions.append((self.player.move, -1))
                        act = True
            elif self.inputs.buttons["backward"]:
                self.sounds["turn"].play()
                self.player.turn(1)
                self.actions.append((self.player.turn, 1))
                self.player.turn(1)
                self.actions.append((self.player.turn, 1))
            elif self.inputs.buttons["fire"]:
                f = self.player.fire()
                if f:
                    act = True

            elif self.inputs.buttons["wait"]:
                act = True
                self.sounds["turn"].play()
                self.delay = 10
                self.hud.output.append("You wait.")
            elif self.inputs.buttons["take"]:
                if not tile.item == None:
                    abc = "abcdefghijklmnopqrstuvwxyz"
                    if len(self.player.stats.inventory) < len(abc):
                        self.sounds["select_b"].play()
                        tile.item[0].removeNode()
                        i = tile.item[1]
                        self.player.stats.inventory.append(i)
                        self.hud.output.append("You found a " + i.name)
                        tile.item = None
                        act = True
                    else:
                        self.hud.output.append("You can't carry any more.")
                        self.delay = 10
            elif self.inputs.buttons["stairs_down"]:
                if tile.c == "<":
                    self.nextLevel()
                self.inputs.buttons["stairs_down"] = False
            elif self.inputs.buttons["fullscreen"]:
                if self.fullscreen:
                    self.fullscreen = 0
                else:
                    self.fullscreen = 1
                self.props.setFullscreen(int(self.fullscreen))
                base.win.requestProperties(self.props)
                self.inputs.buttons["fullscreen"] = False
            else:
                verbs = "inventory", "drop", "throw", "eat", "quaff", "wield", "stats", "help"
                for i in self.inputs.buttons:
                    if self.inputs.buttons[i]:
                        if i in verbs:
                            self.mode = "inventory"
                            self.hud.inv(self.player, i)
                            self.inputs.buttons[i] = False
        if act:
            self.act = False
            self.player.stats.turn()
            for e, enemy in enumerate(self.map.enemies):
                if self.player.stats.speedboost <= 0 or randint(0, 2) == 0:
                    en = enemy.plan(self, e)
                    if en:
                        enemy.stats.turn()
                        self.actions.append((enemy.move, self))
            self.player.stats.updateStats()

    def update(self):
        self.player.update()
        for enemy in self.map.enemies:
            enemy.update(self)
예제 #4
0
class MakeAToon:
    def __init__(self):
        self.notify = DirectNotifyGlobal.directNotify.newCategory("Starting Make A Toon.")
        self.localAvatar = LocalAvatar.toonBody
        base.localAvatar = self.localAvatar
        self.toonColors = Localizer.toonColorDict
        self.colorNum = 0
        self.numColors = Localizer.numColors
        self.MakeAToonText = Localizer.MakeAToonText
        self.Mickey = Localizer.Mickey
        self.mickeyFont = loader.loadFont('phase_3/models/fonts/MickeyFont.bam')
        self.Text = OnscreenText(text = "Make A Toon", pos = (0, 0.75), font = self.mickeyFont, fg = (1, 0, 0, 1),scale=(0.2, 0.2, 0.2))
        self.gui = loader.loadModel('phase_3/models/gui/tt_m_gui_mat_mainGui.bam')
        self.gui.flattenMedium()
        self.gui1 = loader.loadModel('phase_3/models/gui/create_a_toon_gui.bam')
        self.gui2 = loader.loadModel('phase_3/models/gui/gui_toongen.bam')
        self.guiNextUp = self.gui.find('**/tt_t_gui_mat_nextUp')
        self.transition = Transitions(loader)
        self.transition.irisIn(1)
        self.transition.fadeIn(5)
        self.load()

    def load(self):
        self.Music = loader.loadMusic('phase_3/audio/bgm/create_a_toon.mid')
        self.Music.setLoop(1)
        self.MusicVolume = (0.4)
        self.Music.play()
        self.Music.setVolume(self.MusicVolume)
        base.localAvatar.setPos(0.80, 2, 0)
        base.localAvatar.setHpr(176, 0, 0)
        LocalAvatar.setMovementAnimation('neutral')
        self.room = loader.loadModel('phase_3/models/gui/create_a_toon.bam')
        self.room.reparentTo(render)
        self.room.find('**/sewing_machine').removeNode()
        self.room.find('**/drafting_table').removeNode()
        self.room.find("**/wall_floor").setColor(0.7294117647058824, 0.5490196078431373, 0.2392156862745098, 1)
        self.room.setName("Room")
        self.ee = DirectFrame(pos=(-1, 1, 1), frameSize=(-.01, 0.01, -.01, 0.01), frameColor=(0, 0, 0, 0.05), state='normal')
        self.ee.bind(DGG.B1PRESS, lambda x, ee = self.ee: self.toggleSlide())
        self.eee = self.ee
        self.toonSpin = base.localAvatar.hprInterval(2, Vec3(540, 0, 0))
        self.toonSpin2 = base.localAvatar.hprInterval(2, Vec3(180, 0, 0))
        self.CameraMove = camera.posInterval(1,
                                  Point3(-0.50, -11, 3),
                                  startPos=Point3(1, -11, 3))
        self.CameraMoveSequence = Sequence(self.CameraMove)
        self.ToonEnter = base.localAvatar.posInterval(1,
                                  Point3(0.60, 2, 0),
                                  startPos=Point3(-4, 2, 0))
        self.ToonEnterPace = Sequence(self.ToonEnter)
        self.ToonEnter.start()
        self.oobeButton = DirectButton(clickSound=Globals.getClickSound(), rolloverSound=Globals.getRlvrSound(), geom = (self.gui1.find("**/CrtATn_R_Arrow_UP"), self.gui1.find("**/CrtATn_R_Arrow_DN"), self.gui1.find("**/CrtATn_R_Arrow_RLVR")), relief=None, hpr=(0, 0, 180), command=self.goBack)
        self.oobeButton.setScale(1)
        self.oobeButton.setPos(-0.70,3,-0.25)
        self.goBackButton = DirectButton(clickSound=Globals.getClickSound(), rolloverSound=Globals.getRlvrSound(), geom = (self.gui1.find("**/CrtATn_R_Arrow_UP"), self.gui1.find("**/CrtATn_R_Arrow_DN"), self.gui1.find("**/CrtATn_R_Arrow_RLVR")), relief=None, command=self.goRight)
        self.goBackButton.setScale(1)
        self.goBackButton.setPos(0.80,3,-0.25)
        self.spinButton = DirectButton(clickSound=Globals.getClickSound(), rolloverSound=Globals.getRlvrSound(), geom = (self.gui1.find("**/CrtATn_R_Arrow_UP"), self.gui1.find("**/CrtATn_R_Arrow_DN"), self.gui1.find("**/CrtATn_R_Arrow_RLVR")), relief=None, command=self.HprToon)
        self.spinButton.setScale(0.60)
        self.spinButton.setPos(0.50,2,-0.50)
        self.spinButton2 = DirectButton(clickSound=Globals.getClickSound(), rolloverSound=Globals.getRlvrSound(), geom = (self.gui1.find("**/CrtATn_R_Arrow_UP"), self.gui1.find("**/CrtATn_R_Arrow_DN"), self.gui1.find("**/CrtATn_R_Arrow_RLVR")), relief=None, hpr=(0, 0, 180), command=self.HprToon2)
        self.spinButton2.setScale(0.60)
        self.spinButton2.setPos(-0.40,2,-0.50)
        self.OK = DirectButton(clickSound=Globals.getClickSound(), rolloverSound=Globals.getRlvrSound(), geom=(self.gui2.find("**/tt_t_gui_mat_okUp"), self.gui2.find("**/tt_t_gui_mat_okDown")), pos=(0.90,1,-0.80), relief=None, command=self.CameraButton)


    def goRight(self):
        for color in self.toonColors[self.colorNum]:
            LocalAvatar.bodyNodes[color].setColor(self.toonColors[self.colorNum][color])
        self.colorNum += 1
        if self.colorNum > self.numColors:
            self.colorNum = 0

    def goBack(self):
        for color in self.toonColors[self.colorNum]:
            LocalAvatar.bodyNodes[color].setColor(self.toonColors[self.colorNum][color])
        self.colorNum -= 1
        if self.colorNum < 0:
            self.colorNum = self.numColors
    
    def HprToon(self):
        self.toonSpin.start()

    def HprToon2(self):
        self.toonSpin2.start()

    def CameraButton(self):
        self.transition.irisIn()
        self.transition.fadeOut(1)
        self.Music.stop()
class Tutorial:
    def __init__(self, pat):
        self.t = Transitions(loader)
        self.pickAToon = pat

    def askTutorial(self):
        self.firstTimeMsg = YesNoDialog(text=CIGlobals.FirstTimeMsg,
                                        text_scale=0.07,
                                        text_wordwrap=18,
                                        buttonGeomList=[
                                            CIGlobals.getOkayBtnGeom(),
                                            CIGlobals.getCancelBtnGeom()
                                        ],
                                        button_relief=None,
                                        button_text_pos=(0, -0.1),
                                        command=self.handleTutorialDecision,
                                        image_color=CIGlobals.DialogColor,
                                        fadeScreen=1)

    def handleTutorialDecision(self, value):
        if value:
            self.firstTimeMsg.destroy()
            self.startTutorial()
            base.hoodBGM.stop()
        else:
            self.firstTimeMsg.destroy()
            self.enablePatButtons()

    def enablePatButtons(self):
        for btn in self.pickAToon.btnList:
            btn['state'] = DGG.NORMAL
        self.pickAToon.quit_btn['state'] = DGG.NORMAL

    def startTutorial(self):
        self.t.fadeOut(1)
        Sequence(Wait(1.2), Func(self.playVideo)).start()

    def playVideo(self):
        self.t.fadeIn(0)
        self.pickAToon.removeGui()
        self.movieTex = MovieTexture("tutorial")
        assert self.movieTex.read(
            "tutorial.avi"), "Failed to load tutorial video"

        cm = CardMaker("tutorialCard")
        cm.setFrameFullscreenQuad()
        self.card = NodePath(cm.generate())
        self.card.reparentTo(render2d)
        self.card.setTexture(self.movieTex)
        self.card.setTexScale(TextureStage.getDefault(),
                              self.movieTex.getTexScale())
        self.movieSound = loader.loadSfx("tutorial.avi")
        self.movieTex.synchronizeTo(self.movieSound)

        self.movieSound.play()
        taskMgr.add(self.checkMovieStatus, "checkMovieStatus")

    def checkMovieStatus(self, task):
        if self.movieSound.status() == AudioSound.READY:
            self.stopVideo()
            return task.done
        return task.cont

    def stopVideo(self):
        self.movieSound.stop()
        self.card.removeNode()
        self.t.fadeOut(0)
        self.pickAToon.createGui(1)
        Sequence(Wait(0.2), Func(self.t.fadeIn, 1)).start()
예제 #6
0
class LevelChanger(DirectObject):
    
    #Use this to handle changing of levels
    #check the emeny list and if it is empty then change the level
    #Flag to tell if the level is complete
    levelComplete = False

    def __init__(self):
        
        #Level map
        self.level01 = "resources/theSouthBridge"
        self.level02 = "resources/theSocket"
        self.level03 = "resources/theDualChannel"
        self.level04 = "resources/theRoot"
        self.levelMap = {1:self.level01, 2:self.level02, 3:self.level03, 4:self.level04}
        self.currentLevel = 1
        
        #Level music map
        self.level01M = base.loader.loadMusic("resources/sounds/level1.wav")
        self.level02M = base.loader.loadMusic("resources/sounds/level2.wav")
        self.level03M = base.loader.loadMusic("resources/sounds/level3.wav")
        self.level04M = base.loader.loadMusic("resources/sounds/bossMusic.wav")
        self.musicMap = {1:self.level01M, 2:self.level02M, 3:self.level03M, 4:self.level04M}

        self.currentMusic = self.musicMap[self.currentLevel]

        self.currentMusic.setLoop(True)
        self.currentMusic.play()

        #Open file to get player spawns 
        self.pSpawnsFile = open("playerSpawns.txt")
        self.pSpawnsList = self.pSpawnsFile.readlines()
        self.pSpawnsFile.close()
        
        #Set players current spawn
        self.spawnIndex = 0
        base.xPos = float(self.pSpawnsList[self.spawnIndex + 1].split("=")[1].translate(None,"\n"))
        base.yPos = float(self.pSpawnsList[self.spawnIndex + 2].split("=")[1].translate(None,"\n"))
        base.zPos = float(self.pSpawnsList[self.spawnIndex + 3].split("=")[1].translate(None,"\n"))
        base.player.playerNode.setPos(0, 0, 30) #resets height
        base.player.playerModel.setPos(base.xPos, base.yPos, base.zPos) #resets position

    #checks the enemy list
    #if the list is empty, level is complete
    #set flag to true and change the level.
    def checkLevel (self, task):
        
        enemy = base.spawner.spawnId
        
        if(len(base.enemyList) == 0):
            if enemy > 0:
                self.levelComplete = True
                if self.currentLevel == len(self.levelMap):
                    base.player.hide()
                    base.player.canUseWeapons = False
                    base.fsm.request('WinMenu', 1)
                    return task.done
                else:
                    self.changeLevel(task)
        
        return task.cont
        

    def changeLevel(self, task):
        
        if(self.levelComplete == True):
           
            self.transition = Transitions(loader)
            self.transition.setFadeColor(0, 0, 0)
            self.fadeOut = self.transition.fadeOut(2)

            #unload the current level and models
            self.unload(self.levelMap[self.currentLevel])

            #load the next level and models
            self.load(self.levelMap[self.currentLevel + 1])

            #self.fadeIn = self.transition.fadeIn(5)
            base.taskMgr.remove(task)
        
        return task.cont

    #Unloads current level objects
    def unload(self, level):

        for i in base.pickuplist:
           
            i.deletePickup = True
        
        for i in base.enemyList:
            
            i.delFlag = True
            i.deadFlag = True
        
        #stop the music
        self.currentMusic.stop()
        
        #detach playerNode
        base.player.playerNode.detachNode()
        
        #Remove enemies
        #base.taskMgr.remove("Spawn Enemies")
        base.taskMgr.remove("enemyCleanup")

        #unload the env and detach remove the node
        base.loader.unloadModel(level)
        base.environ.removeNode()
    
    #Load the next level
    def load(self, level):
        
        #Reset player health for the next level
        base.player.adjustHealth(base.player.maxEnergy)

        #load Environment - new level
        base.environ = base.loader.loadModel(level)
        base.environ.reparentTo(base.render)
        base.environ.setScale(7, 7, 3)
        
        #update the currentLevel.
        self.currentLevel += 1

        #reattach player to render
        base.player.playerNode.reparentTo(render)
	    
        #Set the next levels spawn coordinates 
        self.spawnIndex += 4
        base.xPos = float(self.pSpawnsList[self.spawnIndex + 1].split("=")[1].translate(None,"\n"))
        base.yPos = float(self.pSpawnsList[self.spawnIndex + 2].split("=")[1].translate(None,"\n"))
        base.zPos = float(self.pSpawnsList[self.spawnIndex + 3].split("=")[1].translate(None,"\n"))
        
        base.player.playerNode.setPos(0,0,30) #resets height
        base.player.playerModel.setPos(base.xPos, base.yPos, base.zPos) #resets position
        
        #create new spawner on the env
        base.spawner = Spawner(base.environ, level.split("/")[1].translate(None,"\n"))
        #Reinit enemies
        base.spawner.spawn()
        base.taskMgr.add(self.checkLevel, "checkLevel")
        base.taskMgr.add(base.enemyCleanUp, "enemyCleanup", taskChain='GameTasks')

        self.fadeIn = self.transition.fadeIn(2)
        
        self.currentMusic = self.musicMap[self.currentLevel]

        self.currentMusic.setLoop(True)
        self.currentMusic.play()
        
    #Returns the current level
    def getCurrentLevel(self):

        return self.currentLevel
    
    #Goes direcctly to the boss level
    def goToBoss(self):

        self.transition = Transitions(loader)
        self.transition.setFadeColor(0, 0, 0)
        self.fadeOut = self.transition.fadeOut(2)
        self.unload(self.levelMap[1])
        self.load(self.levelMap[4])
        self.currentLevel = 4
    
    #Resets enemies upon death
    def resetEnemy(self):

        base.player.playerModel.setPos(base.xPos, base.yPos, base.zPos)
        base.player.playerNode.setPos(0,0,30) #resets height
        
        for i in base.enemyList:
            i.delFlag = True
            i.deadFlag = True
            
        for i in base.pickuplist:
            i.deletePickup = True
            
        #create new spawner on the current level
        base.spawner = Spawner(base.environ, self.levelMap[self.currentLevel].split("/")[1].translate(None,"\n"))
        #Reinit enemies
        base.spawner.spawn()
예제 #7
0
class Play(DirectObject):
  def __init__(self, parent):
    #Turn off default mouse control
    base.disableMouse()
    base.setFrameRateMeter(True)
    
    #globalClock = ClockObject.getGlobalClock()
    #globalClock.setMode(ClockObject.MLimited)
    #globalClock.setFrameRate(1000)
    #Set windows properties
    self.props = WindowProperties()
    self.props.setCursorHidden(True)
    #props.setFullscreen(1)
    #props.setSize(int(base.pipe.getDisplayWidth()), int(base.pipe.getDisplayHeight()))
    self.props.setMouseMode(WindowProperties.MRelative)
    base.win.requestProperties(self.props)
    
    self.transition = Transitions(loader)
    self.transition.setFadeColor(0,0,0)
    
    self.parent = parent
    base.accept("escape", self.togglePause)
    self.setupSounds()
    self.startLevel(0, True)
    self.task = taskMgr.add(self.update, "updateTask")
  
  def fadeOut(self):
    self.transition.fadeOut(1)
    
  def fadeIn(self):
    self.transition.irisIn(1)
  
  def togglePause(self):
    if self.parent.paused:
      self.props.setCursorHidden(True)
      base.win.requestProperties(self.props)
      base.win.movePointer(0, base.win.getXSize()/2, base.win.getYSize()/2)
      taskMgr.add(self.task)
      self.parent.paused = False 
      self.parent.continueImage.hide()
      self.parent.restartImage.hide()
      self.parent.exitImage.hide()
      self.parent.mainFrame.hide()
      self.playingBGM.setTime(self.bgmTime) 
      self.playingBGM.play()
    else:
      self.props.setCursorHidden(False)
      base.win.requestProperties(self.props)
      taskMgr.remove(self.task)
      self.parent.paused = True
      self.parent.mainFrame.show()
      self.parent.continueImage.show()
      self.parent.restartImage.show()
      self.parent.exitImage.show()
      self.bgmTime = self.playingBGM.getTime() 
      self.playingBGM.stop()
  
  def chaseBGM(self, chasing = False):
    if chasing and self.playingBGM != self.bgFast:
      self.playingBGM.stop()
      self.playingBGM = self.bgFast
      self.bgmTime = 0
      self.playingBGM.play()
    elif not chasing and self.playingBGM != self.bgSlow:
      self.playingBGM.stop()
      self.playingBGM = self.bgSlow
      self.bgmTime = 0
      self.playingBGM.play()
    
  def initModels(self):
    self.map = MapGen(self)
    # self.player = Player(self)
    # self.level = Level()
    self.enemies = []
  
  def transitionFunc(self, level, next = False):
    tSequence = Sequence(Func(self.fadeOut), Wait(1), Func(self.startLevel, level, next), 
                               Func(self.fadeIn))
    tSequence.start()
  
  #level number, next = true if next level (false = respawning)
  def startLevel(self, level, next = False):
    # per pixel lighting
    render.clearLight()
    render.setShaderAuto()
    try:
        self.level.initLight()
    except AttributeError:
        pass
    try:
        self.player.initHandLight()
    except AttributeError:
        pass

    # """
    # render.clearLight()
    # render.setShaderAuto()
    # """
    # self.map = MapGen(self)
    # self.player = Player(self)
    # self.level = Level()
    # self.enemies = []
    
    if next:
      for node in render.getChildren():
        node.removeNode()
      for node in base.camera.getChildren():
        if node.getName() != 'cam':
          print node.getName()
          node.removeNode()
    else:
      #Clear render
      self.player.clearItems()
    
    #If next level, load level map
    
      #and initialize enemies
    if next:
      level += 1
      for node in render.getChildren():
        node.removeNode()
      
      self.player = Player(self)
      self.level = Level()
      self.enemies = []
      self.player.level = level

      self.level.loadLevel(level)
      for enemy in self.level.enemies:
        enemySpawn = Enemy( self, enemy[0], enemy[1] )
        self.enemies.append(enemySpawn)
        
    playerPos = self.level.playerPos #level.spawnPos
    walls = self.level.numWalls
    lights = self.level.numLights
    #Spawn player using spawn (spawn pos, max walls, max lights)
    self.player.spawn(playerPos,walls,lights)
    
    if not next:
      for enemy in self.enemies:
        enemy.respawn()
        
    self.playingBGM = self.bgSlow
    self.playingBGM.play()
    
    if next:
      self.setupCollisions()
    
    
  def die(self, level, next = False):
    self.transitionFunc(level, next)
    
  def setupCollisions(self): 
    #Make a collision traverser, set it to default   
    base.cTrav = CollisionTraverser()
    base.itemTrav = CollisionTraverser()
    base.pusher = CollisionHandlerPusher()
    
    base.cHandler = CollisionHandlerEvent()
    base.queue = CollisionHandlerQueue()
    base.eQueue = CollisionHandlerQueue()
    #Set the pattern for the event sent on collision
    base.cHandler.setAgainPattern("%fn-again-%in")
    base.cHandler.setInPattern("%fn-into-%in")
    base.cHandler.setOutPattern("%fn-out-%in")
    
    self.player.initCollisions()
    for enemy in self.enemies:
      enemy.initCollisions(self.player)
    
    #base.cTrav.showCollisions(render)

  #Set up BGM
  def setupSounds(self):
    ######################slow music##########################
    self.bgSlow = base.loadMusic("sounds/slow.ogg")
    self.bgSlow.setLoopCount(0)
    ######################fast music############################
    self.bgFast = base.loadMusic("sounds/fast.ogg")
    self.bgFast.setLoopCount(0)
    self.playingBGM = self.bgSlow    
    
  def update(self, task):
    dt = globalClock.getDt()
    self.player.update(globalClock.getDt())
    if self.player.newLevel:
      return task.cont
    for enemy in self.enemies:
      enemy.update(globalClock.getDt(), self.player)
    return task.cont
예제 #8
0
class Engine(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        self.disableMouse()

        props = WindowProperties()
        props.setTitle('Test')
        self.win.requestProperties(props)

        # self.render.setAntiAlias(AntialiasAttrib.MAuto)

        self.transitions = Transitions(self.loader)
        self.transitions.setFadeColor(0, 0, 0)

        self.filters = CommonFilters(self.win, self.cam)
        # self.filters.setCartoonInk()
        self.filters.setBlurSharpen(1)
        # self.filters.setVolumetricLighting(self.render)

        # self.buffer = self.win.makeTextureBuffer("Post-processing buffer", self.win.getXSize(), self.win.getXSize())
        # print self.buffer.getYSize()
        # self.texture = self.buffer.getTexture()
        # self.buffer.setSort(-100)
        #
        # self.originalCamera = self.camera
        # self.offScreenCamera = self.makeCamera(self.buffer)
        # self.camera = self.offScreenCamera
        #
        # self.img = OnscreenImage(image=self.texture, pos=(0, 0, 0.5))

        self.scene = None
        self.channel = Channel()

    def set_scene(self, scene_module):
        # self.transitions.fadeOut(0.2)
        args = []

        if self.scene:
            args.append(
                Parallel(Func(self.fade_out),
                         LerpFunc(self.blur_out, duration=0.2)))
            args.append(Wait(0.2))

        args.append(Func(self._set_scene, scene_module))
        args.append(
            Parallel(Func(self.fade_in), LerpFunc(self.blur_in, duration=0.4)))

        Sequence(*args).start()

    def blur_out(self, t):
        # index = int(t)
        # self.filters.delBlurSharpen()
        self.filters.setBlurSharpen(1 - t)
        self.filters.setBloom(intensity=t)

    def blur_in(self, t):
        # index = int(t)
        # self.filters.delBlurSharpen()
        self.filters.setBlurSharpen(t)
        self.filters.setBloom(intensity=-t)

    def fade_out(self):
        self.transitions.fadeOut(0.2)

    def fade_in(self):
        self.transitions.fadeIn(0.2)

    def _set_scene(self, scene_module):
        group, class_ = scene_module.split('.')
        module = importlib.import_module('game.scenes.{}'.format(group))
        scene_class = getattr(module, class_)
        if self.scene:
            self.scene.destroy()
            del self.scene
        self.scene = scene_class(self)
        # self.transitions.fadeIn(0.2)

    def start(self):
        self.channel = Channel()
        self.channel.connect()

        self.set_scene('auth.AuthScene')

        while True:
            self.taskMgr.step()
            if self.channel.can_read():
                for packet in self.channel.read_packets():
                    self.scene.on_packet(packet)
예제 #9
0
파일: engine.py 프로젝트: and3rson/gs
class Engine(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        self.disableMouse()

        props = WindowProperties()
        props.setTitle('Test')
        self.win.requestProperties(props)

        # self.render.setAntiAlias(AntialiasAttrib.MAuto)

        self.transitions = Transitions(self.loader)
        self.transitions.setFadeColor(0, 0, 0)

        self.filters = CommonFilters(self.win, self.cam)
        # self.filters.setCartoonInk()
        self.filters.setBlurSharpen(1)
        # self.filters.setVolumetricLighting(self.render)

        # self.buffer = self.win.makeTextureBuffer("Post-processing buffer", self.win.getXSize(), self.win.getXSize())
        # print self.buffer.getYSize()
        # self.texture = self.buffer.getTexture()
        # self.buffer.setSort(-100)
        #
        # self.originalCamera = self.camera
        # self.offScreenCamera = self.makeCamera(self.buffer)
        # self.camera = self.offScreenCamera
        #
        # self.img = OnscreenImage(image=self.texture, pos=(0, 0, 0.5))

        self.scene = None
        self.channel = Channel()

    def set_scene(self, scene_module):
        # self.transitions.fadeOut(0.2)
        args = []

        if self.scene:
            args.append(Parallel(Func(self.fade_out), LerpFunc(self.blur_out, duration=0.2)))
            args.append(Wait(0.2))

        args.append(Func(self._set_scene, scene_module))
        args.append(Parallel(Func(self.fade_in), LerpFunc(self.blur_in, duration=0.4)))

        Sequence(*args).start()

    def blur_out(self, t):
        # index = int(t)
        # self.filters.delBlurSharpen()
        self.filters.setBlurSharpen(1 - t)
        self.filters.setBloom(intensity=t)

    def blur_in(self, t):
        # index = int(t)
        # self.filters.delBlurSharpen()
        self.filters.setBlurSharpen(t)
        self.filters.setBloom(intensity=-t)

    def fade_out(self):
        self.transitions.fadeOut(0.2)

    def fade_in(self):
        self.transitions.fadeIn(0.2)

    def _set_scene(self, scene_module):
        group, class_ = scene_module.split('.')
        module = importlib.import_module('game.scenes.{}'.format(group))
        scene_class = getattr(module, class_)
        if self.scene:
            self.scene.destroy()
            del self.scene
        self.scene = scene_class(self)
        # self.transitions.fadeIn(0.2)

    def start(self):
        self.channel = Channel()
        self.channel.connect()

        self.set_scene('auth.AuthScene')

        while True:
            self.taskMgr.step()
            if self.channel.can_read():
                for packet in self.channel.read_packets():
                    self.scene.on_packet(packet)
예제 #10
0
파일: game.py 프로젝트: arikel/openlancer
class GameManager(FSM):
	
	def __init__(self, filename):
		FSM.__init__(self, 'Game')
		
		self.savedGame = PlayerFileParser("save.xml")
		self.playerData = self.savedGame.playerData
		self.playerData.setShip(shipDb[self.playerData.ship.name])
		
		self.crosshair = MouseCursor()
		self.crosshair.setMode(1)
		
		self.mainMenu = MainMenu()
		self.mainMenu.hide()
		self.mainMenu.buttons[0]["command"] = self.request
		self.mainMenu.buttons[0]["extraArgs"] = ["Space"]
		
		self.mainMenu.buttons[1]["command"] = self.request
		self.mainMenu.buttons[1]["extraArgs"] = ["Ground"]
		
		self.mainMenu.buttons[3]["command"] = self.quit
		self.mainMenu.buttons[3]["extraArgs"] = [0]
		
		
		#self.groundGui = GroundGui(self.playerData)
		#self.groundWorldManager = GroundManager(self)
		
		#self.spaceWorldManager = SpaceOdeWorldManager(self)
		
		self.prevState = None
		
		self.trans = Transitions(loader)
		
		self.request("IntroMainMenu")
		#self.request("Space")
	
	def quit(self, extraArgs=[]):
		audio3d.detachListener()
		sys.exit()
		
	def getEscape(self):
		if self.state == "Space":
			if self.spaceWorldManager.camHandler.mode == "turret":
				self.spaceWorldManager.setMode("manual")
			else:
				self.prevState = "Space"
				self.request("IntroMainMenu")
			
		elif self.state == "Ground":
			self.prevState = "Ground"
			self.request("IntroMainMenu")
		elif self.state == "IntroMainMenu":
			if self.prevState is not None:
				self.request(self.prevState)
		
	def saveGame(self):
		self.savedGame.save()
	
	def enterIntroMainMenu(self):
		#print "we entered intro main menu"
		self.mainMenu.show()
		self.trans.fadeIn()
		
	def exitIntroMainMenu(self):
		#print("we exited intro main menu")
		self.trans.fadeOut()
		self.mainMenu.hide()
		
	def enterSpace(self):
		#print "we entered space"
		'''
		audio3d = Audio3DManager.Audio3DManager(base.sfxManagerList[0], camera)
		audio3d.setDistanceFactor(100)
		audio3d.setListenerVelocityAuto()
		#audio3d.attachListener(camera)
		'''
		self.trans.fadeIn()
		self.spaceWorldManager = SpaceOdeWorldManager(self)
		self.spaceWorldManager.start()
		
		
	def exitSpace(self):
		#print("we exited space")
		self.trans.fadeOut()
		self.spaceWorldManager.destroy()
		del self.spaceWorldManager
		
	def enterGround(self):
		#print "we entered ground"
		self.trans.fadeIn()
		self.groundWorldManager = GroundManager(self)
		self.groundWorldManager.start()
		
		
	def exitGround(self):
		#print("we exited ground")
		self.trans.fadeOut()
		self.groundWorldManager.destroy()
		del self.groundWorldManager
예제 #11
0
class Game(State):
	mapOffset = {"up": (0,1), "down": (0,-1), "left": (-1,0), "right": (1,0)}

	def __init__(self, stage, characters, player, player2):
		State.__init__(self)

		# how to know the players that will be in game? a ChoosePlayer screen before the constructor?
		self.characters = characters

		self.player = player
		self.player2 = player2

		self.stage = stage
		self.room = self.stage.start
		self.isOver = False

		self.players = []

		#print(self.players)
		self.startMap()

		self.status = {}

		posi = 0
		for c in self.characters:
			# initialize character status string
			self.status[c] = (OnscreenText(mayChange= True ,
				                             style=2, fg=(1,1,1,1),
				                             pos=(1.4*posi - 0.8,-0.83), scale = .07)
			)
			posi += 1

		self.transitions = Transitions(GameLoader.loader)
		self.clock = ClockObject()
		self.lastTime = 0

		GameLoader.music.addSfx('barrel_breaks')
		GameLoader.music.addSfx('stone','aif')

	def spawnObject(self, ob):
		ob.setMap(self.currentMap())
		ob.getNode().reparentTo(NodePath(self.currentMap().getNode()))
		x,y = self.currentMap().posToGrid(ob.getPos())

		if ob.symbol == 'i':
			GameLoader.music.addSfx(ob.sfx)

		try:
			self.currentMap().tiles[Map.COLLISION][y][x] = ob.symbol
		except IndexError as e:
			print('Index error: ' , ob.id, e )

	def currentMap(self):
		return self.stage.maps[self.room]

	def exitMap(self):
		for i in range(self.currentMap().width):
			for j in range(self.currentMap().height):
				atype = self.currentMap().tileType(1,(i,j))
				if atype == 'block' or atype == 'liftable':
					self.currentMap().tiles[1][j][i] = ' '

		for b in self.currentMap().blocks:
			b.setPos(b.originalPos)
			x,y = self.currentMap().posToGrid(b.getPos())
			self.currentMap().tiles[Map.COLLISION][y][x] = 'b'
			b.getNode().reparentTo(NodePath(self.currentMap().getNode()))

		for b in self.currentMap().liftables:
			b.setPos(b.originalPos)
			x,y = self.currentMap().posToGrid(b.getPos())
			self.currentMap().tiles[Map.COLLISION][y][x] = 'l'
			b.getNode().reparentTo(NodePath(self.currentMap().getNode()))

		for d in self.currentMap().doors:
			if d.permanent:
				x,y = self.currentMap().posToGrid(d.getPos())
				self.currentMap().tiles[Map.COLLISION][y][x] = 'd'
				d.getNode().reparentTo(NodePath(self.currentMap().getNode()))

		for char in [self.characters[self.player], self.characters[self.player2]]:
			char.lifting = None

		NodePath(self.currentMap().getNode()).detachNode()

	def startMap(self):
		if not self.currentMap().started:
			for obstacle in self.currentMap().obstacles:
				self.spawnObject(obstacle)

			for item in self.currentMap().items:
				self.spawnObject(item)

			for block in self.currentMap().blocks:
				self.spawnObject(block)

			for liftable in self.currentMap().liftables:
				self.spawnObject(liftable)

			for switch in self.currentMap().switches:
				switch.getNode().reparentTo(NodePath(self.currentMap().getNode()))

			for door in self.currentMap().doors:
				self.spawnObject(door)

			self.currentMap().started = True

			for e in self.currentMap().enemies:
				self.spawnObject(e)

		self.characters[self.player].setMap(self.currentMap())
		self.characters[self.player2].setMap(self.currentMap())

	def changeMap(self,direction,char):

		self.transitions.fadeOut(1)
		self.transitions.fadeIn(2)

		#TODO modularize for more characters
		self.exitMap()
		self.room = self.stage.doors[self.room][direction]
		NodePath(self.currentMap().getNode()).reparentTo(self.node)

		map = self.stage.maps[self.room]
		x, y = self.currentMap().posToGrid(char.getPos())
		if   direction == "right": x = 1
		elif direction == "left":  x = map.width-2
		elif direction == "down":  y = 1
		elif direction == "up":    y = map.height-2
		pos = self.currentMap().gridToPos((x,y))

		self.characters[self.player].setPos(pos)
		self.characters[self.player2].setPos(pos)
		self.characters[self.player2].setDirection(self.characters[self.player].direction)


		self.startMap()

	def register(self, render, camera, keys, render2d):
		State.register(self, render, camera, keys, render2d)
		self.node.attachNewNode(self.stage.maps[self.room].getNode())


		for c in self.characters:
			self.status[c].reparentTo(self.node2d)

		for char in self.characters.values():
			char.getNode().reparentTo(self.node)
			char.stunRender = self.node

		for l in self.stage.getLights():
			render.setLight(l)

		# COWABUNGA test!!!
		self.hearts = {}
		numChar=0

		self.heartsNode = NodePath(PandaNode('hearts'))
		self.heartsNode.reparentTo(self.node2d)

		for char in self.characters:
			self.hearts[char] = []

			for i in range(Character.maxHearts):
				self.hearts[char].append(Sprite("heart.png", 0.05, 0.05))
				self.hearts[char][i].setPos(-0.8 + 1.4*numChar + (i%3)*0.055 , -0.9 - int(i/3)*0.055)
				self.hearts[char][i].getNode().reparentTo(self.heartsNode)

			numChar += 1

		#COWABUNGA comment this to stop the madness
		render.setAttrib(LightRampAttrib.makeSingleThreshold(0.1, 1))

		# THE TRUE CARTOON SHADER :P
#		self.separation = 1 # Pixels
		self.filters = CommonFilters(base.win, self.camera.camera)
		# cell shading
#		filterok = self.filters.setCartoonInk(separation=self.separation)
		# glow
		filterok = self.filters.setBloom(blend=(0.5,0.5,0.5,1), desat=-0.5, intensity=0.5, size="small")

		self.camera.setPos(0, -2.5, -2.5)
		self.camera.lookAt(0, 0, 0)

	def iterate(self):
		State.iterate(self)
		self.camera.look()

		self.moveObjects()
		self.doCharActions()
		self.moveChars()
		self.buryDeadPeople()

		self.activateSwitches()

		self.updateHUD()

		for c in self.characters:
			self.characters[c].tryToRecover()

		if self.isOver:
			return "GameOver"
		elif self.keys['start']:
			return "Paused"

	def updateHUD(self):

		for c in self.characters:
			self.status[c].setText(self.characters[c].getStatus())

			if self.characters[c].healthChanged:
				for heart in self.hearts[c]:
					heart.getNode().detachNode()

				for i in range(self.characters[c].hearts):
					self.hearts[c][i].getNode().reparentTo(self.heartsNode)

				self.characters[c].healthChanged = False

	def moveObjects(self):
		# BLOCK MOVEMENT ACTION
		for block in self.currentMap().blocks:
			if block.isMoving:
				block.move(block.direction)
				p1, p2 = block.getCollisionPos(block.direction)
				x1, y1 = self.currentMap().posToGrid(p1)
				x2, y2 = self.currentMap().posToGrid(p2)
				try:
					for x,y in [(x1,y1), (x2,y2)]:
						if self.stage.maps[self.room].tileType(1, (x,y)) == 'enemy':
							for enemy in self.currentMap().enemies:
								lPos = self.currentMap().posToGrid(enemy.getPos())
								if tuple(lPos) == (x,y):
									self.collision(block, enemy)
						else:
							for char in self.characters:
								if (x,y) == self.currentMap().posToGrid(self.characters[char].getPos()):
									bx,by = self.currentMap().posToGrid(block.getPos())
									self.currentMap().tiles[Map.COLLISION][by][bx] = ' '
									self.characters[char].stun()
									block.stop()
									block.getNode().detachNode()
				except IndexError:
					block.stop()

		# LIFTABLE MOVEMENT ACTION
		for liftable in self.currentMap().liftables:
			if liftable.isMoving:
				liftable.move(liftable.direction)
				p1, p2 = liftable.getCollisionPos(liftable.direction)
				x1, y1 = self.currentMap().posToGrid(p1)
				x2, y2 = self.currentMap().posToGrid(p2)
				try:
					for x,y in [(x1,y1), (x2,y2)]:
						if self.stage.maps[self.room].tileType(1, (x,y)) == 'enemy':
							for enemy in self.currentMap().enemies:
								lPos = self.currentMap().posToGrid(enemy.getPos())
								if tuple(lPos) == (x,y):
									self.collision(liftable, enemy)
						elif self.stage.maps[self.room].tileType(1, (x,y)) != 'free':
							liftable.stop()
							liftable.getNode().detachNode()
						else:
							for char in self.characters:
								if (x,y) == self.currentMap().posToGrid(self.characters[char].getPos()):
									print "Stun nele!"
									self.characters[char].stun()
									liftable.stop()
									liftable.getNode().detachNode()
				except IndexError:
					# to do, create a liftable.destroy(), which animates the liftable and do these two actions:
					liftable.stop()
					liftable.getNode().detachNode()

	def doCharActions(self):
		for char in [self.characters[self.player], self.characters[self.player2]]:
			add = "1"
			if char == self.characters[self.player]:
				add = ""

			if self.keys['attack'+add]:
				self.keys['attack'+add] = False
				print('Using %s' % (char.currentItem()) )
				p1, p2 = char.getCollisionPos(char.direction)
				x1, y1 = self.currentMap().posToGrid(p1)
				x2, y2 = self.currentMap().posToGrid(p2)

				for x,y in [(x1,y1), (x2,y2)]:
					if self.stage.maps[self.room].tileType(Map.COLLISION, (x,y)) == 'door':
						for d in self.currentMap().doors:
							if tuple(self.currentMap().posToGrid(d.getPos())) == (x,y):
								opened = d.open(char.currentItem())
								if opened:
									self.currentMap().tiles[Map.COLLISION][y][x] = ' '
									char.destroyCurrentItem()

			if self.keys['cancel'+add]:
				self.keys['cancel'+add] = False
				print('Changing slot')
				char.changeSlot()

			if self.keys['action'+add]:
				self.keys['action'+add] = False
				if char.lifting:
					char.lifting.setHeight(0)
					char.lifting.move(char.direction)
					char.lifting = None
				else:
					p1, p2 = char.getCollisionPos(char.direction)
					x1, y1 = self.currentMap().posToGrid(p1)
					x2, y2 = self.currentMap().posToGrid(p2)

					for x,y in [(x1,y1), (x2,y2)]:
						if self.stage.maps[self.room].tileType(Map.COLLISION, (x,y)) == 'block':
							for block in self.currentMap().blocks:
								if tuple(self.currentMap().posToGrid(block.getPos())) == (x,y):
									GameLoader.music.playSfx('stone')
									block.move(char.direction)
						elif self.stage.maps[self.room].tileType(Map.COLLISION, (x,y)) == 'item':
							for item in self.currentMap().items:
								if tuple(self.currentMap().posToGrid(item.getPos())) == (x,y):
									self.collision(char, item)
						elif self.currentMap().tileType(Map.COLLISION, (x,y)) == 'liftable':
							for liftable in self.currentMap().liftables:
								lPos = self.currentMap().posToGrid(liftable.getPos())
								if tuple(lPos) == (x,y):
									char.pick(liftable)
									self.currentMap().tiles[1][y][x] = ' '

	def moveChars(self):
		for char in [self.characters[self.player], self.characters[self.player2]]:
			add = "1"
			if char == self.characters[self.player]:
				add = ""

			directions = [key for key in ["up","down","left","right"] if self.keys[key+add]]

			if len(directions) == 0:
				char.stop()

			for dir in directions:
				#TODO to be re-refactored
				p1, p2 = char.getCollisionPos(dir)

				if self.currentMap().futPosAreFree(p1, p2):
					char.move(dir)
					if char.lifting:
						char.lifting.setPos(char.getPos())

					ex = self.stage.maps[self.room].getExit(self.currentMap().posToGrid(p1))

					if ex and (ex in self.stage.doors[self.room].keys()):
						self.changeMap(ex,char)
				else:
					char.setDirection(dir)

			for enemy in self.currentMap().enemies:
				#TODO actually enemies are still present in the map
				x,y = self.currentMap().posToGrid(enemy.getPos())
				self.currentMap().tiles[Map.COLLISION][y][x] = ' '

				# COWABUNGA
				# se botarmos aqui uma funcao que define como o inimigo anda
				# vai dar tudo certo
				# por exemplo ele pode as vezes andar em direcao a um heroi e
				# as vezes ser random
				# por enquanto e so random
				# - OK, agreed
				dir = ['up','down','left','right'][random.randint(0,3)]
				p1, p2 = enemy.getCollisionPos(dir)

				if self.currentMap().futPosAreFree(p1, p2):
					enemy.enemy_move(dir)
				else:
					enemy.setDirection(dir)

				x,y = self.currentMap().posToGrid(enemy.getPos())
				self.currentMap().tiles[Map.COLLISION][y][x] = 'e'

			p1, p2 = char.getCollisionPos(char.direction)
			x1, y1 = self.currentMap().posToGrid(p1)
			x2, y2 = self.currentMap().posToGrid(p2)
			for x,y in [(x1,y1), (x2,y2)]:
				collisionTiles = ["enemy"]
				collisionElements = {"enemy": self.currentMap().enemies}

				for t in collisionTiles:
					if self.stage.maps[self.room].tileType(Map.COLLISION, (x,y)) == t:
						for e in collisionElements[t]:
							lPos = self.currentMap().posToGrid(e.getPos())
							if tuple(lPos) == (x,y):
								self.collision(char, e)

	def activateSwitches(self):
		mp = self.currentMap()
		for s in mp.switches:
			x,y = mp.posToGrid(s.getPos())
			charPos = [self.currentMap().posToGrid(self.characters[char].getPos()) for char in self.characters]
			if mp.tiles[Map.COLLISION][y][x] != ' ' or ((x,y) in charPos):
				#print 'activated!'
				mp.tiles[Map.GROUND][y][x] = 'S'
				s.activate()
			else:
				#print 'deactivated!'
				mp.tiles[Map.GROUND][y][x] = 's'
				s.deactivate()

		for d in mp.doors:
			openDoor = True
			if d.openWith == "switches":
				for ds in d.switches:
					for ms in mp.switches:
						if (ds == ms.name) and (not ms.active):
							openDoor = False
							break
				if openDoor:
					d.open("switches")
					x,y = mp.posToGrid(d.getPos())
					mp.tiles[Map.COLLISION][y][x] = ' '

	def collision(self, a, b):
		print "Collision: TYPE A:", a.getType(), "TYPE B:", b.getType()

		if b.getType() == 'item':
			for i in range(len(self.currentMap().items)):
				if i < len(self.currentMap().items): #we need this because the size of the list may change if we remove an item
					if tuple(self.currentMap().items[i].getPos()) == tuple(b.getPos()):
						# removes the item
						self.currentMap().items.pop(i)

						x, y = self.currentMap().posToGrid((NodePath(b.getNode()).getX(), NodePath(b.getNode()).getZ()))

						# it's not drawed anymore
						self.currentMap().tiles[Map.COLLISION][y][x] = ' '
						NodePath(b.getNode()).detachNode()

						#it's picked
						oldItem = a.pickItem(b)
						if oldItem != None:
							print oldItem.name
							oldItem.setPos(self.currentMap().gridToPos((x,y)))
							oldItem.originalPos = oldItem.getPos()
							self.spawnObject(oldItem)
							self.currentMap().items.append(oldItem)

		if a.getType() == 'liftable' or b.getType() == 'liftable':
			GameLoader.music.playSfx('barrel_breaks')

		if a.getType() == 'liftable' and b.getType() == 'enemy':
			a.stop()
			a.getNode().detachNode()
			x,y = self.currentMap().posToGrid(a.getPos()) #nao precisaria
			self.currentMap().tiles[Map.COLLISION][y][x] = ' '
			b.takeDamage(10000)

			if not b.isAlive():
				x, y = self.currentMap().posToGrid(b.getPos())
				self.currentMap().tiles[Map.COLLISION][y][x] = ' '
				NodePath(b.getNode()).removeNode()
				self.currentMap().enemies.remove(b)

		if a.getType() == 'block' and b.getType() == 'enemy':
			a.stop()
			a.getNode().detachNode()
			x,y = self.currentMap().posToGrid(a.getPos())
			self.currentMap().tiles[Map.COLLISION][y][x] = ' '
			b.takeDamage(10000)

			if not b.isAlive():
				x, y = self.currentMap().posToGrid(b.getPos())
				self.currentMap().tiles[Map.COLLISION][y][x] = ' '
				NodePath(b.getNode()).removeNode()
				self.currentMap().enemies.remove(b)

		if a.getType() == 'Character':
			print("Character collided with", b.getType())
			if b.getType() == 'enemy':
				a.takeDamage(1)

	def buryDeadPeople(self):
		# commented while fixing the bugs
		for enemy in self.currentMap().enemies:
			if not enemy.isAlive():
				x, y = self.currentMap().posToGrid(enemy.getPos())
				self.currentMap().tiles[Map.COLLISION][y][x] = ' '
				NodePath(enemy.getNode()).removeNode()
				self.currentMap().enemies.remove(enemy)

		#if not self.player.isAlive() : #tratar isso corretamente!
		for char in self.characters:
			if not self.characters[char].isAlive():
				self.isOver = True


	def enter(self):
		State.enter(self)
		self.stage.playMusic()

	def exit(self):

#		self.transitions.fadeOut(2)
#		self.transitions.fadeIn(3)
#		self.transitions.noFade()

		self.stage.stopMusic()
#		self.heartsNode.removeNode()
#		for c in self.characters:
#			NodePath(self.characters[c].getNode()).removeNode()
#			self.status[c].removeNode()

#		NodePath(self.currentMap().getNode()).removeNode()
		State.exit(self)
예제 #12
0
class MakeAToon:
    def __init__(self):
        self.notify = DirectNotifyGlobal.directNotify.newCategory(
            "Starting Make A Toon.")
        self.localAvatar = LocalAvatar.toonBody
        base.localAvatar = self.localAvatar
        self.toonColors = Localizer.toonColorDict
        self.colorNum = 0
        self.numColors = Localizer.numColors
        self.MakeAToonText = Localizer.MakeAToonText
        self.Mickey = Localizer.Mickey
        self.mickeyFont = loader.loadFont(
            'phase_3/models/fonts/MickeyFont.bam')
        self.Text = OnscreenText(text="Make A Toon",
                                 pos=(0, 0.75),
                                 font=self.mickeyFont,
                                 fg=(1, 0, 0, 1),
                                 scale=(0.2, 0.2, 0.2))
        self.gui = loader.loadModel(
            'phase_3/models/gui/tt_m_gui_mat_mainGui.bam')
        self.gui.flattenMedium()
        self.gui1 = loader.loadModel(
            'phase_3/models/gui/create_a_toon_gui.bam')
        self.gui2 = loader.loadModel('phase_3/models/gui/gui_toongen.bam')
        self.guiNextUp = self.gui.find('**/tt_t_gui_mat_nextUp')
        self.transition = Transitions(loader)
        self.transition.irisIn(1)
        self.transition.fadeIn(5)
        self.load()

    def load(self):
        self.Music = loader.loadMusic('phase_3/audio/bgm/create_a_toon.mid')
        self.Music.setLoop(1)
        self.MusicVolume = (0.4)
        self.Music.play()
        self.Music.setVolume(self.MusicVolume)
        base.localAvatar.setPos(0.80, 2, 0)
        base.localAvatar.setHpr(176, 0, 0)
        LocalAvatar.setMovementAnimation('neutral')
        self.room = loader.loadModel('phase_3/models/gui/create_a_toon.bam')
        self.room.reparentTo(render)
        self.room.find('**/sewing_machine').removeNode()
        self.room.find('**/drafting_table').removeNode()
        self.room.find("**/wall_floor").setColor(0.7294117647058824,
                                                 0.5490196078431373,
                                                 0.2392156862745098, 1)
        self.room.setName("Room")
        self.ee = DirectFrame(pos=(-1, 1, 1),
                              frameSize=(-.01, 0.01, -.01, 0.01),
                              frameColor=(0, 0, 0, 0.05),
                              state='normal')
        self.ee.bind(DGG.B1PRESS, lambda x, ee=self.ee: self.toggleSlide())
        self.eee = self.ee
        self.toonSpin = base.localAvatar.hprInterval(2, Vec3(540, 0, 0))
        self.toonSpin2 = base.localAvatar.hprInterval(2, Vec3(180, 0, 0))
        self.CameraMove = camera.posInterval(1,
                                             Point3(-0.50, -11, 3),
                                             startPos=Point3(1, -11, 3))
        self.CameraMoveSequence = Sequence(self.CameraMove)
        self.ToonEnter = base.localAvatar.posInterval(1,
                                                      Point3(0.60, 2, 0),
                                                      startPos=Point3(
                                                          -4, 2, 0))
        self.ToonEnterPace = Sequence(self.ToonEnter)
        self.ToonEnter.start()
        self.oobeButton = DirectButton(
            clickSound=Globals.getClickSound(),
            rolloverSound=Globals.getRlvrSound(),
            geom=(self.gui1.find("**/CrtATn_R_Arrow_UP"),
                  self.gui1.find("**/CrtATn_R_Arrow_DN"),
                  self.gui1.find("**/CrtATn_R_Arrow_RLVR")),
            relief=None,
            hpr=(0, 0, 180),
            command=self.goBack)
        self.oobeButton.setScale(1)
        self.oobeButton.setPos(-0.70, 3, -0.25)
        self.goBackButton = DirectButton(
            clickSound=Globals.getClickSound(),
            rolloverSound=Globals.getRlvrSound(),
            geom=(self.gui1.find("**/CrtATn_R_Arrow_UP"),
                  self.gui1.find("**/CrtATn_R_Arrow_DN"),
                  self.gui1.find("**/CrtATn_R_Arrow_RLVR")),
            relief=None,
            command=self.goRight)
        self.goBackButton.setScale(1)
        self.goBackButton.setPos(0.80, 3, -0.25)
        self.spinButton = DirectButton(
            clickSound=Globals.getClickSound(),
            rolloverSound=Globals.getRlvrSound(),
            geom=(self.gui1.find("**/CrtATn_R_Arrow_UP"),
                  self.gui1.find("**/CrtATn_R_Arrow_DN"),
                  self.gui1.find("**/CrtATn_R_Arrow_RLVR")),
            relief=None,
            command=self.HprToon)
        self.spinButton.setScale(0.60)
        self.spinButton.setPos(0.50, 2, -0.50)
        self.spinButton2 = DirectButton(
            clickSound=Globals.getClickSound(),
            rolloverSound=Globals.getRlvrSound(),
            geom=(self.gui1.find("**/CrtATn_R_Arrow_UP"),
                  self.gui1.find("**/CrtATn_R_Arrow_DN"),
                  self.gui1.find("**/CrtATn_R_Arrow_RLVR")),
            relief=None,
            hpr=(0, 0, 180),
            command=self.HprToon2)
        self.spinButton2.setScale(0.60)
        self.spinButton2.setPos(-0.40, 2, -0.50)
        self.OK = DirectButton(clickSound=Globals.getClickSound(),
                               rolloverSound=Globals.getRlvrSound(),
                               geom=(self.gui2.find("**/tt_t_gui_mat_okUp"),
                                     self.gui2.find("**/tt_t_gui_mat_okDown")),
                               pos=(0.90, 1, -0.80),
                               relief=None,
                               command=self.CameraButton)

    def goRight(self):
        for color in self.toonColors[self.colorNum]:
            LocalAvatar.bodyNodes[color].setColor(
                self.toonColors[self.colorNum][color])
        self.colorNum += 1
        if self.colorNum > self.numColors:
            self.colorNum = 0

    def goBack(self):
        for color in self.toonColors[self.colorNum]:
            LocalAvatar.bodyNodes[color].setColor(
                self.toonColors[self.colorNum][color])
        self.colorNum -= 1
        if self.colorNum < 0:
            self.colorNum = self.numColors

    def HprToon(self):
        self.toonSpin.start()

    def HprToon2(self):
        self.toonSpin2.start()

    def CameraButton(self):
        self.transition.irisIn()
        self.transition.fadeOut(1)
        self.Music.stop()