Пример #1
0
class GUI:
    def __init__(self, rootParent=None):

        self.btnEndTurn = DirectButton(
            borderWidth=(0.0, 0.0),
            frameColor=(0.8, 0.8, 0.8, 0.0),
            frameSize=(-3.0, 3.0, -1.0, 1.0),
            hpr=LVecBase3f(0, 0, 0),
            image='./assets/Turn/EndTurn.png',
            pos=LPoint3f(0, 0, 0.1),
            relief=1,
            scale=LVecBase3f(0.1, 0.1, 0.1),
            text='End Turn',
            image_scale=LVecBase3f(3, 0, 1),
            image_pos=LPoint3f(0, 0, 0),
            text_align=TextNode.A_center,
            text_scale=(1.0, 1.0),
            text_pos=(0.0, -0.3),
            text_fg=LVecBase4f(1, 1, 1, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            parent=rootParent,
            command=base.messenger.send,
            extraArgs=["endTurn"],
            pressEffect=0,
        )
        self.btnEndTurn.setTransparency(1)

    def show(self):
        self.btnEndTurn.show()

    def hide(self):
        self.btnEndTurn.hide()

    def destroy(self):
        self.btnEndTurn.destroy()
Пример #2
0
class GUI:
    def __init__(self, rootParent=None):

        self.btnRollDice = DirectButton(
            frameColor=(0.8, 0.8, 0.8, 0.0),
            frameSize=(-0.25, 0.25, -0.25, 0.25),
            hpr=LVecBase3f(0, 0, 0),
            image='./assets/Dice/DiceButton.png',
            pos=LPoint3f(0.25, 0, 0.25),
            relief=1,
            scale=LVecBase3f(1, 1, 1),
            text='',
            image_scale=LVecBase3f(0.25, 0.25, 0.25),
            image_pos=LPoint3f(0, 0, 0),
            text_align=TextNode.A_center,
            text_scale=(0.15, 0.15),
            text_pos=(-0.08, -0.09),
            text_fg=LVecBase4f(1, 1, 1, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            parent=rootParent,
            command=base.messenger.send,
            extraArgs=["rollDice"],
            pressEffect=0,
        )
        self.btnRollDice.setTransparency(1)

    def show(self):
        self.btnRollDice.show()

    def hide(self):
        self.btnRollDice.hide()

    def destroy(self):
        self.btnRollDice.destroy()
Пример #3
0
class Main(ShowBase):
    def __init__(self):
        """ Initialization of the connect 4"""
        print('General > Initialization')
        super().__init__()

        # General settings
        # self.disable_mouse()

        # Load the background
        self.background = OnscreenImage(parent=self.render2dp,
                                        image="tex/bedroom.jpg")
        self.cam2dp.node().getDisplayRegion(0).setSort(-20)

        # Load the avatar
        self.arm = Actor("models/Tatsumi_models/Tatsumi_1",
                         {"anim1": "models/Tatsumi_models/Tatsumi_1_anim"})
        self.arm.setPos(0, 50, -36)
        self.arm.setScale(20, 20, 20)
        self.arm.reparentTo(self.render)
        self.arm.setPlayRate(4, "anim1")
        self.arm.play("anim1")

        # Load the buttons
        self.icon_connect4 = DirectButton(image="img/connect4.png",
                                          pos=(-1.5, 0, -0.8),
                                          scale=(0.2, 0.2, 0.2),
                                          relief=None,
                                          command=self.run_connect4)
        self.icon_connect4.setTransparency(TransparencyAttrib.MAlpha)

        self.games = []

    def run_connect4(self):
        """ Function that initializers the connect4 game """
        print("General > Run the Connect 4")
        self.hide_elements()
        connect4 = Connect4(self)
        self.games.append(connect4)
        self.taskMgr.add(self.loop, "loop")

    def show_elements(self):
        """ Function that shows the elements of the initial display """
        self.games = []
        self.icon_connect4.show()

    def hide_elements(self):
        """ Function that hides the elements of the initial display """
        self.icon_connect4.hide()

    def loop(self, task):
        """ Function that runs the connect4 game """
        if self.games[0].mainloop() == 0:
            self.show_elements()
            return task.done
        else:
            return task.cont
Пример #4
0
class TeamActivityGui:
    COUNTDOWN_TASK_NAME = "updateCountdownTask"

    timer = None
    statusText = None
    countdownText = None
    exitButton = None
    switchButton = None

    def __init__(self, activity):
        self.activity = activity  # instance of the DistributedPartyTeamActivity

    def load(self):
        buttonModels = loader.loadModel("phase_3.5/models/gui/inventory_gui")
        upButton = buttonModels.find("**//InventoryButtonUp")
        downButton = buttonModels.find("**/InventoryButtonDown")
        rolloverButton = buttonModels.find("**/InventoryButtonRollover")

        self.exitButton = DirectButton(
            relief=None,
            text=TTLocalizer.PartyTeamActivityExitButton,
            text_fg=(1, 1, 0.65, 1),
            text_pos=(0, -0.15),
            text_scale=0.50,
            image=(upButton, downButton, rolloverButton),
            image_color=(1, 0, 0, 1),
            image_scale=(14.5, 1, 9),
            pos=(0, 0, 0.8),
            scale=0.15,
            command=self.handleExitButtonClick,
        )
        self.exitButton.hide()

        if self.activity.toonsCanSwitchTeams():
            self.switchButton = DirectButton(
                relief=None,
                text=TTLocalizer.PartyTeamActivitySwitchTeamsButton,
                text_fg=(1, 1, 1, 1),
                text_pos=(0, 0.1),
                text_scale=0.50,
                image=(upButton, downButton, rolloverButton),
                image_color=(0, 1, 0, 1),
                image_scale=(15, 1, 15),
                pos=(0, 0, 0.5),
                scale=0.15,
                command=self.handleSwitchButtonClick,
            )
            self.switchButton.hide()
        else:
            self.switchButton = None

        buttonModels.removeNode()

        self.countdownText = OnscreenText(
            text="",
            pos=(0.0, -0.2),
            scale=PartyGlobals.TeamActivityTextScale * 1.2,
            fg=(1.0, 1.0, 0.65, 1.0),
            align=TextNode.ACenter,
            font=ToontownGlobals.getSignFont(),
            mayChange=True,
        )
        self.countdownText.hide()

        # load general purpose text display element
        self.statusText = OnscreenText(
            text="",
            pos=(0.0, 0.0),
            scale=PartyGlobals.TeamActivityTextScale,
            fg=PartyGlobals.TeamActivityStatusColor,
            align=TextNode.ACenter,
            font=ToontownGlobals.getSignFont(),
            mayChange=True,
        )
        self.statusText.hide()

        # load the timer that displays time left in the game
        self.timer = PartyUtils.getNewToontownTimer()
        self.timer.hide()

    def unload(self):
        self.hideWaitToStartCountdown()

        if self.exitButton is not None:
            self.exitButton.destroy()
            self.exitButton = None

        if self.switchButton is not None:
            self.switchButton.destroy()
            self.switchButton = None

        if self.countdownText is not None:
            self.countdownText.destroy()
            self.countdownText.removeNode()
            self.countdownText = None

        if self.statusText is not None:
            self.statusText.destroy()
            self.statusText.removeNode()
            self.statusText = None

        if self.timer is not None:
            self.timer.destroy()
            del self.timer

#===============================================================================
# Status
#===============================================================================

    def showStatus(self, text):
        self.statusText.setText(text)
        self.statusText.show()

    def hideStatus(self):
        self.statusText.hide()

#===============================================================================
# Exit
#===============================================================================

    def enableExitButton(self):
        self.exitButton.show()

    def disableExitButton(self):
        assert (self.activity.notify.debug("GUI: disableExitButton"))

        self.exitButton.hide()

    def handleExitButtonClick(self):
        self.disableExitButton()
        self.disableSwitchButton()
        self.activity.d_toonExitRequest()

#===============================================================================
# Switch Teams button
#===============================================================================

    def enableSwitchButton(self):
        self.switchButton.show()

    def disableSwitchButton(self):
        assert (self.activity.notify.debug("GUI: disableSwitchButton"))

        if self.switchButton is not None:
            self.switchButton.hide()

    def handleSwitchButtonClick(self):
        self.disableSwitchButton()
        self.disableExitButton()
        self.activity.d_toonSwitchTeamRequest()

#===============================================================================
# Wait To Start Countdown
#===============================================================================

    def showWaitToStartCountdown(self,
                                 duration,
                                 waitToStartTimestamp,
                                 almostDoneCallback=None):
        self._countdownAlmostDoneCallback = almostDoneCallback

        currentTime = globalClock.getRealTime()
        waitTimeElapsed = currentTime - waitToStartTimestamp

        # if still time left to display countdown
        if (duration - waitTimeElapsed) > 1.0:
            countdownTask = Task(self._updateCountdownTask)
            countdownTask.duration = duration - waitTimeElapsed

            self.countdownText.setText(str(int(countdownTask.duration)))
            self.countdownText.show()

            taskMgr.remove(TeamActivityGui.COUNTDOWN_TASK_NAME)
            taskMgr.add(countdownTask, TeamActivityGui.COUNTDOWN_TASK_NAME)

        else:
            # don't bother showing timer at all
            assert (self.activity.notify.debug(
                "GUI: Server entered WaitToStart %.1f seconds ago. No point in displaying on screen countdown."
                % waitTimeElapsed))

    def hideWaitToStartCountdown(self):
        assert (self.activity.notify.debug("finishWaitToStart"))
        # it is possible that self.isLocalToonPlaying will be False at this
        # point even though we had the localToon in the activity, so clean up as
        # if the local toon was in.
        taskMgr.remove(TeamActivityGui.COUNTDOWN_TASK_NAME)
        self._countdownAlmostDoneCallback = None

        if self.countdownText is not None:
            self.countdownText.hide()

    def _updateCountdownTask(self, task):
        countdownTime = int(task.duration - task.time)

        seconds = str(countdownTime)

        if self.countdownText["text"] != seconds:
            assert (self.activity.notify.debug(
                "GUI: Setting countdown label to %s" % seconds))
            self.countdownText["text"] = seconds

            if countdownTime == 3 and self._countdownAlmostDoneCallback is not None:
                self._countdownAlmostDoneCallback()
                self._countdownAlmostDoneCallback = None

        if task.time >= task.duration:
            return Task.done
        else:
            return Task.cont

#===============================================================================
# Timer
#===============================================================================

    def showTimer(self, duration):
        self.timer.setTime(duration)
        self.timer.countdown(duration, self._handleTimerExpired)
        self.timer.show()

    def hideTimer(self):
        self.timer.hide()
        self.timer.stop()

    def _handleTimerExpired(self):
        assert (self.activity.notify.debug("Timer Expired!"))
        self.activity.handleGameTimerExpired()
Пример #5
0
class GUI:
    def __init__(self, rootParent=None):
        
        self.frmInventory = DirectFrame(
            frameColor=(0.2, 0.2, 0.2, 1.0),
            frameSize=(-0.3, 0.3, -0.5, 0.5),
            hpr=LVecBase3f(0, 0, 0),
            pos=LPoint3f(0.725, 0, 0.2),
            parent=rootParent,
        )
        self.frmInventory.setTransparency(0)

        self.frmContent = DirectScrolledFrame(
            canvasSize=(-0.8, 0.8, -0.8, 0.8),
            frameColor=(0.2, 0.2, 0.2, 1.0),
            frameSize=(-0.8, 0.8, -0.8, 0.8),
            hpr=LVecBase3f(0, 0, 0),
            pos=LPoint3f(-0.475, 0, 0.1),
            scrollBarWidth=0.08,
            state='normal',
            horizontalScroll_borderWidth=(0.01, 0.01),
            horizontalScroll_frameSize=(-0.05, 0.05, -0.04, 0.04),
            horizontalScroll_hpr=LVecBase3f(0, 0, 0),
            horizontalScroll_pos=LPoint3f(0, 0, 0),
            horizontalScroll_decButton_borderWidth=(0.01, 0.01),
            horizontalScroll_decButton_frameSize=(-0.05, 0.05, -0.04, 0.04),
            horizontalScroll_decButton_hpr=LVecBase3f(0, 0, 0),
            horizontalScroll_decButton_pos=LPoint3f(0, 0, 0),
            horizontalScroll_incButton_borderWidth=(0.01, 0.01),
            horizontalScroll_incButton_frameSize=(-0.05, 0.05, -0.04, 0.04),
            horizontalScroll_incButton_hpr=LVecBase3f(0, 0, 0),
            horizontalScroll_incButton_pos=LPoint3f(0, 0, 0),
            horizontalScroll_thumb_borderWidth=(0.01, 0.01),
            horizontalScroll_thumb_hpr=LVecBase3f(0, 0, 0),
            horizontalScroll_thumb_pos=LPoint3f(0, 0, 0),
            verticalScroll_borderWidth=(0.01, 0.01),
            verticalScroll_frameSize=(-0.04, 0.04, -0.05, 0.05),
            verticalScroll_hpr=LVecBase3f(0, 0, 0),
            verticalScroll_pos=LPoint3f(0, 0, 0),
            verticalScroll_decButton_borderWidth=(0.01, 0.01),
            verticalScroll_decButton_frameSize=(-0.04, 0.04, -0.05, 0.05),
            verticalScroll_decButton_hpr=LVecBase3f(0, 0, 0),
            verticalScroll_decButton_pos=LPoint3f(0, 0, 0),
            verticalScroll_incButton_borderWidth=(0.01, 0.01),
            verticalScroll_incButton_frameSize=(-0.04, 0.04, -0.05, 0.05),
            verticalScroll_incButton_hpr=LVecBase3f(0, 0, 0),
            verticalScroll_incButton_pos=LPoint3f(0, 0, 0),
            verticalScroll_thumb_borderWidth=(0.01, 0.01),
            verticalScroll_thumb_hpr=LVecBase3f(0, 0, 0),
            verticalScroll_thumb_pos=LPoint3f(0, 0, 0),
            parent=rootParent,
        )
        self.frmContent.setTransparency(1)

        self.btnQuit = DirectButton(
            frameSize=(-3.0, 3.0, -0.3, 0.9),
            hpr=LVecBase3f(0, 0, 0),
            pos=LPoint3f(0.725, 0, -0.85),
            scale=LVecBase3f(0.1, 0.1, 0.1),
            text='Quit',
            text_align=TextNode.A_center,
            text_scale=(1, 1),
            text_pos=(0, 0),
            text_fg=LVecBase4f(0, 0, 0, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            text_wordwrap=None,
            parent=rootParent,
            command=base.messenger.send,
            extraArgs=["quitGame"],
            pressEffect=1,
        )
        self.btnQuit.setTransparency(0)

        self.btnAudioToggle = DirectButton(
            frameSize=(-3.0, 3.0, -0.3, 0.9),
            hpr=LVecBase3f(0, 0, 0),
            pos=LPoint3f(0.725, 0, -0.7),
            scale=LVecBase3f(0.1, 0.1, 0.1),
            text='Audio On',
            text_align=TextNode.A_center,
            text_scale=(1, 1),
            text_pos=(0, 0),
            text_fg=LVecBase4f(0, 0, 0, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            text_wordwrap=None,
            parent=rootParent,
            command=base.messenger.send,
            extraArgs=["toggleAudio"],
            pressEffect=1,
        )
        self.btnAudioToggle.setTransparency(0)

        self.frmBorderOverlay = DirectFrame(
            frameColor=(1.0, 1.0, 1.0, 0.0),
            frameSize=(-0.8, 0.8, -0.8, 0.8),
            hpr=LVecBase3f(0, 0, 0),
            image='gameScreen/border.png',
            pos=LPoint3f(-0.475, 0, 0.1),
            image_scale=LVecBase3f(0.8, 1, 0.8),
            image_pos=LPoint3f(0, 0, 0),
            parent=rootParent,
        )
        self.frmBorderOverlay.setTransparency(1)

        self.lblInventory = DirectLabel(
            frameColor=(0.8, 0.8, 0.8, 0.0),
            hpr=LVecBase3f(0, 0, 0),
            pos=LPoint3f(0.725, 0, 0.775),
            scale=LVecBase3f(0.1, 0.1, 0.1),
            text='Inventory',
            text_align=TextNode.A_center,
            text_scale=(1, 1),
            text_pos=(0, 0),
            text_fg=LVecBase4f(0.9, 0.9, 0.9, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            text_wordwrap=None,
            parent=rootParent,
        )
        self.lblInventory.setTransparency(0)

        self.lblStory = DirectLabel(
            frameSize=(-0.125, 12.0, -0.313, 0.925),
            hpr=LVecBase3f(0, 0, 0),
            pad=(0.2, 0.2),
            pos=LPoint3f(-1.26, 0, -0.845),
            scale=LVecBase3f(0.1, 0.1, 0.1),
            text='',
            text_align=TextNode.A_left,
            text_scale=(0.4, 0.4),
            text_pos=(0.0, 0.4),
            text_fg=LVecBase4f(0, 0, 0, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            text_wordwrap=29.8,
            parent=rootParent,
        )
        self.lblStory.setTransparency(0)

        self.btnContinue = DirectButton(
            frameSize=(-1.8, 1.8, -0.3, 0.9),
            hpr=LVecBase3f(0, 0, 0),
            pos=LPoint3f(0.145, 0, -0.845),
            scale=LVecBase3f(0.1, 0.1, 0.1),
            text='Cont.',
            text_align=TextNode.A_center,
            text_scale=(1, 1),
            text_pos=(0, 0),
            text_fg=LVecBase4f(0, 0, 0, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            text_wordwrap=None,
            parent=rootParent,
            command=base.messenger.send,
            extraArgs=["story_continue"],
            pressEffect=1,
        )
        self.btnContinue.setTransparency(0)

        self.frmFadeOverlay = DirectFrame(
            frameColor=(0.0, 0.0, 0.0, 1.0),
            frameSize=(-0.8, 0.8, -0.8, 0.8),
            hpr=LVecBase3f(0, 0, 0),
            pos=LPoint3f(-0.475, 0, 0.1),
            parent=rootParent,
        )
        self.frmFadeOverlay.setTransparency(1)


    def show(self):
        self.frmInventory.show()
        self.frmContent.show()
        self.btnQuit.show()
        self.btnAudioToggle.show()
        self.frmBorderOverlay.show()
        self.lblInventory.show()
        self.lblStory.show()
        self.btnContinue.show()
        self.frmFadeOverlay.show()

    def hide(self):
        self.frmInventory.hide()
        self.frmContent.hide()
        self.btnQuit.hide()
        self.btnAudioToggle.hide()
        self.frmBorderOverlay.hide()
        self.lblInventory.hide()
        self.lblStory.hide()
        self.btnContinue.hide()
        self.frmFadeOverlay.hide()

    def destroy(self):
        self.frmInventory.destroy()
        self.frmContent.destroy()
        self.btnQuit.destroy()
        self.btnAudioToggle.destroy()
        self.frmBorderOverlay.destroy()
        self.lblInventory.destroy()
        self.lblStory.destroy()
        self.btnContinue.destroy()
        self.frmFadeOverlay.destroy()
Пример #6
0
class App(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        self.prop = WindowProperties()
        self.prop.setSize(1920, 1080)
        self.prop.setMinimized(False)
        self.win.requestProperties(self.prop)
        self.path = os.path.abspath(sys.path[0])
        self.path = Filename.fromOsSpecific(self.path).getFullpath()
        self.fram = DirectFrame(frameColor=(0, 0, 0, 1),
                                frameSize=(-1, 1, -1, 1),
                                pos=(0, 0, 0),
                                image=self.path + "/start.png")
        self.fram.reparentTo(self.render2d)
        self.easyAI = DirectButton(text="Easy AI",
                                   command=self.easyPlay,
                                   pos=(0, 0, 0),
                                   scale=0.1,
                                   text_bg=(0, 0, 0, 1),
                                   text_fg=(255, 255, 255, 1))
        self.hardAI = DirectButton(text="Hard AI",
                                   command=self.hardPlay,
                                   pos=(0, 0, -0.2),
                                   scale=0.1,
                                   text_bg=(0, 0, 0, 1),
                                   text_fg=(255, 255, 255, 1))
        self.help = DirectButton(text="Help",
                                 command=self.helpScreen,
                                 pos=(0, 0, -0.4),
                                 scale=0.1,
                                 text_bg=(0, 0, 0, 1),
                                 text_fg=(255, 255, 255, 1))

    def easyPlay(self):
        self.play(True)

    def hardPlay(self):
        self.play(True, True)

    def helpScreen(self):
        self.easyAI.hide()
        self.hardAI.hide()
        self.help.hide()
        self.fram["image"] = self.path + "/help.jpg"
        self.fram.updateFrameStyle()
        self.back = DirectButton(text="",
                                 command=self.helpScreen,
                                 pos=(0, 0, -0.4),
                                 scale=0.1,
                                 text_bg=(0, 0, 0, 1),
                                 text_fg=(255, 255, 255, 1))


    def back(self):
        self.hardAI.show()
        self.easyAI.show()
        self.help.show()
        self.back.destroy()
        self.fram["image"] = self.path + "/start.png"

    def play(self, ai, difficult=False):
        self.easyAI.destroy()
        self.hardAI.destroy()
        self.ai = None
        self.cTrav = CollisionTraverser()
        self.coll = CollisionHandlerEvent()
        self.coll.addInPattern("%fn-into-%in")
        self.clock = ClockObject()
        terrain = GeoMipTerrain("worldTerrain")
        terrain.setHeightfield("heightMap.png")
        terrain.setColorMap("colormap.png")
        terrain.setBruteforce(True)
        root = terrain.getRoot()
        root.reparentTo(self.render)
        root.setSz(1)
        terrain.generate()
        self.player = Character("models/panda-model", 0.05, (300, 300, 0),
                                self.render, {"walk": "models/panda-walk4"},
                                self, self.path, 200, "player")
        self.addControls()
        self.loadUI()
        self.startTasks()
        self.accept("proj-into-player", self.player.changeLife, [-1])
        self.others = dict()
        self.roundOv = False
        self.taskMgr.add(self.update, "Update")
        self.gameOver = False
        if ai:
            self.aiBattle(difficult)

    def startTasks(self):
        self.taskMgr.add(self.camra, "Cam")
        self.taskMgr.add(self.manageCollisions, "colls")

    def loadUI(self):
        self.lifeBar = DirectWaitBar(text="", value=self.player.life,
                                     barColor=(0, 1, 0.25, 1),
                                     barBorderWidth=(0.03, 0.03),
                                     borderWidth=(0.01, 0.01),
                                     frameColor=(0.5, 0.55, 0.70, 1),
                                     range=self.player.life,
                                     frameSize=(-1.2, 0, 0, -0.1),
                                     pos=(0.6, self.a2dLeft, self.a2dBottom + 0.15))
        self.lifeBar.setTransparency(1)
        self.lifeBar.reparentTo(self.render2d)

    def addControls(self):
        self.accept("w", self.moveY, [-80])
        self.accept("w-up", self.moveY, [0])
        self.accept("s", self.moveY, [80])
        self.accept("s-up", self.moveY, [0])
        self.accept("a", self.moveZ, [5])
        self.accept("a-up", self.moveZ, [0])
        self.accept("d", self.moveZ, [-5])
        self.accept("d-up", self.moveZ, [0])
        self.accept("space", self.fire)
        for abil in self.player.abilities:
            self.accept(abil.inp, abil.use)

    def manageCollisions(self, task):
        self.cTrav.traverse(self.render)
        self.player.collisions()
        for a in self.others:
            self.others[a].collisions()
        return Task.cont

    def camra(self, task):
        self.camera.setPos(self.player.getX(), self.player.getY(), 750)
        self.camera.setHpr(10, 270, 100)
        return Task.cont

    def aiBattle(self, advanced=False):
        if not advanced:
            self.ai = AI("models/panda-model", 0.05, (700, 700, 0), self.render,
                         {"walk": "models/panda-walk4"}, self, self.path, 200)
        else:
            self.ai = AdvancedAI("models/panda-model", 0.05, (700, 700, 0),
                                 self.render, {"walk": "models/panda-walk4"}, self,
                                 self.path, 200)
        self.others["ai"] = self.ai
        self.aiLifebar = DirectWaitBar(text="", value=self.ai.life,
                                       barColor=(0, 1, 0.25, 1),
                                       barBorderWidth=(0.003, 0.003),
                                       borderWidth=(0.001, 0.001),
                                       frameColor=(0.5, 0.55, 0.70, 1),
                                       range=self.ai.life,
                                       frameSize=(-0.45, 0, 0, -0.1),
                                       pos=(1, 0, self.a2dTop - 0.11)
                                       )
        self.aiLifebar.setTransparency(1)
        self.aiLifebar.reparentTo(self.render2d)

    def moveY(self, amount):
        self.player.moveY(amount)
        msg = "moved y " + str(amount) + "\n"
        print("sending: ", msg)
        server.send(msg.encode())

    def moveZ(self, amount):
        self.player.moveZ(amount)
        msg = "moved z " + str(amount) + "\n"
        print("sending: ", msg)
        server.send(msg.encode())

    def fire(self):
        self.player.fire()
        msg = "fired\n"
        print ("sending: ", msg)
        server.send(msg.encode())

    def update(self, task):
        self.lifeBar['value'] = self.player.currLife
        self.lifeBar.setValue()
        if self.ai is not None:
            self.aiLifebar['value'] = self.ai.currLife
            self.aiLifebar.setValue()
        while serverMsg.qsize() > 0:
            msg = serverMsg.get(False)
            try:
                print("received: ", msg, "\n")
                msg = msg.split()
                command = msg[0]
                if command == "myIDis":
                    self.myPID = msg[1]

                elif command == "newPlayer":
                    n = msg[1]
                    self.others[n] = Character("models/panda-model", 0.05, (300, 300, 0),
                                               self.render,
                                               {"walk": "models/panda-walk4"}, self,
                                               self.path, 200, "play2")
                    self.taskMgr.add(self.others[n].move, "Move" + n)
                elif command == "moved":
                    PID = msg[1]
                    if msg[2] == "y":
                        self.others[PID].moveY(int(msg[3]))
                    else:
                        self.others[PID].moveZ(int(msg[3]))
                elif command == "fired":
                    PID = msg[1]
                    self.others[PID].fire()
            except:
                print("rip")
            serverMsg.task_done()
        return Task.cont
Пример #7
0
class GUI:
    def __init__(self, rootParent=None):

        self.table = DirectFrame(
            frameColor=(1.0, 1.0, 1.0, 0.0),
            frameSize=(-1, 1, -1, 1),
            hpr=LVecBase3f(0, 0, 0),
            image='chapter1/table.png',
            pos=LPoint3f(0.55, 0, -0.575),
            sortOrder=200,
            image_scale=LVecBase3f(0.256, 1, 0.312),
            image_pos=LPoint3f(0, 0, 0),
            parent=rootParent,
        )
        self.table.setTransparency(1)

        self.btnFlashlight = DirectButton(
            frameColor=(0.8, 0.8, 0.8, 0.0),
            frameSize=(-0.4, 0.4, -0.4, 0.4),
            hpr=LVecBase3f(0, 0, 0),
            image='chapter1/flashlight.png',
            pos=LPoint3f(0.39, 0, -0.39),
            sortOrder=201,
            relief=1,
            scale=LVecBase3f(0.1, 0.1, 0.1),
            text='',
            image_scale=LVecBase3f(0.4, 0, 0.4),
            image_pos=LPoint3f(0, 0, 0),
            text_align=TextNode.A_center,
            text_scale=(1.0, 1.0),
            text_pos=(0, 0),
            text_fg=LVecBase4f(0, 0, 0, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            text_wordwrap=None,
            parent=rootParent,
            command=base.messenger.send,
            extraArgs=["chapter1_flashlight"],
            pressEffect=1,
        )
        self.btnFlashlight.setTransparency(1)

        self.btnTelephone = DirectButton(
            frameColor=(0.8, 0.8, 0.8, 0.0),
            frameSize=(-0.4, 0.4, -0.4, 0.4),
            hpr=LVecBase3f(0, 0, 0),
            pos=LPoint3f(0.625, 0, -0.125),
            relief=1,
            scale=LVecBase3f(0.1, 0.1, 0.1),
            text='',
            text_align=TextNode.A_center,
            text_scale=(1, 1),
            text_pos=(0, 0),
            text_fg=LVecBase4f(0, 0, 0, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            text_wordwrap=None,
            parent=rootParent,
            command=base.messenger.send,
            extraArgs=["chapter1_telephone"],
            pressEffect=1,
        )
        self.btnTelephone.setTransparency(0)

        self.btnDoor = DirectButton(
            frameColor=(0.8, 0.8, 0.8, 0.0),
            frameSize=(-0.5, 0.5, -2.0, 2.0),
            hpr=LVecBase3f(0, 0, 0),
            pos=LPoint3f(-0.75, 0, -0.125),
            relief=1,
            scale=LVecBase3f(0.1, 0.1, 0.1),
            text='',
            text_align=TextNode.A_center,
            text_scale=(1, 1),
            text_pos=(0, 0),
            text_fg=LVecBase4f(0, 0, 0, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            text_wordwrap=None,
            parent=rootParent,
            command=base.messenger.send,
            extraArgs=["chapter1_door"],
            pressEffect=1,
        )
        self.btnDoor.setTransparency(0)

        self.ringRing = DirectFrame(
            frameColor=(1.0, 1.0, 1.0, 0.0),
            frameSize=(-0.1, 0.1, -0.1, 0.1),
            hpr=LVecBase3f(0, 0, 0),
            image='chapter1/ringRing.png',
            pos=LPoint3f(0.5, 0, -0.025),
            image_scale=LVecBase3f(0.1, 1, 0.1),
            image_pos=LPoint3f(0, 0, 0),
            parent=rootParent,
        )
        self.ringRing.setTransparency(1)


    def show(self):
        self.table.show()
        self.btnFlashlight.show()
        self.btnTelephone.show()
        self.btnDoor.show()
        self.ringRing.show()

    def hide(self):
        self.table.hide()
        self.btnFlashlight.hide()
        self.btnTelephone.hide()
        self.btnDoor.hide()
        self.ringRing.hide()

    def destroy(self):
        self.table.destroy()
        self.btnFlashlight.destroy()
        self.btnTelephone.destroy()
        self.btnDoor.destroy()
        self.ringRing.destroy()
class NewsPageButtonManager(FSM.FSM):
    """This will control which button shows up in the HUD, the Goto News, Goto Prev Page, or Goto 3d World."""
    notify = DirectNotifyGlobal.directNotify.newCategory(
        "NewsPageButtonManager")

    def __init__(self):
        """Create the buttons."""
        FSM.FSM.__init__(self, "NewsPageButtonManager")
        self.buttonsLoaded = False
        self.goingToNewsPageFrom3dWorld = False
        self.goingToNewsPageFromStickerBook = False
        self.__blinkIval = None

        self.load()

##        if not launcher.getPhaseComplete(5.5):
##            # We haven't downloaded phase 5.5 yet; set a callback hook
##            # so the pages will load when we do get phase 5.5.
##            self.acceptOnce('phaseComplete-5.5', self.delayedLoadPhase55Stuff)
##            return
##        else:
##            self.loadPhase55Stuff()
##
##    def delayedLoadPhase55Stuff(self):
##        """Load the buttons, and then show the appropriate button."""
##        # we've just finished downloading phase 55
##        self.loadPhase55Stuff()
##        self.showAppropriateButton()

    def load(self):
        """
        We're now loading the assets from phase 3.5.
        """
        btnGui = loader.loadModel(
            'phase_3.5/models/gui/tt_m_gui_ign_newsBtnGui')
        self.openNewNewsUp = btnGui.find('**/tt_t_gui_ign_new')
        self.openNewNewsUpBlink = btnGui.find('**/tt_t_gui_ign_newBlink')
        self.openNewNewsHover = btnGui.find('**/tt_t_gui_ign_newHover')
        self.openOldNewsUp = btnGui.find('**/tt_t_gui_ign_oldNews')
        self.openOldNewsHover = btnGui.find('**/tt_t_gui_ign_oldHover')
        self.closeNewsUp = btnGui.find('**/tt_t_gui_ign_open')
        self.closeNewsHover = btnGui.find('**/tt_t_gui_ign_closeHover')
        btnGui.removeNode()

        oldScale = 0.5
        newScale = 0.9
        newPos = VBase3(0.914, 0, 0.862)
        textScale = 0.06
        self.gotoNewsButton = DirectButton(
            relief=None,
            image=(self.openOldNewsUp, self.openOldNewsHover,
                   self.openOldNewsHover),
            text=('', TTLocalizer.EventsPageNewsTabName,
                  TTLocalizer.EventsPageNewsTabName
                  ),  # TODO replace this with a symbol
            text_fg=(1, 1, 1, 1),
            text_shadow=(0, 0, 0, 1),
            text_scale=textScale,
            text_font=ToontownGlobals.getInterfaceFont(),
            pos=newPos,
            scale=newScale,
            command=self.__handleGotoNewsButton,
        )

        self.newIssueButton = DirectButton(
            relief=None,
            image=(self.openNewNewsUp, self.openNewNewsHover,
                   self.openNewNewsHover),
            text=('', TTLocalizer.EventsPageNewsTabName,
                  TTLocalizer.EventsPageNewsTabName
                  ),  # TODO replace this with a symbol
            text_fg=(1, 1, 1, 1),
            text_shadow=(0, 0, 0, 1),
            text_scale=textScale,
            text_font=ToontownGlobals.getInterfaceFont(),
            pos=newPos,
            scale=newScale,
            command=self.__handleGotoNewsButton,
        )

        self.gotoPrevPageButton = DirectButton(
            relief=None,
            image=(self.closeNewsUp, self.closeNewsHover, self.closeNewsHover),
            text=('', TTLocalizer.lClose, TTLocalizer.lClose
                  ),  #"goto prev page", # TODO replace this with a synmbol
            text_fg=(1, 1, 1, 1),
            text_shadow=(0, 0, 0, 1),
            text_scale=textScale,
            text_font=ToontownGlobals.getInterfaceFont(),
            pos=newPos,
            scale=newScale,
            command=self.__handleGotoPrevPageButton,
        )

        self.goto3dWorldButton = DirectButton(
            relief=None,
            image=(self.closeNewsUp, self.closeNewsHover, self.closeNewsHover),
            text=('', TTLocalizer.lClose, TTLocalizer.lClose
                  ),  # "goto 3d world", # TODO replace this with a symbol
            text_fg=(1, 1, 1, 1),
            text_shadow=(0, 0, 0, 1),
            text_scale=textScale,
            text_font=ToontownGlobals.getInterfaceFont(),
            pos=newPos,
            scale=newScale,
            command=self.__handleGoto3dWorldButton,
        )

        self.newIssueButton.hide()
        self.gotoNewsButton.hide()
        self.gotoPrevPageButton.hide()
        self.goto3dWorldButton.hide()

        self.accept('newIssueOut', self.handleNewIssueOut)

        bounce1Pos = VBase3(newPos.getX(), newPos.getY(),
                            newPos.getZ() + 0.022)  # (0.914, 0, 0.902)
        bounce2Pos = VBase3(newPos.getX(), newPos.getY(),
                            newPos.getZ() + 0.015)  # (0.914, 0, 0.895)

        bounceIval = Sequence(
            LerpPosInterval(self.newIssueButton,
                            0.1,
                            bounce1Pos,
                            blendType='easeOut'),
            LerpPosInterval(self.newIssueButton,
                            0.1,
                            newPos,
                            blendType='easeIn'),
            LerpPosInterval(self.newIssueButton,
                            0.07,
                            bounce2Pos,
                            blendType='easeOut'),
            LerpPosInterval(self.newIssueButton,
                            0.07,
                            newPos,
                            blendType='easeIn'))

        self.__blinkIval = Sequence(
            Func(self.__showOpenEyes),
            Wait(2),
            bounceIval,
            Wait(0.5),
            Func(self.__showClosedEyes),
            Wait(0.1),
            Func(self.__showOpenEyes),
            Wait(0.1),
            Func(self.__showClosedEyes),
            Wait(0.1),
        )

        # Start it looping, but pause it, so we can resume/pause it to
        # start/stop the flashing.
        self.__blinkIval.loop()
        self.__blinkIval.pause()

        self.buttonsLoaded = True

    def __showOpenEyes(self):
        self.newIssueButton['image'] = (self.openNewNewsUp,
                                        self.openNewNewsHover,
                                        self.openNewNewsHover)

    def __showClosedEyes(self):
        self.newIssueButton['image'] = (self.openNewNewsUpBlink,
                                        self.openNewNewsHover,
                                        self.openNewNewsHover)

    def clearGoingToNewsInfo(self):
        """Clear our flags on how we got to the news page."""
        self.goingToNewsPageFrom3dWorld = False
        self.goingToNewsPageFromStickerBook = False

    def __handleGotoNewsButton(self):
        # Don't open news if we are jumping
        currentState = base.localAvatar.animFSM.getCurrentState().getName()
        if currentState == 'jumpAirborne':
            return
        assert self.notify.debugStateCall(self)
        from toontown.toon import LocalToon  # must do import here to stop cyclic reference
        if not LocalToon.WantNewsPage:
            return
        if base.cr and base.cr.playGame and base.cr.playGame.getPlace(
        ) and base.cr.playGame.getPlace().fsm:
            fsm = base.cr.playGame.getPlace().fsm
            curState = fsm.getCurrentState().getName()
            if curState == 'walk':
                if hasattr(localAvatar, "newsPage"):
                    base.cr.centralLogger.writeClientEvent(
                        "news gotoNewsButton clicked")
                    localAvatar.book.setPage(localAvatar.newsPage)
                    fsm.request("stickerBook")
                    self.goingToNewsPageFrom3dWorld = True
            elif curState == 'stickerBook':
                if hasattr(localAvatar, "newsPage"):
                    base.cr.centralLogger.writeClientEvent(
                        "news gotoNewsButton clicked")
                    localAvatar.book.setPage(localAvatar.newsPage)
                    fsm.request("stickerBook")
                    self.goingToNewsPageFromStickerBook = True
                    self.showAppropriateButton()

    def __handleGotoPrevPageButton(self):
        assert self.notify.debugStateCall(self)
        localAvatar.book.setPageBeforeNews()
        self.clearGoingToNewsInfo()
        self.showAppropriateButton()
        pass

    def __handleGoto3dWorldButton(self):
        assert self.notify.debugStateCall(self)
        localAvatar.book.closeBook()
        pass

    def hideAllButtons(self):
        """Hide everything."""
        if not self.buttonsLoaded:
            return
        self.gotoNewsButton.hide()
        self.gotoPrevPageButton.hide()
        self.goto3dWorldButton.hide()
        self.newIssueButton.hide()
        self.__blinkIval.pause()

    def enterHidden(self):
        """There are times when we don't want any of this buttons to show, like when the shtikerbook is hidden."""
        self.hideAllButtons()

    def exitHidden(self):
        pass

    def enterNormalWalk(self):
        """The usual state when the avatar is just walking around the world."""
        if not self.buttonsLoaded:
            return

        if localAvatar.getLastTimeReadNews(
        ) < base.cr.inGameNewsMgr.getLatestIssue():
            self.gotoNewsButton.hide()
            self.newIssueButton.show()
            self.__blinkIval.resume()
        else:
            self.gotoNewsButton.show()
            self.newIssueButton.hide()
        self.gotoPrevPageButton.hide()
        self.goto3dWorldButton.hide()

    def exitNormalWalk(self):
        if not self.buttonsLoaded:
            return
        self.hideAllButtons()

    def enterGotoWorld(self):
        """We got here by directly clicking on the goto news button from the 3d world."""
        if not self.buttonsLoaded:
            return
        self.hideAllButtons()
        self.goto3dWorldButton.show()

    def exitGotoWorld(self):
        """Fix our state properly."""
        if not self.buttonsLoaded:
            return
        self.hideAllButtons()
        localAvatar.book.setPageBeforeNews(enterPage=False)
        self.clearGoingToNewsInfo()

    def enterPrevPage(self):
        """We got here by directly clicking on the goto news button from the sticker book."""
        if not self.buttonsLoaded:
            return
        self.hideAllButtons()
        self.gotoPrevPageButton.show()

    def exitPrevPage(self):
        """Fix our state properly."""
        if not self.buttonsLoaded:
            return
        self.hideAllButtons()
        ##        localAvatar.book.setPageBeforeNews()
        self.clearGoingToNewsInfo()

    def showAppropriateButton(self):
        """We know we want to show one of the 3 buttons, figure out which one."""
        self.notify.debugStateCall(self)
        from toontown.toon import LocalToon  # must do import here to stop cyclic reference
        if not LocalToon.WantNewsPage:
            return
        if not self.buttonsLoaded:
            return
        if base.cr and base.cr.playGame and base.cr.playGame.getPlace() and \
           hasattr(base.cr.playGame.getPlace(),'fsm') and base.cr.playGame.getPlace().fsm:
            fsm = base.cr.playGame.getPlace().fsm
            curState = fsm.getCurrentState().getName()
            # do not show the news page button if we are in the tutorial
            # or in cog hq lobbies
            if curState == 'walk':
                if localAvatar.tutorialAck and not localAvatar.isDisguised:
                    self.request("NormalWalk")
                else:
                    self.request("Hidden")
            elif curState == 'stickerBook':
                if self.goingToNewsPageFrom3dWorld:
                    if localAvatar.tutorialAck:
                        self.request("GotoWorld")
                    else:
                        self.request("Hidden")
                elif self.goingToNewsPageFromStickerBook:
                    if localAvatar.tutorialAck:
                        self.request("PrevPage")
                    else:
                        self.request("Hidden")
                else:
                    # we get here when he just clicked on the sticker book button
                    if localAvatar.tutorialAck:
                        self.request("NormalWalk")
                    else:
                        self.request("Hidden")

    def setGoingToNewsPageFromStickerBook(self, newVal):
        """Called when the news page tab gets clicked in sticker book."""
        assert self.notify.debugStateCall(self)
        self.goingToNewsPageFromStickerBook = newVal

    def enterOff(self):
        """Clean up the buttons."""
        self.ignoreAll()
        if not self.buttonsLoaded:
            return

        if self.__blinkIval:
            self.__blinkIval.finish()
            self.__blinkIval = None

        self.gotoNewsButton.destroy()
        self.newIssueButton.destroy()
        self.gotoPrevPageButton.destroy()
        self.goto3dWorldButton.destroy()

        del self.openNewNewsUp
        del self.openNewNewsUpBlink
        del self.openNewNewsHover
        del self.openOldNewsUp
        del self.openOldNewsHover
        del self.closeNewsUp
        del self.closeNewsHover

    def exitOff(self):
        """Print a warning if we get here."""
        self.notify.warning(
            'Should not get here. NewsPageButtonManager.exitOff')

    def simulateEscapeKeyPress(self):
        # Go back to the 3D World if you have come from the 3D World.
        if self.goingToNewsPageFrom3dWorld:
            self.__handleGoto3dWorldButton()
        # Else, go back to the previous page in the shticker book if you have come from there.
        if self.goingToNewsPageFromStickerBook:
            self.__handleGotoPrevPageButton()

    def handleNewIssueOut(self):
        """Handle the message that a new issue has been released."""
        # Our code does not deal with the case when it gets the new issue out message
        # while you are reading the news
        if localAvatar.isReadingNews():
            # do nothing he'll get informed when he closes the news that there's a new issue
            pass
        else:
            self.showAppropriateButton()
Пример #9
0
class GUI:
    def __init__(self, rootParent=None):
        
        self.frmChat = DirectFrame(
            frameColor=(0.25, 0.25, 0.25, 1.0),
            frameSize=(-0.4, 0.4, -1.25, 0.0),
            hpr=LVecBase3f(0, 0, 0),
            pos=LPoint3f(0, 0, 0),
            parent=rootParent,
        )
        self.frmChat.setTransparency(0)

        self.frmMessages = DirectScrolledFrame(
            borderWidth=(0.005, 0.005),
            canvasSize=(-0.38, 0.34, -1.2, 0.0),
            frameColor=(1, 1, 1, 1),
            frameSize=(-0.38, 0.38, -1.0, 0.0),
            hpr=LVecBase3f(0, 0, 0),
            pos=LPoint3f(0, 0, -0.1),
            relief=3,
            scrollBarWidth=0.03,
            state='normal',
            horizontalScroll_borderWidth=(0.01, 0.01),
            horizontalScroll_frameSize=(-0.05, 0.05, -0.015, 0.015),
            horizontalScroll_hpr=LVecBase3f(0, 0, 0),
            horizontalScroll_pos=LPoint3f(0, 0, 0),
            horizontalScroll_decButton_borderWidth=(0.01, 0.01),
            horizontalScroll_decButton_frameSize=(-0.05, 0.05, -0.04, 0.04),
            horizontalScroll_decButton_hpr=LVecBase3f(0, 0, 0),
            horizontalScroll_decButton_pos=LPoint3f(0, 0, 0),
            horizontalScroll_incButton_borderWidth=(0.01, 0.01),
            horizontalScroll_incButton_frameSize=(-0.05, 0.05, -0.04, 0.04),
            horizontalScroll_incButton_hpr=LVecBase3f(0, 0, 0),
            horizontalScroll_incButton_pos=LPoint3f(0, 0, 0),
            horizontalScroll_thumb_borderWidth=(0.01, 0.01),
            horizontalScroll_thumb_hpr=LVecBase3f(0, 0, 0),
            horizontalScroll_thumb_pos=LPoint3f(0, 0, 0),
            verticalScroll_borderWidth=(0.01, 0.01),
            verticalScroll_frameSize=(-0.015, 0.015, -0.05, 0.05),
            verticalScroll_hpr=LVecBase3f(0, 0, 0),
            verticalScroll_pos=LPoint3f(0, 0, 0),
            verticalScroll_decButton_borderWidth=(0.01, 0.01),
            verticalScroll_decButton_frameSize=(-0.04, 0.04, -0.05, 0.05),
            verticalScroll_decButton_hpr=LVecBase3f(0, 0, 0),
            verticalScroll_decButton_pos=LPoint3f(0.36, 0, -0.02),
            verticalScroll_incButton_borderWidth=(0.01, 0.01),
            verticalScroll_incButton_frameSize=(-0.04, 0.04, -0.05, 0.05),
            verticalScroll_incButton_hpr=LVecBase3f(0, 0, 0),
            verticalScroll_incButton_pos=LPoint3f(0.36, 0, -0.98),
            verticalScroll_thumb_borderWidth=(0.01, 0.01),
            verticalScroll_thumb_hpr=LVecBase3f(0, 0, 0),
            verticalScroll_thumb_pos=LPoint3f(0.36, 0, -0.418625),
            parent=self.frmChat,
        )
        self.frmMessages.setTransparency(0)

        self.txtMessage = DirectEntry(
            borderWidth=(0.005, 0.005),
            frameColor=(1.0, 1.0, 1.0, 1.0),
            hpr=LVecBase3f(0, 0, 0),
            overflow=1,
            pos=LPoint3f(-0.375, 0, -1.195),
            relief=3,
            scale=LVecBase3f(0.045, 0.045, 0.045),
            width=14.0,
            text_align=TextNode.A_left,
            text_scale=(1.0, 1.0),
            text_pos=(0, 0),
            text_fg=LVecBase4f(0, 0, 0, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            parent=self.frmChat,
        )
        self.txtMessage.setTransparency(0)

        self.btnSend = DirectButton(
            frameColor=(0.0, 0.0, 0.0, 0.0),
            frameSize=(-0.4, 0.4, -0.4, 0.4),
            hpr=LVecBase3f(0, 0, 0),
            image='assets/chat/ChatSend.png',
            pos=LPoint3f(0.33, 0, -1.18),
            relief=1,
            scale=LVecBase3f(0.1, 0.1, 0.1),
            text='',
            image_scale=LVecBase3f(0.4, 1, 0.4),
            image_pos=LPoint3f(0, 0, 0),
            text_align=TextNode.A_center,
            text_scale=(1, 1),
            text_pos=(0, 0),
            text_fg=LVecBase4f(0, 0, 0, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            parent=self.frmChat,
            command=base.messenger.send,
            extraArgs=["sendMessage"],
        )
        self.btnSend.setTransparency(1)

        self.btnToggleChat = DirectButton(
            frameColor=(0.15, 0.15, 0.15, 1.0),
            frameSize=(-0.4, 0.4, -0.02, 0.05),
            hpr=LVecBase3f(0, 0, 0),
            pos=LPoint3f(0, 0, -0.05),
            relief=1,
            scale=LVecBase3f(1, 1, 1),
            text='Toggle Chat',
            text_align=TextNode.A_center,
            text_scale=(0.05, 0.05),
            text_pos=(0, 0),
            text_fg=LVecBase4f(0.8, 0.8, 0.8, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            parent=rootParent,
            command=base.messenger.send,
            extraArgs=["toggleChat"],
        )
        self.btnToggleChat.setTransparency(0)


    def show(self):
        self.frmChat.show()
        self.btnToggleChat.show()

    def hide(self):
        self.frmChat.hide()
        self.btnToggleChat.hide()

    def destroy(self):
        self.frmChat.destroy()
        self.btnToggleChat.destroy()
Пример #10
0
class TeamActivityGui:
    COUNTDOWN_TASK_NAME = 'updateCountdownTask'
    timer = None
    statusText = None
    countdownText = None
    exitButton = None
    switchButton = None

    def __init__(self, activity):
        self.activity = activity

    def load(self):
        buttonModels = loader.loadModel('phase_3.5/models/gui/inventory_gui')
        upButton = buttonModels.find('**//InventoryButtonUp')
        downButton = buttonModels.find('**/InventoryButtonDown')
        rolloverButton = buttonModels.find('**/InventoryButtonRollover')
        self.exitButton = DirectButton(relief=None, text=TTLocalizer.PartyTeamActivityExitButton, text_fg=(1, 1, 0.65, 1), text_pos=(0, -0.15), text_scale=0.5, image=(upButton, downButton, rolloverButton), image_color=(1, 0, 0, 1), image_scale=(14.5, 1, 9), pos=(0, 0, 0.8), scale=0.15, command=self.handleExitButtonClick)
        self.exitButton.hide()
        if self.activity.toonsCanSwitchTeams():
            self.switchButton = DirectButton(relief=None, text=TTLocalizer.PartyTeamActivitySwitchTeamsButton, text_fg=(1, 1, 1, 1), text_pos=(0, 0.1), text_scale=0.5, image=(upButton, downButton, rolloverButton), image_color=(0, 1, 0, 1), image_scale=(15, 1, 15), pos=(0, 0, 0.5), scale=0.15, command=self.handleSwitchButtonClick)
            self.switchButton.hide()
        else:
            self.switchButton = None
        buttonModels.removeNode()
        self.countdownText = OnscreenText(text='', pos=(0.0, -0.2), scale=PartyGlobals.TeamActivityTextScale * 1.2, fg=(1.0, 1.0, 0.65, 1.0), align=TextNode.ACenter, font=ToontownGlobals.getSignFont(), mayChange=True)
        self.countdownText.hide()
        self.statusText = OnscreenText(text='', pos=(0.0, 0.0), scale=PartyGlobals.TeamActivityTextScale, fg=PartyGlobals.TeamActivityStatusColor, align=TextNode.ACenter, font=ToontownGlobals.getSignFont(), mayChange=True)
        self.statusText.hide()
        self.timer = PartyUtils.getNewToontownTimer()
        self.timer.hide()
        return

    def unload(self):
        self.hideWaitToStartCountdown()
        if self.exitButton is not None:
            self.exitButton.destroy()
            self.exitButton = None
        if self.switchButton is not None:
            self.switchButton.destroy()
            self.switchButton = None
        if self.countdownText is not None:
            self.countdownText.destroy()
            self.countdownText.removeNode()
            self.countdownText = None
        if self.statusText is not None:
            self.statusText.destroy()
            self.statusText.removeNode()
            self.statusText = None
        if self.timer is not None:
            self.timer.destroy()
            del self.timer
        return

    def showStatus(self, text):
        self.statusText.setText(text)
        self.statusText.show()

    def hideStatus(self):
        self.statusText.hide()

    def enableExitButton(self):
        self.exitButton.show()

    def disableExitButton(self):
        self.exitButton.hide()

    def handleExitButtonClick(self):
        self.disableExitButton()
        self.disableSwitchButton()
        self.activity.d_toonExitRequest()

    def enableSwitchButton(self):
        self.switchButton.show()

    def disableSwitchButton(self):
        if self.switchButton is not None:
            self.switchButton.hide()
        return

    def handleSwitchButtonClick(self):
        self.disableSwitchButton()
        self.disableExitButton()
        self.activity.d_toonSwitchTeamRequest()

    def showWaitToStartCountdown(self, duration, waitToStartTimestamp, almostDoneCallback = None):
        self._countdownAlmostDoneCallback = almostDoneCallback
        currentTime = globalClock.getRealTime()
        waitTimeElapsed = currentTime - waitToStartTimestamp
        if duration - waitTimeElapsed > 1.0:
            countdownTask = Task(self._updateCountdownTask)
            countdownTask.duration = duration - waitTimeElapsed
            self.countdownText.setText(str(int(countdownTask.duration)))
            self.countdownText.show()
            taskMgr.remove(TeamActivityGui.COUNTDOWN_TASK_NAME)
            taskMgr.add(countdownTask, TeamActivityGui.COUNTDOWN_TASK_NAME)

    def hideWaitToStartCountdown(self):
        taskMgr.remove(TeamActivityGui.COUNTDOWN_TASK_NAME)
        self._countdownAlmostDoneCallback = None
        if self.countdownText is not None:
            self.countdownText.hide()
        return

    def _updateCountdownTask(self, task):
        countdownTime = int(task.duration - task.time)
        seconds = str(countdownTime)
        if self.countdownText['text'] != seconds:
            self.countdownText['text'] = seconds
            if countdownTime == 3 and self._countdownAlmostDoneCallback is not None:
                self._countdownAlmostDoneCallback()
                self._countdownAlmostDoneCallback = None
        if task.time >= task.duration:
            return Task.done
        else:
            return Task.cont
        return

    def showTimer(self, duration):
        self.timer.setTime(duration)
        self.timer.countdown(duration, self._handleTimerExpired)
        self.timer.show()

    def hideTimer(self):
        self.timer.hide()
        self.timer.stop()

    def _handleTimerExpired(self):
        self.activity.handleGameTimerExpired()
Пример #11
0
class Menu(object):
    def __init__(self, main):
        self.main = main
        wx = base.win.get_x_size()
        wy = base.win.get_y_size()
        kx = 1600
        ky = 900
        self.myFrame = DirectFrame(frameColor=(1, 1, 1, 1),
                                   frameSize=(0, kx, 0, ky))

        menu_tex = loader.loadTexture("res/menu.png")
        menu_tex.set_minfilter(SamplerState.FT_nearest)
        menu_tex.set_magfilter(SamplerState.FT_linear)
        self.myFrame["frameTexture"] = menu_tex
        self.myFrame.reparentTo(base.pixel2d)
        self.myFrame.set_pos((wx - kx) / 2, 0, -(wy + ky) / 2)
        self.myFrame.set_transparency(True)

        self.startButton = DirectButton(text="",
                                        text_scale=1.0,
                                        text_fg=(0.2, 0.2, 0.2, 1),
                                        frameTexture="res/start.png",
                                        frameColor=(1, 1, 1, 1),
                                        frameSize=(-64, 64, -20, 20),
                                        command=self.main.startGame,
                                        relief=DGG.FLAT,
                                        rolloverSound=None,
                                        clickSound=None,
                                        parent=self.myFrame,
                                        scale=2.0,
                                        pos=(wx / 2, 0, wy / 2 + 50))
        self.startButton.setTransparency(1)

        self.exitButton = DirectButton(text="",
                                       text_scale=1.0,
                                       text_fg=(0.2, 0.2, 0.2, 1),
                                       frameTexture="res/exit.png",
                                       frameColor=(1, 1, 1, 1),
                                       frameSize=(-64, 64, -20, 20),
                                       relief=DGG.FLAT,
                                       command=exit,
                                       rolloverSound=None,
                                       clickSound=None,
                                       parent=self.myFrame,
                                       scale=2.0,
                                       pos=(wx / 2, 0, wy / 2 - 50))
        self.exitButton.setTransparency(1)

        self.resumeButton = DirectButton(text="",
                                         text_scale=1.0,
                                         text_fg=(0.2, 0.2, 0.2, 1),
                                         frameTexture="res/resume.png",
                                         frameColor=(1, 1, 1, 1),
                                         frameSize=(-64, 64, -20, 20),
                                         relief=DGG.FLAT,
                                         command=self.main.resumeGame,
                                         rolloverSound=None,
                                         clickSound=None,
                                         parent=self.myFrame,
                                         scale=2.0,
                                         pos=(wx / 2, 0, wy / 2 + 150))

        self.resumeButton.setTransparency(1)
        self.resumeButton.hide()

    def hideMenu(self):
        self.main.gui.show()
        seq = Sequence(LerpColorScaleInterval(self.myFrame, 0.4, (1, 1, 1, 0)),
                       Func(self.myFrame.hide))
        seq.start()

    def hideResume(self):
        seq = Sequence(
            LerpColorScaleInterval(self.resumeButton, .5, (1, 1, 1, 0)),
            Func(self.resumeButton.hide))
        seq.start()

    def showResume(self):
        self.resumeButton.show()
        seq = Sequence(
            LerpColorScaleInterval(self.resumeButton, .5, (1, 1, 1, 1)))
        seq.start()

    def showMenu(self):
        self.myFrame.show()
        self.main.gui.hide()
        seq = Sequence(LerpColorScaleInterval(self.myFrame, .5, (1, 1, 1, 1)))
        seq.start()
Пример #12
0
class GUI:
    def __init__(self, rootParent=None):

        self.volume = DirectSlider(
            pos=LPoint3f(0.2, 0, 0.325),
            text='Volume',
            text_pos=(-1.05, -0.02),
            text_fg=(1, 1, 1, 1),
            text_scale=0.1,
            text_align=TextNode.ARight,
            parent=rootParent,
            command=base.messenger.send,
            extraArgs=["volumeChange"],
        )
        self.volume.setTransparency(0)

        self.audioMute = DirectCheckButton(
            frameSize=(-2.925000047683716, 3.024999713897705, -0.225,
                       0.8250000238418579),
            pos=LPoint3f(0, 0, 0),
            scale=LVecBase3f(0.1, 0.1, 0.1),
            text='Mute',
            parent=rootParent,
            command=self.toggleMute,
        )
        self.audioMute.setTransparency(0)

        self.btnBack = DirectButton(
            frameSize=(-1.5249999523162843, 1.6499999523162843,
                       -0.21250001192092896, 0.8250000238418579),
            pos=LPoint3f(0, 0, -0.575),
            scale=LVecBase3f(0.1, 0.1, 0.1),
            text='Back',
            parent=rootParent,
            command=base.messenger.send,
            extraArgs=["optionBack"],
            pressEffect=1,
        )
        self.btnBack.setTransparency(0)

        self.fullscreen = DirectCheckButton(
            frameSize=(-3.35, 2.6, -0.213, 0.825),
            pos=LPoint3f(0.045, 0, -0.175),
            scale=LVecBase3f(0.1, 0.1, 0.1),
            text='Fullscreen',
            parent=rootParent,
            command=self.toggleFullscreen,
        )
        self.fullscreen.setTransparency(0)

    def show(self):
        self.volume.show()
        self.audioMute.show()
        self.btnBack.show()
        self.fullscreen.show()

    def hide(self):
        self.volume.hide()
        self.audioMute.hide()
        self.btnBack.hide()
        self.fullscreen.hide()

    def destroy(self):
        self.volume.destroy()
        self.audioMute.destroy()
        self.btnBack.destroy()
        self.fullscreen.destroy()
Пример #13
0
class Menu(object):
    def __init__(self,main): 
        self.main=main

        wx = base.win.get_x_size()
        wy = base.win.get_y_size()
        kx = 1920
        ky = 1080
        self.myFrame = DirectFrame(frameColor=(1,1,1,1),
            frameSize=(0, kx,0, ky))

        menu_tex = loader.loadTexture("res/menu.png")
        menu_tex.set_minfilter(SamplerState.FT_nearest)
        menu_tex.set_magfilter(SamplerState.FT_linear)
        self.myFrame["frameTexture"] = menu_tex
        self.myFrame.reparentTo(base.pixel2d)
        self.myFrame.set_pos( (wx-kx) / 2, 0, -(wy+ky) / 2)
        self.myFrame.set_transparency(True)

        self.startButton = DirectButton(
                    text = "",  
                    text_scale=1.0,
                    text_fg=(0.2,0.2,0.2,1),
                    frameTexture="res/start_game.png",
                    frameColor=(1,1,1,1),
                    frameSize=(-64, 64, -20, 20),
                    command=self.main.startGame,
                    relief=DGG.FLAT,
                    rolloverSound=None,
                    clickSound=None,
                    parent=self.myFrame,
                    scale=2.0,
                    pos=(wx/2 + 160, 0, wy/2 + 50)
                    )
        self.startButton.setTransparency(1)

        self.exitButton = DirectButton(
                    text = ("Exit Game"),  
                    pos=(0,0,-.8),
                    text_scale=.1,
                    frameColor=(0,0,0,0),
                    relief=1,
                    frameVisibleScale=(2,3),
                    command=exit,
                    rolloverSound=None,
                    clickSound=None,
                    parent=self.myFrame,
                    )
        self.exitButton.setTransparency(1)
        
        self.resumeButton = DirectButton(
                    text = ("Resume"),  
                    pos=(.0,0,.3),
                    text_scale=.1,
                    frameColor=(0,0,0,0),
                    relief=1,
                    frameVisibleScale=(2,3),
                    command=self.main.resumeGame,
                    rolloverSound=None,
                    clickSound=None,
                    parent=self.myFrame,
                    )
        
        self.resumeButton.setTransparency(1)
        self.resumeButton.hide()
        
        self.selectFrame= DirectFrame( frameColor=(1,1,1,1) , frameSize=(-64, 64, -20, 20) , frameTexture="res/select.png")
        self.selectFrame.setTransparency(1)
        self.selectFrame.reparentTo(self.startButton)
        self.entries = [self.exitButton,self.startButton,self.resumeButton]
        self.activeEntry = 1


    
    
    def clearKeys(self):
        base.ignore("arrow_up")
        base.ignore("arrow_down")
        base.ignore("arrow_left")
        base.ignore("arrow_right")
        base.ignore("escape")
        base.ignore("enter")
    
    def execSelection(self):
        self.entries[self.activeEntry]["command"]()
      
        
    def selectDown(self):
        if self.activeEntry == 0:
            self.activeEntry = len(self.entries)-1
        else:
            self.activeEntry -=1
        
        if self.entries[self.activeEntry].isHidden():
            self.selectDown()
            return   
        self.selectFrame.reparentTo(self.entries[self.activeEntry])
        
    def selectUp(self):

        if self.activeEntry == len(self.entries)-1:
            self.activeEntry=0
        else:
            self.activeEntry +=1
        if self.entries[self.activeEntry].isHidden() :
            self.selectUp()
            return
        self.selectFrame.reparentTo(self.entries[self.activeEntry])

    def hideMenu(self):
        self.clearKeys()
        self.main.gui.show()
        seq= Sequence( LerpColorScaleInterval(self.myFrame, 0.4 ,(1,1,1,0)) , Func(self.myFrame.hide) )
        seq.start()
    
    def hideResume(self):
        seq= Sequence( LerpColorScaleInterval(self.resumeButton, .5 ,(1,1,1,0)) , Func(self.resumeButton.hide))
        seq.start()
     
    def showResume(self):
        self.resumeButton.show()
        #seq= Sequence(  LerpColorScaleInterval(self.resumeButton, 1 ,(1,1,1,1)) )
        #seq.start()
        
    def showMenu(self): 
        self.clearKeys()
        base.accept("arrow_up" , self.selectUp )
        base.accept("arrow_down" , self.selectDown )
        base.accept("escape", exit)
        base.accept("enter",self.execSelection)  
        self.myFrame.show()
        self.main.gui.hide()
        seq= Sequence( LerpColorScaleInterval(self.myFrame, .5 ,(1,1,1,1)) )
        seq.start()
Пример #14
0
class LocalToon(DistributedToon):
    neverDisable = 1

    def __init__(self, cr):
        try:
            self.LocalToon_initialized
            return
        except:
            self.LocalToon_initialized = 1
        DistributedToon.__init__(self, cr)
        self.gagStartKey = config.GetString('gag-start-key')
        self.gagThrowKey = config.GetString('gag-throw-key')
        self.avatarChoice = cr.localAvChoice
        self.smartCamera = SmartCamera()
        self.chatInput = ChatInput()
        self.moneyGui = MoneyGui()
        self.laffMeter = LaffOMeter()
        self.positionExaminer = PositionExaminer()
        self.friendRequestManager = FriendRequestManager()
        self.friendsList = FriendsList()
        self.panel = ToonPanel()
        friendsgui = loader.loadModel(
            'phase_3.5/models/gui/friendslist_gui.bam')
        self.friendButton = DirectButton(
            geom=(friendsgui.find('**/FriendsBox_Closed'),
                  friendsgui.find('**/FriendsBox_Rollover'),
                  friendsgui.find('**/FriendsBox_Rollover')),
            text=("", "Friends", "Friends", ""),
            text_fg=(1, 1, 1, 1),
            text_shadow=(0, 0, 0, 1),
            text_scale=0.065,
            text_pos=(0, -0.2),
            relief=None,
            parent=base.a2dTopRight,
            pos=(-0.18, 0.0, -0.17),
            command=self.friendsButtonClicked,
            scale=0.75)
        friendsgui.removeNode()
        del friendsgui
        self.hideFriendButton()
        self.runSfx = base.loadSfx(
            "phase_3.5/audio/sfx/AV_footstep_runloop.ogg")
        self.runSfx.setLoop(True)
        self.walkSfx = base.loadSfx(
            "phase_3.5/audio/sfx/AV_footstep_walkloop.ogg")
        self.walkSfx.setLoop(True)
        self.controlManager = ControlManager.ControlManager(True, False)
        self.offset = 3.2375
        self.firstPersonCamPos = None
        self.movementKeymap = {
            "forward": 0,
            "backward": 0,
            "left": 0,
            "right": 0,
            "jump": 0
        }
        self.avatarMovementEnabled = False
        self.isMoving_forward = False
        self.isMoving_side = False
        self.isMoving_back = False
        self.isMoving_jump = False
        self.gagThrowBtn = None
        self.myBattle = None
        self.gagsTimedOut = False
        self.needsToSwitchToGag = None
        self.gagsEnabled = False

        self.pickerTrav = None
        self.pickerRay = None
        self.pickerRayNode = None
        self.pickerHandler = None
        self.rolledOverTag = None

        self.inTutorial = False
        self.hasDoneJump = False
        self.lastState = None
        self.lastAction = None

        self.jumpHardLandIval = None

        #base.cTrav.showCollisions(render)

    def _handleWentInTunnel(self, requestStatus):
        self.cr.playGame.getPlace().doneStatus = requestStatus
        messenger.send(self.cr.playGame.getPlace().doneEvent)

    def _handleCameOutTunnel(self):
        self.walkControls.setCollisionsActive(1)
        self.cr.playGame.getPlace().fsm.request(
            self.cr.playGame.getPlace().nextState)

    def handleClickedWhisper(self,
                             senderName,
                             fromId,
                             isPlayer,
                             openPanel=False):
        if self.cr.playGame.getPlace() == None or not hasattr(
                self.cr.playGame.getPlace(),
                'fsm') or self.cr.playGame.getPlace().fsm == None:
            return
        if openPanel and self.cr.playGame.getPlace().fsm.getCurrentState(
        ).getName() in ['walk', 'shtickerBook']:
            self.panel.makePanel(fromId)
        self.chatInput.disableKeyboardShortcuts()
        self.chatInput.fsm.request('input', ["", self.sendWhisper, [fromId]])

    def handleClickedSentWhisper(self, senderName, fromId, isPlayer):
        self.handleClickedWhisper(senderName, fromId, isPlayer, True)

    def sendWhisper(self, message, target):
        message = self.chatInput.chatInput.get()
        self.cr.friendsManager.d_sendWhisper(target, message)
        self.chatInput.fsm.request('idle')
        self.chatInput.enableKeyboardShortcuts()

    def hasDiscoveredHood(self, zoneId):
        return zoneId in self.hoodsDiscovered

    def hasTeleportAccess(self, zoneId):
        return zoneId in self.teleportAccess

    def tutorialCreated(self, zoneId):
        self.cr.tutorialCreated(zoneId)

    def friendsButtonClicked(self):
        self.hideFriendButton()
        self.friendsList.fsm.request('onlineFriendsList')

    def hideFriendButton(self):
        self.friendButton.hide()

    def showFriendButton(self):
        self.friendButton.show()

    def gotoNode(self, node, eyeHeight=3):
        possiblePoints = (Point3(3, 6, 0), Point3(-3, 6, 0), Point3(6, 6, 0),
                          Point3(-6, 6, 0), Point3(3, 9, 0), Point3(-3, 9, 0),
                          Point3(6, 9, 0), Point3(-6, 9, 0), Point3(9, 9, 0),
                          Point3(-9, 9, 0), Point3(6, 0, 0), Point3(-6, 0, 0),
                          Point3(6, 3, 0), Point3(-6, 3, 0), Point3(9, 9, 0),
                          Point3(-9, 9, 0), Point3(0, 12, 0), Point3(3, 12, 0),
                          Point3(-3, 12, 0), Point3(6, 12,
                                                    0), Point3(-6, 12, 0),
                          Point3(9, 12, 0), Point3(-9, 12,
                                                   0), Point3(0, -6, 0),
                          Point3(-3, -6, 0), Point3(0, -9,
                                                    0), Point3(-6, -9, 0))
        for point in possiblePoints:
            pos = self.positionExaminer.consider(node, point, eyeHeight)
            if pos:
                self.setPos(node, pos)
                self.lookAt(node)
                self.setHpr(self.getH() + random.choice((-10, 10)), 0, 0)
                return

        self.setPos(node, 0, 0, 0)

    def setFriendsList(self, friends):
        DistributedToon.setFriendsList(self, friends)
        self.cr.friendsManager.d_requestFriendsList()
        self.panel.maybeUpdateFriendButton()

    def d_requestAddFriend(self, avId):
        self.sendUpdate('requestAddFriend', [avId])

    def enablePicking(self):
        self.accept('toonClicked', self.toonClicked)

    def disablePicking(self):
        self.ignore('toonClicked')

    def toonClicked(self, avId):
        self.panel.makePanel(avId)

    def prepareToSwitchControlType(self):
        # Hack fix for getting stuck moving in one direction without pressing the movement keys.
        inputs = [
            "run", "forward", "reverse", "turnLeft", "turnRight", "slideLeft",
            "slideRight", "jump"
        ]
        for inputName in inputs:
            try:
                inputState.releaseInputs(inputName)
            except:
                pass

    def getBackpack(self):
        return DistributedToon.getBackpack(self)

    def setMyBattle(self, battle):
        self.myBattle = battle

    def getMyBattle(self):
        return self.myBattle

    def ghostOn(self):
        self.getGeomNode().setTransparency(1)
        self.getGeomNode().setColorScale(1, 1, 1, 0.25)

    def ghostOff(self):
        self.getGeomNode().setColorScale(1, 1, 1, 1)
        self.getGeomNode().setTransparency(0)

    def enterReadBook(self, ts=0, callback=None, extraArgs=[]):
        self.stopLookAround()
        self.b_lookAtObject(0, -45, 0)
        DistributedToon.enterReadBook(self, ts, callback, extraArgs)

    def exitReadBook(self):
        DistributedToon.exitReadBook(self)
        self.startLookAround()

    def getAirborneHeight(self):
        return self.offset + 0.025000000000000001

    def setupControls(self):
        self.walkControls = GravityWalker(legacyLifter=False)
        self.walkControls.setWallBitMask(CIGlobals.WallBitmask)
        self.walkControls.setFloorBitMask(CIGlobals.FloorBitmask)
        self.walkControls.setWalkSpeed(CIGlobals.ToonForwardSpeed,
                                       CIGlobals.ToonJumpForce,
                                       CIGlobals.ToonReverseSpeed,
                                       CIGlobals.ToonRotateSpeed)
        self.walkControls.initializeCollisions(base.cTrav,
                                               self,
                                               floorOffset=0.025,
                                               reach=4.0)
        self.walkControls.cEventSphereNodePath.node().setFromCollideMask(
            CIGlobals.WallBitmask | CIGlobals.WeaponBitmask
            | GunGameGlobals.HILL_BITMASK)
        self.walkControls.setAirborneHeightFunc(self.getAirborneHeight)

    def setWalkSpeedNormal(self):
        self.walkControls.setWalkSpeed(CIGlobals.ToonForwardSpeed,
                                       CIGlobals.ToonJumpForce,
                                       CIGlobals.ToonReverseSpeed,
                                       CIGlobals.ToonRotateSpeed)

    def setWalkSpeedSlow(self):
        self.walkControls.setWalkSpeed(CIGlobals.ToonForwardSlowSpeed,
                                       CIGlobals.ToonJumpSlowForce,
                                       CIGlobals.ToonReverseSlowSpeed,
                                       CIGlobals.ToonRotateSlowSpeed)

    def setupCamera(self):
        base.camLens.setMinFov(CIGlobals.DefaultCameraFov / (4. / 3.))
        base.camLens.setNearFar(CIGlobals.DefaultCameraNear,
                                CIGlobals.DefaultCameraFar)
        self.smartCamera.initializeSmartCamera()
        self.smartCamera.initCameraPositions()
        self.smartCamera.setCameraPositionByIndex(0)

    def setDNAStrand(self, dnaStrand):
        DistributedToon.setDNAStrand(self, dnaStrand)
        self.initCollisions()
        self.setupCamera()

    def setMoney(self, money):
        DistributedToon.setMoney(self, money)
        self.moneyGui.update(money)

    def setupNameTag(self, tempName=None):
        DistributedToon.setupNameTag(self, tempName)
        self.nametag.setNametagColor(
            NametagGlobals.NametagColors[NametagGlobals.CCLocal])
        self.nametag.unmanage(base.marginManager)
        self.nametag.setActive(0)
        self.nametag.updateAll()

    def d_broadcastPositionNow(self):
        self.d_clearSmoothing()
        self.d_broadcastPosHpr()

    def b_setAnimState(self, anim, callback=None, extraArgs=[]):
        if self.anim != anim:
            self.d_setAnimState(anim)
            DistributedToon.setAnimState(self,
                                         anim,
                                         callback=callback,
                                         extraArgs=extraArgs)

    def attachCamera(self):
        #self.notify.info("Attaching camera...")
        camera.reparentTo(self)
        camera.setPos(self.smartCamera.getIdealCameraPos())

    def startSmartCamera(self):
        #self.notify.info("Starting camera...")
        self.smartCamera.startUpdateSmartCamera()

    def resetSmartCamera(self):
        #self.notify.info("Resetting camera...")
        self.stopSmartCamera()
        self.startSmartCamera()

    def stopSmartCamera(self):
        #self.notify.info("Stopping camera...")
        self.smartCamera.stopUpdateSmartCamera()

    def detachCamera(self):
        #self.notify.info("Detaching camera...")
        camera.reparentTo(render)
        camera.setPos(0, 0, 0)
        camera.setHpr(0, 0, 0)

    def handleSuitAttack(self, attack_id, suit_id):
        DistributedToon.handleSuitAttack(self, attack_id, suit_id)

        if not self.isDead() and base.config.GetBool('want-sa-reactions'):
            base.taskMgr.remove('LT.attackReactionDone')
            attack = SuitAttacks.SuitAttackLengths.keys()[attack_id]
            suit = self.cr.doId2do.get(suit_id)
            animToPlay = None
            timeToWait = 3.0
            if not attack in ["pickpocket", "fountainpen"]:
                suitH = suit.getH(render) % 360
                myH = self.getH(render) % 360
                if -90.0 <= (suitH - myH) <= 90.0:
                    animToPlay = "fallFWD"
                else:
                    animToPlay = "fallBCK"
            elif attack in ["pickpocket"]:
                animToPlay = "cringe"
            elif attack in ["fountainpen"]:
                animToPlay = "conked"
                timeToWait = 5.0
            self.cr.playGame.getPlace().fsm.request('stop')
            self.b_setAnimState(animToPlay)
            base.taskMgr.doMethodLater(timeToWait, self.__attackReactionDone,
                                       'LT.attackReactionDone')

    def __attackReactionDone(self, task):
        self.cr.playGame.hood.loader.place.fsm.request('walk')
        self.b_setAnimState('neutral')
        return Task.done

    def printPos(self):
        x, y, z = self.getPos(render)
        h, p, r = self.getHpr(render)
        print "Pos: (%s, %s, %s), Hpr: (%s, %s, %s)" % (x, y, z, h, p, r)

    def enableAvatarControls(self):
        self.walkControls.enableAvatarControls()
        self.accept("control", self.updateMovementKeymap, ["jump", 1])
        self.accept("control-up", self.updateMovementKeymap, ["jump", 0])
        self.accept('tab', self.smartCamera.nextCameraPos, [1])
        self.accept('shift-tab', self.smartCamera.nextCameraPos, [0])
        self.accept('page_up', self.smartCamera.pageUp)
        self.accept('page_down', self.smartCamera.pageDown)
        self.accept('p', self.printPos)
        self.accept('jumpStart', self.__jump)
        self.accept('jumpLand', self.__handleJumpLand)
        self.accept('jumpHardLand', self.__handleJumpHardLand)
        self.avatarMovementEnabled = True
        self.playMovementSfx(None)

    def __handleJumpLand(self):
        if self.jumpHardLandIval:
            self.jumpHardLandIval.finish()
            self.jumpHardLandIval = None
        if self.getHealth() > 0:
            self.b_setAnimState('Happy')

    def __handleJumpHardLand(self):
        if self.jumpHardLandIval:
            self.jumpHardLandIval.finish()
            self.jumpHardLandIval = None
        self.jumpHardLandIval = ActorInterval(self, 'zend')
        self.jumpHardLandIval.setDoneEvent('LT::zend-done')
        self.acceptOnce('LT::zend-done', self.__handleJumpLand)
        self.jumpHardLandIval.start()

    def disableAvatarControls(self):
        self.walkControls.disableAvatarControls()
        self.ignore('tab')
        self.ignore('shift-tab')
        self.ignore('page_up')
        self.ignore('page_down')
        self.ignore("arrow_up")
        self.ignore("arrow_up-up")
        self.ignore("arrow_down")
        self.ignore("arrow_down-up")
        self.ignore("arrow_left")
        self.ignore("arrow_left-up")
        self.ignore("arrow_right")
        self.ignore("arrow_right-up")
        self.ignore("control")
        self.ignore("control-up")
        self.ignore('jumpStart')
        self.ignore('jumpLand')
        self.ignore('jumpHardLand')
        taskMgr.remove("avatarMovementTask")
        self.isMoving_forward = False
        self.isMoving_side = False
        self.isMoving_back = False
        self.isMoving_jump = False
        self.avatarMovementEnabled = False
        self.playMovementSfx(None)
        for k, _ in self.movementKeymap.items():
            self.updateMovementKeymap(k, 0)

    def updateMovementKeymap(self, key, value):
        self.movementKeymap[key] = value

    def getMovementKeyValue(self, key):
        return self.movementKeymap[key]

    def playMovementSfx(self, movement):
        if movement == "run":
            self.walkSfx.stop()
            self.runSfx.play()
        elif movement == "walk":
            self.runSfx.stop()
            self.walkSfx.play()
        else:
            self.runSfx.stop()
            self.walkSfx.stop()

    def __forward(self):
        self.resetHeadHpr()
        self.stopLookAround()
        if self.getHealth() < 1:
            self.playMovementSfx("walk")
            self.setPlayRate(1.2, 'dwalk')
            self.setAnimState('deadWalk')
        else:
            self.playMovementSfx("run")
            self.setAnimState('run')
        self.isMoving_side = False
        self.isMoving_back = False
        self.isMoving_forward = True
        self.isMoving_jump = False

    def __turn(self):
        self.resetHeadHpr()
        self.stopLookAround()
        self.playMovementSfx("walk")
        if self.getHealth() < 1:
            self.setPlayRate(1.2, 'dwalk')
            self.setAnimState('deadWalk')
        else:
            self.setPlayRate(1.0, "walk")
            self.setAnimState("walk")
        self.isMoving_forward = False
        self.isMoving_back = False
        self.isMoving_side = True
        self.isMoving_jump = False

    def __reverse(self):
        self.resetHeadHpr()
        self.stopLookAround()
        self.playMovementSfx("walk")
        if self.getHealth() < 1:
            self.setPlayRate(-1.0, 'dwalk')
            self.setAnimState('deadWalk')
        else:
            self.setAnimState("walkBack")
        self.isMoving_side = False
        self.isMoving_forward = False
        self.isMoving_back = True
        self.isMoving_jump = False

    def __jump(self):
        self.playMovementSfx(None)
        if base.localAvatar.getHealth() > 0:
            if self.playingAnim in ['run', 'walk']:
                self.b_setAnimState("leap")
            else:
                self.b_setAnimState("jump")
        self.isMoving_side = False
        self.isMoving_forward = False
        self.isMoving_back = False
        self.isMoving_jump = True

    def __neutral(self):
        self.resetHeadHpr()
        self.startLookAround()
        self.playMovementSfx(None)
        if base.localAvatar.getHealth() > 0:
            self.setAnimState("neutral")
        else:
            self.setPlayRate(1.0, 'dneutral')
            self.setAnimState("deadNeutral")
        self.isMoving_side = False
        self.isMoving_forward = False
        self.isMoving_back = False
        self.isMoving_jump = False

    def movementTask(self, task):
        if self.getMovementKeyValue("jump") == 1:
            if not self.walkControls.isAirborne:
                if self.walkControls.mayJump:
                    self.__jump()
                    self.hasDoneJump = True
                else:
                    if self.hasDoneJump:
                        if self.getHealth() > 0:
                            self.b_setAnimState('Happy')
                        self.hasDoneJump = False
        else:
            if not self.walkControls.isAirborne:
                if self.hasDoneJump:
                    if self.getHealth() > 0:
                        self.b_setAnimState('Happy')
                    self.hasDoneJump = False
        return task.cont

    def startTrackAnimToSpeed(self):
        if not base.taskMgr.hasTaskNamed(self.uniqueName('trackAnimToSpeed')):
            base.taskMgr.add(self.trackAnimToSpeed,
                             self.uniqueName('trackAnimToSpeed'))

    def stopTrackAnimToSpeed(self):
        base.taskMgr.remove(self.uniqueName('trackAnimToSpeed'))

    def trackAnimToSpeed(self, task):
        speed, rotSpeed, slideSpeed = self.walkControls.getSpeeds()
        state = None
        if self.getHealth() > 0:
            state = 'Happy'
        else:
            state = 'Sad'
        if state != self.lastState:
            self.lastState = state
            self.b_setAnimState(state)
            if base.minigame is None:
                if state == 'Sad':
                    self.setWalkSpeedSlow()
                else:
                    self.setWalkSpeedNormal()
        action = self.setSpeed(speed, rotSpeed)
        if action != self.lastAction:
            self.lastAction = action
            if action == CIGlobals.WALK_INDEX or action == CIGlobals.REVERSE_INDEX:
                self.resetHeadHpr()
                self.stopLookAround()
                self.playMovementSfx("walk")
            elif action == CIGlobals.RUN_INDEX:
                self.resetHeadHpr()
                self.stopLookAround()
                self.playMovementSfx("run")
            else:
                self.resetHeadHpr()
                self.startLookAround()
                self.playMovementSfx(None)
        return task.cont

    def createLaffMeter(self):
        r, g, b, _ = self.getHeadColor()
        animal = self.getAnimal()
        maxHp = self.getMaxHealth()
        hp = self.getHealth()
        self.laffMeter.generate(r, g, b, animal, maxHP=maxHp, initialHP=hp)
        self.laffMeter.start()

    def disableLaffMeter(self):
        self.laffMeter.stop()
        self.laffMeter.disable()

    def deleteLaffMeter(self):
        self.laffMeter.delete()

    def setLoadout(self, gagIds):
        DistributedToon.setLoadout(self, gagIds)
        if base.cr.playGame.getPlace() and base.cr.playGame.getPlace(
        ).fsm.getCurrentState().getName() == 'shtickerBook':
            if hasattr(base.cr.playGame.getPlace(), 'shtickerBookStateData'):
                if base.cr.playGame.getPlace(
                ).shtickerBookStateData.fsm.getCurrentState().getName(
                ) == 'inventoryPage':
                    base.cr.playGame.getPlace(
                    ).shtickerBookStateData.gui.fsm.request('idle')

    def enableGags(self, andKeys=0):
        if self.avatarMovementEnabled and andKeys:
            self.enableGagKeys()
        self.invGui.createGui()
        self.invGui.updateLoadout()
        self.backpack.loadoutGUI = self.invGui
        if self.backpack.getCurrentGag():
            self.invGui.setWeapon(self.backpack.getCurrentGag().getName(),
                                  playSound=False)

    def enableGagKeys(self):
        if self.gagThrowBtn:
            self.gagThrowBtn.bind(DGG.B1PRESS, self.startGag)
            self.gagThrowBtn.bind(DGG.B1RELEASE, self.throwGag)
        self.accept(self.gagStartKey, self.startGag)
        self.accept(self.gagThrowKey, self.throwGag)
        self.gagsEnabled = True

    def disableGagKeys(self):
        self.gagsEnabled = False
        if self.gagThrowBtn:
            self.gagThrowBtn.unbind(DGG.B1PRESS)
            self.gagThrowBtn.unbind(DGG.B1RELEASE)
        self.ignore(self.gagStartKey)
        self.ignore(self.gagThrowKey)

    def disableGags(self):
        self.disableGagKeys()
        if self.invGui:
            self.invGui.deleteGui()
        if hasattr(self, 'backpack'):
            if self.backpack:
                self.backpack.setCurrentGag()

    def setWeaponType(self, weaponType):
        enableKeysAgain = 0
        if weaponType != self.weaponType:
            enableKeysAgain = 1
        self.weaponType = weaponType
        if enableKeysAgain:
            self.disableGagKeys()
            self.enableGagKeys()

    def createMoney(self):
        self.moneyGui.createGui()
        # Automatically update incase we missed the db field.
        self.moneyGui.update(self.money)

    def handleMoneyChanged(self):
        self.moneyGui.update()

    def disableMoney(self):
        self.moneyGui.deleteGui()

    def resetHeadHpr(self):
        self.b_lookAtObject(0, 0, 0, blink=0)

    def canUseGag(self, preActive):
        if preActive:

            # We're checking if we can call `startGag` (before the gag gets activated)
            return (self.backpack is not None
                    and self.backpack.getCurrentGag() is not None
                    and self.backpack.getSupply() > 0 and self.gagsEnabled)

        else:

            # We're checking if we can call `throwGag` or `releaseGag` (after the gag gets activated)
            return (self.backpack is not None
                    and self.backpack.getCurrentGag() is not None
                    and self.backpack.getActiveGag() is not None
                    and self.backpack.getSupply() > 0 and self.gagsEnabled)

    def startGag(self, start=True):
        if not self.canUseGag(True) or self.backpack.getCurrentGag(
        ).__class__.__name__ == 'BananaPeel':
            return

        if self.gagThrowBtn:
            self.gagThrowBtn.unbind(DGG.B1PRESS)

        self.ignore(self.gagStartKey)
        self.resetHeadHpr()
        self.b_gagStart(self.backpack.getCurrentGag().getID())

    def throwGag(self, start=True):
        if not self.canUseGag(False):
            return

        if self.gagThrowBtn:
            self.gagThrowBtn.unbind(DGG.B1RELEASE)

        self.ignore(self.gagThrowKey)

        if self.backpack.getActiveGag().getType(
        ) == GagType.SQUIRT and self.backpack.getActiveGag().getName() in [
                CIGlobals.SeltzerBottle
        ]:
            self.b_gagRelease(self.backpack.getActiveGag().getID())
        else:
            self.b_gagThrow(self.backpack.getActiveGag().getID())

        activeGag = self.backpack.getActiveGag()
        if not activeGag:
            activeGag = self.backpack.getCurrentGag()

        if not activeGag.doesAutoRelease():
            Sequence(Wait(0.75), Func(self.releaseGag)).start()

    def releaseGag(self):
        if not self.canUseGag(False) or self.backpack.getCurrentGag(
        ).__class__.__name__ == 'BananaPeel':
            return
        gag = self.backpack.getActiveGag()
        if not gag:
            gag = self.backpack.getCurrentGag()
        if gag.getState() != GagState.RELEASED:
            gagName = gag.getName()
            self.b_gagRelease(GagGlobals.getIDByName(gagName))

    def checkSuitHealth(self, suit):
        pass

    def handleLookSpot(self, hpr):
        h, p, r = hpr
        self.d_lookAtObject(h, p, r, blink=1)

    def showGagButton(self):
        geom = CIGlobals.getDefaultBtnGeom()
        self.gagThrowBtn = DirectButton(geom=geom,
                                        geom_scale=(0.75, 1, 1),
                                        text="Throw Gag",
                                        text_scale=0.05,
                                        text_pos=(0, -0.01),
                                        relief=None,
                                        parent=base.a2dTopCenter,
                                        pos=(0, 0, -0.1))
        self.gagThrowBtn.setBin('gui-popup', 60)
        self.gagThrowBtn.hide()

    def hideGagButton(self):
        self.gagThrowBtn.removeNode()
        self.gagThrowBtn = None

    def showBookButton(self, inBook=0):
        self.book_gui = loader.loadModel(
            "phase_3.5/models/gui/sticker_open_close_gui.bam")
        self.book_btn = DirectButton(
            geom=(self.book_gui.find('**/BookIcon_CLSD'),
                  self.book_gui.find('**/BookIcon_OPEN'),
                  self.book_gui.find('**/BookIcon_RLVR')),
            relief=None,
            pos=(-0.175, 0, 0.163),
            command=self.bookButtonClicked,
            scale=(0.7, 0.8, 0.8),
            parent=base.a2dBottomRight)
        self.book_btn.setBin('gui-popup', 60)
        if inBook:
            self.book_btn["geom"] = (self.book_gui.find('**/BookIcon_OPEN'),
                                     self.book_gui.find('**/BookIcon_CLSD'),
                                     self.book_gui.find('**/BookIcon_RLVR2'))
            self.book_btn["command"] = self.bookButtonClicked
            self.book_btn["extraArgs"] = [0]

    def hideBookButton(self):
        if hasattr(self, 'book_gui'):
            self.book_gui.removeNode()
            del self.book_gui
        if hasattr(self, 'book_btn'):
            self.book_btn.destroy()
            del self.book_btn

    def bookButtonClicked(self, openIt=1):
        if openIt:
            base.cr.playGame.getPlace().fsm.request('shtickerBook')
        else:
            base.cr.playGame.getPlace().shtickerBookStateData.finished(
                "resume")

    def startMonitoringHP(self):
        taskMgr.add(self.monitorHealth, "localToon-monitorHealth")

    def monitorHealth(self, task):
        if self.isDead():
            base.taskMgr.remove("LT.attackReactionDone")
            if (self.cr.playGame.hood.id != ZoneUtil.getHoodId(self.zoneId)):
                self.cr.playGame.getPlace().fsm.request(
                    'died', [{}, self.diedStateDone])
                messenger.send(PCTMM.getLocalAvDiedEvent())
            return task.done
        return task.cont

    def stopMonitoringHP(self):
        taskMgr.remove("localToon-monitorHealth")

    def setHealth(self, hp):
        if hp > 0 and self.getHealth() < 1:
            if self.cr.playGame and self.cr.playGame.getPlace():
                if self.cr.playGame.getPlace().fsm.getCurrentState().getName(
                ) == 'walk':
                    if self.cr.playGame.getPlace(
                    ).walkStateData.fsm.getCurrentState().getName(
                    ) == 'deadWalking':
                        self.cr.playGame.getPlace().walkStateData.fsm.request(
                            'walking')
            if self.animFSM.getCurrentState().getName() == 'deadNeutral':
                self.playMovementSfx(None)
                self.b_setAnimState("neutral")
            elif self.animFSM.getCurrentState().getName() == 'deadWalk':
                self.playMovementSfx("run")
                self.b_setAnimState("run")
        DistributedToon.setHealth(self, hp)

    def diedStateDone(self, requestStatus):
        hood = self.cr.playGame.hood.id
        if hood == CIGlobals.BattleTTC:
            hood = CIGlobals.ToontownCentral
        toZone = ZoneUtil.getZoneId(hood)
        if self.zoneId != toZone:
            requestStatus = {
                'zoneId': toZone,
                'hoodId': hood,
                'where': ZoneUtil.getWhereName(toZone),
                'avId': self.doId,
                'loader': ZoneUtil.getLoaderName(toZone),
                'shardId': None,
                'wantLaffMeter': 1,
                'how': 'teleportIn'
            }
            self.cr.playGame.getPlace().doneStatus = requestStatus
            messenger.send(self.cr.playGame.getPlace().doneEvent)

        else:
            return

        ## Tell the ai we're dead so they can refill our hp.
        #self.sendUpdate("died", [])
        ## Then, log out and notify the client that they're dead.
        # self.cr.gameFSM.request("closeShard", ['died'])

    def teleportToCT(self):
        toZone = CIGlobals.CogTropolisId
        hood = CIGlobals.CogTropolis
        requestStatus = {
            'zoneId': toZone,
            'hoodId': hood,
            'where': ZoneUtil.getWhereName(toZone),
            'avId': self.doId,
            'loader': ZoneUtil.getLoaderName(toZone),
            'shardId': None,
            'wantLaffMeter': 1,
            'how': 'teleportIn',
            'world': CIGlobals.OToontown
        }
        self.cr.playGame.getPlace().fsm.request('teleportOut', [requestStatus])

    def createChatInput(self):
        self.chatInput.load()
        self.chatInput.enter()

    def disableChatInput(self):
        self.chatInput.exit()
        self.chatInput.unload()

    def collisionsOn(self):
        self.controlManager.collisionsOn()

    def collisionsOff(self):
        self.controlManager.collisionsOff()

    def toggleAspect2d(self):
        if base.aspect2d.isHidden():
            base.aspect2d.show()
        else:
            base.aspect2d.hide()

    def generate(self):
        DistributedToon.generate(self)

    def delete(self):
        DistributedToon.delete(self)
        self.deleteLaffMeter()
        return

    def disable(self):
        base.camLens.setMinFov(CIGlobals.OriginalCameraFov / (4. / 3.))
        if self.jumpHardLandIval:
            self.ignore('LT::zend-done')
            self.jumpHardLandIval.finish()
            self.jumpHardLandIval = None
        self.friendsList.destroy()
        self.friendsList = None
        self.panel.cleanup()
        self.panel = None
        self.positionExaminer.delete()
        self.positionExaminer = None
        self.disablePicking()
        self.stopMonitoringHP()
        taskMgr.remove("resetHeadColorAfterFountainPen")
        taskMgr.remove("LT.attackReactionDone")
        self.stopLookAround()
        DistributedToon.disable(self)
        self.disableAvatarControls()
        self.disableLaffMeter()
        self.disableGags()
        self.disableChatInput()
        self.weaponType = None
        self.myBattle = None
        self.ignore("gotLookSpot")
        self.ignore("clickedWhisper")
        self.ignore('f2')
        return

    def announceGenerate(self):
        DistributedToon.announceGenerate(self)
        self.setupControls()
        self.startLookAround()
        self.friendRequestManager.watch()
        self.accept("gotLookSpot", self.handleLookSpot)
        self.accept("clickedWhisper", self.handleClickedSentWhisper)
        self.accept('f2', self.toggleAspect2d)

        #self.accept('c', self.walkControls.setCollisionsActive, [0])

        self.invGui = InventoryGui()

        # Unused developer methods.
        #self.accept('enter', self.printAvPos)
        #self.accept('p', self.enterPictureMode)
        #self.accept('c', self.teleportToCT)
        #posBtn = DirectButton(text = "Get Pos", scale = 0.08, pos = (0.3, 0, 0), parent = base.a2dLeftCenter, command = self.printAvPos)

    def enterHiddenToonMode(self):
        self.laffMeter.stop()
        self.laffMeter.disable()
        self.laffMeter.destroy()
        self.getGeomNode().hide()
        self.deleteNameTag()
        self.moneyGui.deleteGui()
        self.invGui.deleteGui()
        self.hideGagButton()
        self.hideFriendButton()
        self.hideBookButton()
        self.removeAdminToken()

    def printAvPos(self):
        print "Pos: %s, Hpr: %s" % (self.getPos(), self.getHpr())
Пример #15
0
class GUI:
    def __init__(self, rootParent=None):

        self.btnBox1 = DirectButton(
            frameColor=(0.8, 0.8, 0.8, 0.0),
            frameSize=(-1.0, 1.0, -1.0, 1.0),
            hpr=LVecBase3f(0, 0, 0),
            image='chapter2/box1.png',
            pos=LPoint3f(-0.25, 0, -0.35),
            relief=1,
            scale=LVecBase3f(0.05, 0.08, 0.05),
            text='',
            image_scale=LVecBase3f(1, 1, 1),
            image_pos=LPoint3f(0, 0, 0),
            text_align=TextNode.A_center,
            text_scale=(1.0, 1.0),
            text_pos=(0, 0),
            text_fg=LVecBase4f(0, 0, 0, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            text_wordwrap=None,
            parent=rootParent,
            command=base.messenger.send,
            extraArgs=["box1"],
            pressEffect=0,
        )
        self.btnBox1.setTransparency(1)

        self.btnBox2 = DirectButton(
            frameColor=(0.8, 0.8, 0.8, 0.0),
            frameSize=(-1.0, 1.0, -1.0, 1.0),
            hpr=LVecBase3f(0, 0, 0),
            image='chapter2/box2.png',
            pos=LPoint3f(0.4, 0, 0.16),
            relief=1,
            scale=LVecBase3f(0.05, 0.08, 0.05),
            text='',
            image_scale=LVecBase3f(1, 1, 1),
            image_pos=LPoint3f(0, 0, 0),
            text_align=TextNode.A_center,
            text_scale=(1, 1),
            text_pos=(0, 0),
            text_fg=LVecBase4f(0, 0, 0, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            text_wordwrap=None,
            parent=rootParent,
            command=base.messenger.send,
            extraArgs=["box2"],
            pressEffect=0,
        )
        self.btnBox2.setTransparency(1)

        self.btnBox3 = DirectButton(
            frameColor=(0.8, 0.8, 0.8, 0.0),
            frameSize=(-1.0, 1.0, -1.0, 1.0),
            hpr=LVecBase3f(0, 0, 0),
            image='chapter2/box3.png',
            pos=LPoint3f(0.305, 0, -0.435),
            relief=1,
            scale=LVecBase3f(0.08, 0.1, 0.08),
            text='',
            image_scale=LVecBase3f(1, 1, 1),
            image_pos=LPoint3f(0, 0, 0),
            text_align=TextNode.A_center,
            text_scale=(1, 1),
            text_pos=(0, 0),
            text_fg=LVecBase4f(0, 0, 0, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            text_wordwrap=None,
            parent=rootParent,
            command=base.messenger.send,
            extraArgs=["box3"],
            pressEffect=0,
        )
        self.btnBox3.setTransparency(1)

        self.overlay = DirectFrame(
            frameColor=(1.0, 1.0, 1.0, 0.0),
            frameSize=(-0.8, 0.8, -0.8, 0.8),
            hpr=LVecBase3f(0, 0, 0),
            image='chapter2/overlay.png',
            pos=LPoint3f(0, 0, 0),
            image_scale=LVecBase3f(0.8, 1, 0.8),
            image_pos=LPoint3f(0, 0, 0),
            parent=rootParent,
        )
        self.overlay.setTransparency(1)

    def show(self):
        self.btnBox1.show()
        self.btnBox2.show()
        self.btnBox3.show()
        self.overlay.show()

    def hide(self):
        self.btnBox1.hide()
        self.btnBox2.hide()
        self.btnBox3.hide()
        self.overlay.hide()

    def destroy(self):
        self.btnBox1.destroy()
        self.btnBox2.destroy()
        self.btnBox3.destroy()
        self.overlay.destroy()
Пример #16
0
class Menu(object):
    def __init__(self, main):
        self.main = main

        wx = base.win.get_x_size()
        wy = base.win.get_y_size()
        kx = 1920
        ky = 1080
        self.myFrame = DirectFrame(frameColor=(1, 1, 1, 1),
                                   frameSize=(0, kx, 0, ky))

        menu_tex = loader.loadTexture("res/menu.png")
        menu_tex.set_minfilter(SamplerState.FT_nearest)
        menu_tex.set_magfilter(SamplerState.FT_linear)
        self.myFrame["frameTexture"] = menu_tex
        self.myFrame.reparentTo(base.pixel2d)
        self.myFrame.set_pos((wx - kx) / 2, 0, -(wy + ky) / 2)
        self.myFrame.set_transparency(True)

        self.startButton = DirectButton(text="",
                                        text_scale=1.0,
                                        text_fg=(0.2, 0.2, 0.2, 1),
                                        frameTexture="res/start_game.png",
                                        frameColor=(1, 1, 1, 1),
                                        frameSize=(-64, 64, -20, 20),
                                        command=self.main.startGame,
                                        relief=DGG.FLAT,
                                        rolloverSound=None,
                                        clickSound=None,
                                        parent=self.myFrame,
                                        scale=2.0,
                                        pos=(wx / 2 + 160, 0, wy / 2 + 50))
        self.startButton.setTransparency(1)

        self.exitButton = DirectButton(
            text=("Exit Game"),
            pos=(0, 0, -.8),
            text_scale=.1,
            frameColor=(0, 0, 0, 0),
            relief=1,
            frameVisibleScale=(2, 3),
            command=exit,
            rolloverSound=None,
            clickSound=None,
            parent=self.myFrame,
        )
        self.exitButton.setTransparency(1)

        self.resumeButton = DirectButton(
            text=("Resume"),
            pos=(.0, 0, .3),
            text_scale=.1,
            frameColor=(0, 0, 0, 0),
            relief=1,
            frameVisibleScale=(2, 3),
            command=self.main.resumeGame,
            rolloverSound=None,
            clickSound=None,
            parent=self.myFrame,
        )

        self.resumeButton.setTransparency(1)
        self.resumeButton.hide()

        self.selectFrame = DirectFrame(frameColor=(1, 1, 1, 1),
                                       frameSize=(-64, 64, -20, 20),
                                       frameTexture="res/select.png")
        self.selectFrame.setTransparency(1)
        self.selectFrame.reparentTo(self.startButton)
        self.entries = [self.exitButton, self.startButton, self.resumeButton]
        self.activeEntry = 1

    def clearKeys(self):
        base.ignore("arrow_up")
        base.ignore("arrow_down")
        base.ignore("arrow_left")
        base.ignore("arrow_right")
        base.ignore("escape")
        base.ignore("enter")

    def execSelection(self):
        self.entries[self.activeEntry]["command"]()

    def selectDown(self):
        if self.activeEntry == 0:
            self.activeEntry = len(self.entries) - 1
        else:
            self.activeEntry -= 1

        if self.entries[self.activeEntry].isHidden():
            self.selectDown()
            return
        self.selectFrame.reparentTo(self.entries[self.activeEntry])

    def selectUp(self):

        if self.activeEntry == len(self.entries) - 1:
            self.activeEntry = 0
        else:
            self.activeEntry += 1
        if self.entries[self.activeEntry].isHidden():
            self.selectUp()
            return
        self.selectFrame.reparentTo(self.entries[self.activeEntry])

    def hideMenu(self):
        self.clearKeys()
        self.main.gui.show()
        seq = Sequence(LerpColorScaleInterval(self.myFrame, 0.4, (1, 1, 1, 0)),
                       Func(self.myFrame.hide))
        seq.start()

    def hideResume(self):
        seq = Sequence(
            LerpColorScaleInterval(self.resumeButton, .5, (1, 1, 1, 0)),
            Func(self.resumeButton.hide))
        seq.start()

    def showResume(self):
        self.resumeButton.show()
        #seq= Sequence(  LerpColorScaleInterval(self.resumeButton, 1 ,(1,1,1,1)) )
        #seq.start()

    def showMenu(self):
        self.clearKeys()
        base.accept("arrow_up", self.selectUp)
        base.accept("arrow_down", self.selectDown)
        base.accept("escape", exit)
        base.accept("enter", self.execSelection)
        self.myFrame.show()
        self.main.gui.hide()
        seq = Sequence(LerpColorScaleInterval(self.myFrame, .5, (1, 1, 1, 1)))
        seq.start()
Пример #17
0
class LocalToon(DistributedToon):
    neverDisable = 1

    def __init__(self, cr):
        try:
            self.LocalToon_initialized
            return
        except:
            self.LocalToon_initialized = 1

        DistributedToon.__init__(self, cr)
        self.avatarChoice = cr.localAvChoice
        self.smartCamera = SmartCamera()
        self.chatInput = ChatInput()
        self.moneyGui = MoneyGui()
        self.laffMeter = LaffOMeter()
        self.positionExaminer = PositionExaminer()
        self.friendRequestManager = FriendRequestManager()
        self.friendsList = FriendsList()
        self.panel = ToonPanel()
        friendsgui = loader.loadModel('phase_3.5/models/gui/friendslist_gui.bam')
        self.friendButton = DirectButton(geom=(friendsgui.find('**/FriendsBox_Closed'), friendsgui.find('**/FriendsBox_Rollover'), friendsgui.find('**/FriendsBox_Rollover')), text=('', 'Friends', 'Friends', ''), text_fg=(1, 1, 1, 1), text_shadow=(0, 0, 0, 1), text_scale=0.065, text_pos=(0, -0.2), relief=None, parent=base.a2dTopRight, pos=(-0.18, 0.0, -0.17), command=self.friendsButtonClicked, scale=0.75)
        friendsgui.removeNode()
        del friendsgui
        self.hideFriendButton()
        self.runSfx = base.loadSfx('phase_3.5/audio/sfx/AV_footstep_runloop.wav')
        self.runSfx.setLoop(True)
        self.walkSfx = base.loadSfx('phase_3.5/audio/sfx/AV_footstep_walkloop.wav')
        self.walkSfx.setLoop(True)
        self.controlManager = ControlManager.ControlManager(True, False)
        self.offset = 3.2375
        self.movementKeymap = {'forward': 0,
         'backward': 0,
         'left': 0,
         'right': 0,
         'jump': 0}
        self.avatarMovementEnabled = False
        self.isMoving_forward = False
        self.isMoving_side = False
        self.isMoving_back = False
        self.isMoving_jump = False
        self.pieThrowBtn = None
        self.myBattle = None
        self.invGui = None
        self.pickerTrav = None
        self.pickerRay = None
        self.pickerRayNode = None
        self.pickerHandler = None
        self.rolledOverTag = None
        self.inTutorial = False
        self.hasDoneJump = False
        self.lastState = None
        self.lastAction = None
        return

    def hasDiscoveredHood(self, zoneId):
        return zoneId in self.hoodsDiscovered

    def hasTeleportAccess(self, zoneId):
        return zoneId in self.teleportAccess

    def tutorialCreated(self, zoneId):
        self.cr.tutorialCreated(zoneId)

    def friendsButtonClicked(self):
        self.hideFriendButton()
        self.friendsList.fsm.request('onlineFriendsList')

    def hideFriendButton(self):
        self.friendButton.hide()

    def showFriendButton(self):
        self.friendButton.show()

    def gotoNode(self, node, eyeHeight = 3):
        possiblePoints = (Point3(3, 6, 0),
         Point3(-3, 6, 0),
         Point3(6, 6, 0),
         Point3(-6, 6, 0),
         Point3(3, 9, 0),
         Point3(-3, 9, 0),
         Point3(6, 9, 0),
         Point3(-6, 9, 0),
         Point3(9, 9, 0),
         Point3(-9, 9, 0),
         Point3(6, 0, 0),
         Point3(-6, 0, 0),
         Point3(6, 3, 0),
         Point3(-6, 3, 0),
         Point3(9, 9, 0),
         Point3(-9, 9, 0),
         Point3(0, 12, 0),
         Point3(3, 12, 0),
         Point3(-3, 12, 0),
         Point3(6, 12, 0),
         Point3(-6, 12, 0),
         Point3(9, 12, 0),
         Point3(-9, 12, 0),
         Point3(0, -6, 0),
         Point3(-3, -6, 0),
         Point3(0, -9, 0),
         Point3(-6, -9, 0))
        for point in possiblePoints:
            pos = self.positionExaminer.consider(node, point, eyeHeight)
            if pos:
                self.setPos(node, pos)
                self.lookAt(node)
                self.setHpr(self.getH() + random.choice((-10, 10)), 0, 0)
                return

        self.setPos(node, 0, 0, 0)

    def setFriendsList(self, friends):
        DistributedToon.setFriendsList(self, friends)
        self.cr.friendsManager.d_requestFriendsList()
        self.panel.maybeUpdateFriendButton()

    def d_requestAddFriend(self, avId):
        self.sendUpdate('requestAddFriend', [avId])

    def setupPicker(self):
        self.pickerTrav = CollisionTraverser('LT.pickerTrav')
        self.pickerRay = CollisionRay()
        rayNode = CollisionNode('LT.pickerNode')
        rayNode.addSolid(self.pickerRay)
        rayNode.setCollideMask(BitMask32(0))
        rayNode.setFromCollideMask(CIGlobals.WallBitmask)
        self.pickerRayNode = base.camera.attachNewNode(rayNode)
        self.pickerHandler = CollisionHandlerQueue()
        self.pickerTrav.addCollider(self.pickerRayNode, self.pickerHandler)

    def enablePicking(self):
        self.accept('mouse1', self.pickedSomething_down)
        self.accept('mouse1-up', self.pickedSomething_up)
        base.taskMgr.add(self.__travMousePicker, 'LT.travMousePicker')

    def disablePicking(self):
        base.taskMgr.remove('LT.travMousePicker')
        self.ignore('mouse1')
        self.ignore('mouse1-up')

    def pickedSomething_down(self):
        if self.rolledOverTag:
            base.playSfx(DGG.getDefaultClickSound())
            avatar = self.cr.doId2do.get(self.rolledOverTag)
            avatar.nameTag.setPickerState('down')

    def pickedSomething_up(self):
        if self.rolledOverTag:
            avatar = self.cr.doId2do.get(self.rolledOverTag)
            avatar.nameTag.setPickerState('up')
            self.panel.makePanel(self.rolledOverTag)

    def __travMousePicker(self, task):
        if not base.mouseWatcherNode.hasMouse():
            return task.cont
        else:
            mpos = base.mouseWatcherNode.getMouse()
            self.pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())
            self.pickerTrav.traverse(render)
            if self.pickerHandler.getNumEntries() > 0:
                self.pickerHandler.sortEntries()
                pickedObject = self.pickerHandler.getEntry(0).getIntoNodePath()
                avatarId = pickedObject.getParent().getPythonTag('avatar')
                if avatarId != None:
                    for do in self.cr.doId2do.values():
                        if do.__class__.__name__ == 'DistributedToon':
                            if do.doId == avatarId:
                                if do.nameTag.getClickable() == 1:
                                    if do.nameTag.fsm.getCurrentState().getName() != 'rollover' and do.nameTag.fsm.getCurrentState().getName() != 'down':
                                        do.nameTag.setPickerState('rollover')
                                        base.playSfx(DGG.getDefaultRolloverSound())
                                        self.rolledOverTag = avatarId
                                        break
                        elif do.__class__.__name__ == 'DistributedToon':
                            if do.nameTag.fsm.getCurrentState().getName() != 'up':
                                do.nameTag.setPickerState('up')

                elif self.rolledOverTag:
                    avatar = self.cr.doId2do.get(self.rolledOverTag)
                    if avatar:
                        if avatar.nameTag.fsm.getCurrentState().getName() != 'up':
                            avatar.nameTag.setPickerState('up')
                    self.rolledOverTag = None
            return task.cont

    def prepareToSwitchControlType(self):
        inputs = ['run',
         'forward',
         'reverse',
         'turnLeft',
         'turnRight',
         'slideLeft',
         'slideRight',
         'jump']
        for inputName in inputs:
            try:
                inputState.releaseInputs(inputName)
            except:
                pass

    def getBackpack(self):
        return DistributedToon.getBackpack(self)

    def setMyBattle(self, battle):
        self.myBattle = battle

    def getMyBattle(self):
        return self.myBattle

    def ghostOn(self):
        self.getGeomNode().setTransparency(1)
        self.getGeomNode().setColorScale(1, 1, 1, 0.25)

    def ghostOff(self):
        self.getGeomNode().setColorScale(1, 1, 1, 1)
        self.getGeomNode().setTransparency(0)

    def enterReadBook(self, ts = 0, callback = None, extraArgs = []):
        self.stopLookAround()
        self.b_lookAtObject(0, -45, 0)
        DistributedToon.enterReadBook(self, ts, callback, extraArgs)

    def exitReadBook(self):
        DistributedToon.exitReadBook(self)
        self.startLookAround()

    def getAirborneHeight(self):
        return self.offset + 0.025

    def setupControls(self):
        self.walkControls = GravityWalker(legacyLifter=False)
        self.walkControls.setWallBitMask(CIGlobals.WallBitmask)
        self.walkControls.setFloorBitMask(CIGlobals.FloorBitmask)
        self.walkControls.setWalkSpeed(CIGlobals.ToonForwardSpeed, CIGlobals.ToonJumpForce, CIGlobals.ToonReverseSpeed, CIGlobals.ToonRotateSpeed)
        self.walkControls.initializeCollisions(base.cTrav, self, floorOffset=0.025, reach=4.0)
        self.walkControls.setAirborneHeightFunc(self.getAirborneHeight)

    def setWalkSpeedNormal(self):
        self.walkControls.setWalkSpeed(CIGlobals.ToonForwardSpeed, CIGlobals.ToonJumpForce, CIGlobals.ToonReverseSpeed, CIGlobals.ToonRotateSpeed)

    def setWalkSpeedSlow(self):
        self.walkControls.setWalkSpeed(CIGlobals.ToonForwardSlowSpeed, CIGlobals.ToonJumpSlowForce, CIGlobals.ToonReverseSlowSpeed, CIGlobals.ToonRotateSlowSpeed)

    def setupCamera(self):
        base.camLens.setMinFov(CIGlobals.DefaultCameraFov / (4.0 / 3.0))
        base.camLens.setNearFar(CIGlobals.DefaultCameraNear, CIGlobals.DefaultCameraFar)
        camHeight = max(self.getHeight(), 3.0)
        heightScaleFactor = camHeight * 0.3333333333
        defLookAt = Point3(0.0, 1.5, camHeight)
        camPos = (Point3(0.0, -9.0 * heightScaleFactor, camHeight),
         defLookAt,
         Point3(0.0, camHeight, camHeight * 4.0),
         Point3(0.0, camHeight, camHeight * -1.0),
         0)
        self.smartCamera.initializeSmartCamera()
        self.smartCamera.setIdealCameraPos(camPos[0])
        self.smartCamera.setLookAtPoint(defLookAt)

    def setDNAStrand(self, dnaStrand):
        DistributedToon.setDNAStrand(self, dnaStrand)
        self.initCollisions()
        self.setupCamera()

    def setMoney(self, money):
        DistributedToon.setMoney(self, money)
        self.moneyGui.update(money)

    def setupNameTag(self, tempName = None):
        DistributedToon.setupNameTag(self, tempName)
        if self.nameTag:
            self.nameTag.setColorLocal()

    def d_broadcastPositionNow(self):
        self.d_clearSmoothing()
        self.d_broadcastPosHpr()

    def b_setAnimState(self, anim, callback = None, extraArgs = []):
        if self.anim != anim:
            self.d_setAnimState(anim)
            DistributedToon.setAnimState(self, anim, callback=callback, extraArgs=extraArgs)

    def attachCamera(self):
        camera.reparentTo(self)
        camera.setPos(self.smartCamera.getIdealCameraPos())

    def startSmartCamera(self):
        self.smartCamera.startUpdateSmartCamera()

    def resetSmartCamera(self):
        self.stopSmartCamera()
        self.startSmartCamera()

    def stopSmartCamera(self):
        self.smartCamera.stopUpdateSmartCamera()

    def detachCamera(self):
        camera.reparentTo(render)
        camera.setPos(0, 0, 0)
        camera.setHpr(0, 0, 0)

    def handleSuitAttack(self, attack_id, suit_id):
        DistributedToon.handleSuitAttack(self, attack_id, suit_id)
        if not self.isDead() and base.config.GetBool('want-sa-reactions'):
            base.taskMgr.remove('LT.attackReactionDone')
            attack = SuitAttacks.SuitAttackLengths.keys()[attack_id]
            suit = self.cr.doId2do.get(suit_id)
            animToPlay = None
            timeToWait = 3.0
            if attack not in ('pickpocket', 'fountainpen'):
                suitH = suit.getH(render) % 360
                myH = self.getH(render) % 360
                if -90.0 <= suitH - myH <= 90.0:
                    animToPlay = 'fallFWD'
                else:
                    animToPlay = 'fallBCK'
            elif attack in ('pickpocket',):
                animToPlay = 'cringe'
            elif attack in ('fountainpen',):
                animToPlay = 'conked'
                timeToWait = 5.0
            self.cr.playGame.getPlace().fsm.request('stop')
            self.b_setAnimState(animToPlay)
            base.taskMgr.doMethodLater(timeToWait, self.__attackReactionDone, 'LT.attackReactionDone')
        return

    def __attackReactionDone(self, task):
        self.cr.playGame.hood.loader.place.fsm.request('walk')
        self.b_setAnimState('neutral')
        return Task.done

    def enableAvatarControls(self):
        self.walkControls.enableAvatarControls()
        self.accept('control', self.updateMovementKeymap, ['jump', 1])
        self.accept('control-up', self.updateMovementKeymap, ['jump', 0])
        taskMgr.add(self.movementTask, 'avatarMovementTask')
        self.avatarMovementEnabled = True
        self.playMovementSfx(None)
        return

    def disableAvatarControls(self):
        self.walkControls.disableAvatarControls()
        self.ignore('arrow_up')
        self.ignore('arrow_up-up')
        self.ignore('arrow_down')
        self.ignore('arrow_down-up')
        self.ignore('arrow_left')
        self.ignore('arrow_left-up')
        self.ignore('arrow_right')
        self.ignore('arrow_right-up')
        self.ignore('control')
        self.ignore('control-up')
        taskMgr.remove('avatarMovementTask')
        self.isMoving_forward = False
        self.isMoving_side = False
        self.isMoving_back = False
        self.isMoving_jump = False
        self.avatarMovementEnabled = False
        self.playMovementSfx(None)
        for k, _ in self.movementKeymap.items():
            self.updateMovementKeymap(k, 0)

        return

    def updateMovementKeymap(self, key, value):
        self.movementKeymap[key] = value

    def getMovementKeyValue(self, key):
        return self.movementKeymap[key]

    def playMovementSfx(self, movement):
        if movement == 'run':
            self.walkSfx.stop()
            self.runSfx.play()
        elif movement == 'walk':
            self.runSfx.stop()
            self.walkSfx.play()
        else:
            self.runSfx.stop()
            self.walkSfx.stop()

    def __forward(self):
        self.resetHeadHpr()
        self.stopLookAround()
        if self.getHealth() < 1:
            self.playMovementSfx('walk')
            self.setPlayRate(1.2, 'dwalk')
            self.setAnimState('deadWalk')
        else:
            self.playMovementSfx('run')
            self.setAnimState('run')
        self.isMoving_side = False
        self.isMoving_back = False
        self.isMoving_forward = True
        self.isMoving_jump = False

    def __turn(self):
        self.resetHeadHpr()
        self.stopLookAround()
        self.playMovementSfx('walk')
        if self.getHealth() < 1:
            self.setPlayRate(1.2, 'dwalk')
            self.setAnimState('deadWalk')
        else:
            self.setPlayRate(1.0, 'walk')
            self.setAnimState('walk')
        self.isMoving_forward = False
        self.isMoving_back = False
        self.isMoving_side = True
        self.isMoving_jump = False

    def __reverse(self):
        self.resetHeadHpr()
        self.stopLookAround()
        self.playMovementSfx('walk')
        if self.getHealth() < 1:
            self.setPlayRate(-1.0, 'dwalk')
            self.setAnimState('deadWalk')
        else:
            self.setAnimState('walkBack')
        self.isMoving_side = False
        self.isMoving_forward = False
        self.isMoving_back = True
        self.isMoving_jump = False

    def __jump(self):
        self.playMovementSfx(None)
        if base.localAvatar.getHealth() > 0:
            if self.playingAnim == 'run' or self.playingAnim == 'walk':
                self.b_setAnimState('leap')
            else:
                self.b_setAnimState('jump')
        self.isMoving_side = False
        self.isMoving_forward = False
        self.isMoving_back = False
        self.isMoving_jump = True
        return

    def __neutral(self):
        self.resetHeadHpr()
        self.startLookAround()
        self.playMovementSfx(None)
        if base.localAvatar.getHealth() > 0:
            self.setAnimState('neutral')
        else:
            self.setPlayRate(1.0, 'dneutral')
            self.setAnimState('deadNeutral')
        self.isMoving_side = False
        self.isMoving_forward = False
        self.isMoving_back = False
        self.isMoving_jump = False
        return

    def movementTask(self, task):
        if self.getMovementKeyValue('jump') == 1:
            if not self.walkControls.isAirborne:
                if self.walkControls.mayJump:
                    self.__jump()
                    self.hasDoneJump = True
                elif self.hasDoneJump:
                    if self.getHealth() > 0:
                        self.b_setAnimState('Happy')
                    self.hasDoneJump = False
        elif not self.walkControls.isAirborne:
            if self.hasDoneJump:
                if self.getHealth() > 0:
                    self.b_setAnimState('Happy')
                self.hasDoneJump = False
        return task.cont

    def startTrackAnimToSpeed(self):
        base.taskMgr.add(self.trackAnimToSpeed, self.uniqueName('trackAnimToSpeed'))

    def stopTrackAnimToSpeed(self):
        base.taskMgr.remove(self.uniqueName('trackAnimToSpeed'))

    def trackAnimToSpeed(self, task):
        speed, rotSpeed, slideSpeed = self.walkControls.getSpeeds()
        state = None
        if self.getHealth() > 0:
            state = 'Happy'
        else:
            state = 'Sad'
        if state != self.lastState:
            self.lastState = state
            self.b_setAnimState(state)
            if state == 'Sad':
                self.setWalkSpeedSlow()
            else:
                self.setWalkSpeedNormal()
        action = self.setSpeed(speed, rotSpeed)
        if action != self.lastAction:
            self.lastAction = action
            if action == CIGlobals.WALK_INDEX or action == CIGlobals.REVERSE_INDEX:
                self.resetHeadHpr()
                self.stopLookAround()
                self.playMovementSfx('walk')
            elif action == CIGlobals.RUN_INDEX:
                self.resetHeadHpr()
                self.stopLookAround()
                self.playMovementSfx('run')
            else:
                self.resetHeadHpr()
                self.startLookAround()
                self.playMovementSfx(None)
        return task.cont

    def createLaffMeter(self):
        r, g, b, _ = self.getHeadColor()
        animal = self.getAnimal()
        maxHp = self.getMaxHealth()
        hp = self.getHealth()
        self.laffMeter.generate(r, g, b, animal, maxHP=maxHp, initialHP=hp)
        self.laffMeter.start()

    def disableLaffMeter(self):
        self.laffMeter.stop()
        self.laffMeter.disable()

    def deleteLaffMeter(self):
        self.laffMeter.delete()

    def setLoadout(self, gagIds):
        DistributedToon.setLoadout(self, gagIds)
        if base.cr.playGame.getPlace() and base.cr.playGame.getPlace().fsm.getCurrentState().getName() == 'shtickerBook':
            if hasattr(base.cr.playGame.getPlace(), 'shtickerBookStateData'):
                if base.cr.playGame.getPlace().shtickerBookStateData.fsm.getCurrentState().getName() == 'inventoryPage':
                    base.cr.playGame.getPlace().shtickerBookStateData.gui.fsm.request('idle')

    def enablePies(self, andKeys = 0):
        if self.avatarMovementEnabled and andKeys:
            self.enablePieKeys()
        self.backpack = DistributedToon.getBackpack(self)
        self.invGui = InventoryGui()
        self.invGui.createGui()
        self.invGui.setBackpack(self.backpack)
        for gag in self.backpack.getGags():
            gag.setAvatar(self)

        self.backpack.setGagGUI(self.invGui)
        if self.backpack.getCurrentGag():
            self.invGui.setWeapon(self.backpack.getCurrentGag().getName(), playSound=False)

    def enablePieKeys(self):
        if self.pieThrowBtn:
            if not self.backpack:
                self.backpack = DistributedToon.getBackpack(self)
            self.pieThrowBtn.bind(DGG.B1PRESS, self.startGag)
            self.pieThrowBtn.bind(DGG.B1RELEASE, self.throwGag)
        self.accept('delete', self.startGag)
        self.accept('delete-up', self.throwGag)

    def disablePieKeys(self):
        if self.pieThrowBtn:
            self.pieThrowBtn.unbind(DGG.B1PRESS)
            self.pieThrowBtn.unbind(DGG.B1RELEASE)
        self.ignore('delete')
        self.ignore('delete-up')

    def disablePies(self):
        self.disablePieKeys()
        self.invGui.deleteGui()
        if hasattr(self, 'backpack'):
            if self.backpack:
                self.backpack.setCurrentGag(None)
        return

    def setWeaponType(self, weaponType):
        enableKeysAgain = 0
        if weaponType != self.weaponType:
            enableKeysAgain = 1
        self.weaponType = weaponType
        if enableKeysAgain:
            self.disablePieKeys()
            self.enablePieKeys()

    def createMoney(self):
        self.moneyGui.createGui()
        self.moneyGui.update(self.money)

    def handleMoneyChanged(self):
        self.moneyGui.update()

    def disableMoney(self):
        self.moneyGui.deleteGui()

    def resetHeadHpr(self):
        self.b_lookAtObject(0, 0, 0, blink=0)

    def startGag(self, start = True):
        if not self.backpack or not self.backpack.getCurrentGag():
            return
        if self.backpack.getSupply() > 0:
            if self.pieThrowBtn:
                self.pieThrowBtn.unbind(DGG.B1PRESS)
            if self.backpack.getActiveGag():
                if self.backpack.getActiveGag().getState() != GagState.LOADED:
                    return
            self.ignore('delete')
            self.backpack.getCurrentGag().setAvatar(self)
            self.resetHeadHpr()
            self.b_gagStart(self.backpack.getCurrentGag().getID())

    def throwGag(self, start = True):
        if not self.backpack or not self.backpack.getCurrentGag() or not self.backpack.getActiveGag():
            return
        if self.backpack.getSupply() > 0:
            if self.pieThrowBtn:
                self.pieThrowBtn.unbind(DGG.B1RELEASE)
            self.ignore('delete-up')
            if self.backpack.getActiveGag().getType() == GagType.SQUIRT and self.backpack.getActiveGag().getName() == CIGlobals.SeltzerBottle:
                self.b_gagRelease(self.backpack.getActiveGag().getID())
            else:
                self.b_gagThrow(self.backpack.getActiveGag().getID())
            activeGag = self.backpack.getActiveGag()
            if not activeGag:
                activeGag = self.backpack.getCurrentGag()
            if not activeGag.doesAutoRelease():
                Sequence(Wait(0.75), Func(self.releaseGag), Wait(0.3), Func(self.enablePieKeys)).start()

    def releaseGag(self):
        if not self.backpack or not self.backpack.getActiveGag():
            return
        if self.backpack.getSupply() > 0:
            gag = self.backpack.getActiveGag()
            if not gag:
                gag = self.backpack.getCurrentGag()
            if gag.getState() != GagState.RELEASED:
                gagName = gag.getName()
                self.b_gagRelease(GagGlobals.getIDByName(gagName))

    def checkSuitHealth(self, suit):
        pass

    def handleLookSpot(self, hpr):
        h, p, r = hpr
        self.d_lookAtObject(h, p, r, blink=1)

    def showPieButton(self):
        geom = CIGlobals.getDefaultBtnGeom()
        self.pieThrowBtn = DirectButton(geom=geom, geom_scale=(0.75, 1, 1), text='Throw Gag', text_scale=0.05, text_pos=(0, -0.01), relief=None, parent=base.a2dTopCenter, pos=(0, 0, -0.1))
        self.pieThrowBtn.setBin('gui-popup', 60)
        return

    def hidePieButton(self):
        self.pieThrowBtn.removeNode()
        self.pieThrowBtn = None
        return

    def showBookButton(self, inBook = 0):
        self.book_gui = loader.loadModel('phase_3.5/models/gui/sticker_open_close_gui.bam')
        self.book_btn = DirectButton(geom=(self.book_gui.find('**/BookIcon_CLSD'), self.book_gui.find('**/BookIcon_OPEN'), self.book_gui.find('**/BookIcon_RLVR')), relief=None, pos=(-0.175, 0, 0.163), command=self.bookButtonClicked, scale=(0.7, 0.8, 0.8), parent=base.a2dBottomRight)
        self.book_btn.setBin('gui-popup', 60)
        if inBook:
            self.book_btn['geom'] = (self.book_gui.find('**/BookIcon_OPEN'), self.book_gui.find('**/BookIcon_CLSD'), self.book_gui.find('**/BookIcon_RLVR2'))
            self.book_btn['command'] = self.bookButtonClicked
            self.book_btn['extraArgs'] = [0]
        return

    def hideBookButton(self):
        if hasattr(self, 'book_gui'):
            self.book_gui.removeNode()
            del self.book_gui
        if hasattr(self, 'book_btn'):
            self.book_btn.destroy()
            del self.book_btn

    def bookButtonClicked(self, openIt = 1):
        if openIt:
            base.cr.playGame.getPlace().fsm.request('shtickerBook')
        else:
            base.cr.playGame.getPlace().shtickerBookStateData.finished('resume')

    def startMonitoringHP(self):
        taskMgr.add(self.monitorHealth, 'localToon-monitorHealth')

    def monitorHealth(self, task):
        if self.isDead():
            base.taskMgr.remove('LT.attackReactionDone')
            if self.cr.playGame.hood.id != ZoneUtil.getHoodId(self.zoneId):
                self.cr.playGame.getPlace().fsm.request('died', [{}, self.diedStateDone])
            return task.done
        return task.cont

    def stopMonitoringHP(self):
        taskMgr.remove('localToon-monitorHealth')

    def setHealth(self, hp):
        if hp > 0 and self.getHealth() < 1:
            if self.cr.playGame.getPlace():
                if self.cr.playGame.getPlace().fsm.getCurrentState().getName() == 'walk':
                    if self.cr.playGame.getPlace().walkStateData.fsm.getCurrentState().getName() == 'deadWalking':
                        self.cr.playGame.getPlace().walkStateData.fsm.request('walking')
            if self.animFSM.getCurrentState().getName() == 'deadNeutral':
                self.playMovementSfx(None)
                self.b_setAnimState('neutral')
            elif self.animFSM.getCurrentState().getName() == 'deadWalk':
                self.playMovementSfx('run')
                self.b_setAnimState('run')
        DistributedToon.setHealth(self, hp)
        return

    def diedStateDone(self, requestStatus):
        hood = self.cr.playGame.hood.id
        if hood == CIGlobals.BattleTTC:
            hood = CIGlobals.ToontownCentral
        toZone = ZoneUtil.getZoneId(hood)
        if self.zoneId != toZone:
            requestStatus = {'zoneId': toZone,
             'hoodId': hood,
             'where': ZoneUtil.getWhereName(toZone),
             'avId': self.doId,
             'loader': ZoneUtil.getLoaderName(toZone),
             'shardId': None,
             'wantLaffMeter': 1,
             'how': 'teleportIn'}
            self.cr.playGame.getPlace().doneStatus = requestStatus
            messenger.send(self.cr.playGame.getPlace().doneEvent)
        else:
            return
        return

    def teleportToCT(self):
        toZone = CIGlobals.CogTropolisId
        hood = CIGlobals.CogTropolis
        requestStatus = {'zoneId': toZone,
         'hoodId': hood,
         'where': ZoneUtil.getWhereName(toZone),
         'avId': self.doId,
         'loader': ZoneUtil.getLoaderName(toZone),
         'shardId': None,
         'wantLaffMeter': 1,
         'how': 'teleportIn'}
        self.cr.playGame.getPlace().fsm.request('teleportOut', [requestStatus])
        return

    def createChatInput(self):
        self.chatInput.load()
        self.chatInput.enter()

    def disableChatInput(self):
        self.chatInput.exit()
        self.chatInput.unload()

    def collisionsOn(self):
        self.controlManager.collisionsOn()

    def collisionsOff(self):
        self.controlManager.collisionsOff()

    def generate(self):
        DistributedToon.generate(self)

    def delete(self):
        DistributedToon.delete(self)
        self.deleteLaffMeter()

    def disable(self):
        base.camLens.setMinFov(CIGlobals.OriginalCameraFov / (4.0 / 3.0))
        self.friendsList.destroy()
        self.friendsList = None
        self.positionExaminer.delete()
        self.positionExaminer = None
        self.disablePicking()
        self.stopMonitoringHP()
        taskMgr.remove('resetHeadColorAfterFountainPen')
        taskMgr.remove('LT.attackReactionDone')
        self.stopLookAround()
        DistributedToon.disable(self)
        self.disableAvatarControls()
        self.disableLaffMeter()
        self.disablePies()
        self.disableChatInput()
        self.weaponType = None
        self.pieType = None
        self.myBattle = None
        self.ignore('gotLookSpot')
        return

    def announceGenerate(self):
        DistributedToon.announceGenerate(self)
        self.setupPicker()
        self.setupControls()
        self.startLookAround()
        self.friendRequestManager.watch()
        self.accept('gotLookSpot', self.handleLookSpot)

    def printAvPos(self):
        print 'Pos: %s, Hpr: %s' % (self.getPos(), self.getHpr())
Пример #18
0
class Menu:
    def __init__(self, otherProperties, baseClass):
        self.text_pointers = []
        self.keyboard = Controller()
        self.IsFullScreen = False
        self.others = otherProperties
        self.baseClass = baseClass

    def __del__(self):
        print('Destructor called')

    def start(self):

        self.fullScreenShape = loader.loadModel("models/fullscreen_shape.bam")
        self.fullScreenShape.reparentTo(render)
        self.fullScreenShape.setScale(0.25, 0.25, 0.25)
        self.fullScreenShape.setPos(-1.5, 6, -1)
        self.fondo = loader.loadModel("models/fondo_menu.bam")
        self.fondo.reparentTo(render)
        self.fondo.setScale(0.27, 0.01, 0.32)
        self.fondo.setPos(0, 7, 0)
        font = loader.loadFont('./fonts/comic/comic.ttf')
        self.TextInsertName = OnscreenText(font=font,
                                           text='Ingrese su nombre:',
                                           pos=(-0.5, 0.02),
                                           scale=0.07,
                                           fg=(143 / 255, 250 / 255, 2 / 255,
                                               1))
        self.TextFullScreen = OnscreenText(font=font,
                                           text='Fulscreen:',
                                           pos=(-0.99, -0.67),
                                           scale=0.04,
                                           fg=(143 / 255, 250 / 255, 2 / 255,
                                               1))
        self.TextInsertNameInput = DirectEntry(text="",
                                               scale=.05,
                                               numLines=1,
                                               focus=1)
        self.ButtonInsertName = DirectButton(text=("Insertar nombre"),
                                             scale=.05,
                                             pos=(0.25, 0, -0.10),
                                             command=self.make_player)
        self.InvisibleButton = DirectButton(text=("*"),
                                            scale=.05,
                                            pos=(-1, 5, -0.73),
                                            command=self.setFullScreen)
        self.InvisibleButton.bind(WITHIN, command=self.mouseOver)
        self.fullScreenShape.reparentTo(render)
        self.fondo.reparentTo(render)
        self.TextInsertNameInput.show()
        self.fullScreenShape.show()
        self.fondo.show()
        self.TextInsertName.show()
        self.TextFullScreen.show()
        self.ButtonInsertName.show()
        self.InvisibleButton.show()

    def stop(self):
        self.fullScreenShape.hide()
        self.fondo.remove_node()
        self.TextInsertName.hide()
        self.TextFullScreen.hide()
        self.ButtonInsertName.hide()
        self.InvisibleButton.hide()
        self.TextInsertNameInput.hide()
        self.keyboard.press('3')
        self.keyboard.release('3')
        self.__del__()

    def mouseOver(self, argumento):
        rotation_interval = self.fullScreenShape.hprInterval(
            10, Vec3(360, 0, 0))
        rotation_interval.start()

    def setFullScreen(self):
        props = self.others
        if (self.IsFullScreen == True):
            props.fullscreen = False
            self.IsFullScreen = False
        else:
            props.fullscreen = True
            self.IsFullScreen = True
        self.baseClass.win.requestProperties(props)

    def make_player(self):
        self.player = player.Player(self.TextInsertNameInput.get())
        self.player.savefile()
        self.stop()
class LabTask03(DirectObject):
  
  #define the state of the game and level
  gameState = 'INIT'
  gameLevel = 1
  cameraState = 'STARTUP'
  count = 0
  attempts = 3
  posX = -200
  posY = 20
  posZ = 30
  score = 0
  contacts = 0
  pause = False
  fire = True
  desiredCamPos = Vec3(-200,30,20)

  def __init__(self):
    self.imageObject = OnscreenImage(image = 'models/splashscreen.png', pos=(0,0,0), scale=(1.4,1,1))
    preloader = Preloader()
    self.musicLoop = loader.loadSfx("music/loop/EndlessBliss.mp3")
    self.snowmansHit = loader.loadSfx("music/effects/snowball_hit.wav")
    self.candleThrow = loader.loadSfx("music/effects/snowball_throw.wav")
    self.presentHit = loader.loadSfx("music/effects/present_hit.wav")
    self.loseSound = loader.loadSfx("music/effects/Failure-WahWah.mp3")
    self.winSound = loader.loadSfx("music/effects/Ta Da-SoundBible.com-1884170640.mp3")
    self.nextLevelSound = loader.loadSfx("music/effects/button-17.wav")
    self.loseScreen = OnscreenImage(image = 'models/losescreen.png', pos=(0,0,0), scale=(1.4,1,1))
    self.loseScreen.hide()
    self.winScreen = OnscreenImage(image = 'models/winscreen.png', pos=(0,0,0), scale=(1.4,1,1))
    self.winScreen.hide()
    self.helpScreen = OnscreenImage(image = 'models/helpscreen.jpg', pos=(0,0,0.1), scale=(1,1,0.8))
    self.helpScreen.hide()
    self.backBtn = DirectButton(text=("Back"), scale = 0.1,  pos = (0,0,-0.8), command = self.doBack)
    self.retryBtn = DirectButton(text="Retry", scale = 0.1, pos = (0,0,0), command = self.doRetry)
    self.retryBtn.hide()
    self.menuBtn = DirectButton(text="Main Menu", scale = 0.1, pos = (0,0,0), command = self.doBack)
    self.menuBtn.hide()
    self.backBtn.hide()
    base.setBackgroundColor(0.1, 0.1, 0.8, 1)
    #base.setFrameRateMeter(True)
    
    # Position the camera
    base.cam.setPos(0, 30, 20)
    base.cam.lookAt(0, 30, 0)

    # Light
    alight = AmbientLight('ambientLight')
    alight.setColor(Vec4(0.5, 0.5, 0.5, 1))
    alightNP = render.attachNewNode(alight)

    dlight = DirectionalLight('directionalLight')
    dlight.setDirection(Vec3(1, 1, -1))
    dlight.setColor(Vec4(0.7, 0.7, 0.7, 1))
    dlightNP = render.attachNewNode(dlight)

    render.clearLight()
    render.setLight(alightNP)
    render.setLight(dlightNP)

    # Input
    self.accept('escape', self.doExit)
    self.accept('r', self.doReset)
    self.accept('f1', self.toggleWireframe)
    self.accept('f2', self.toggleTexture)
    self.accept('f3', self.toggleDebug)
    self.accept('f5', self.doScreenshot)
    self.accept('f', self.doShoot, [True])
    self.accept('p', self.doPause)

    inputState.watchWithModifiers('forward', 'w')
    inputState.watchWithModifiers('left', 'a')
    inputState.watchWithModifiers('reverse', 's')
    inputState.watchWithModifiers('right', 'd')
    inputState.watchWithModifiers('turnLeft', 'q')
    inputState.watchWithModifiers('turnRight', 'e')
    
    inputState.watchWithModifiers('moveLineUp', 'i')
    inputState.watchWithModifiers('moveLineDown','k')
    inputState.watchWithModifiers('moveLineRight','l')
    inputState.watchWithModifiers('moveLineLeft','j')
    
    self.font = loader.loadFont('models/SHOWG.TTF')
    self.font.setPixelsPerUnit(60)
    self.attemptText = OnscreenText(text='', pos = (0.9,0.8), scale = 0.07, font = self.font)
    self.levelText = OnscreenText(text='', pos=(-0.9,0.9), scale = 0.07, font = self.font )
    self.scoreText = OnscreenText(text='', pos = (0.9,0.9), scale = 0.07, font = self.font)
    self.text = OnscreenText(text = '', 
                              pos = (0, 0), scale = 0.07, font = self.font)
    self.pauseText = OnscreenText(text='P: Pause', pos= (0.9,0.7), scale = 0.05, font = self.font)
    self.pauseText.hide()
    # Task
    taskMgr.add(self.update, 'updateWorld')

    # Physics
    self.setup()

  # _____HANDLER_____
  
  def doRetry(self):
    self.loseScreen.hide()
    self.levelText.clearText()
    self.scoreText.clearText()
    self.attemptText.clearText()
    self.playGame()
    self.retryBtn.hide()
    self.cleanup()
    self.setup()
    

  def doExit(self):
    self.cleanup()
    sys.exit(1)

  def doReset(self):
    self.attempts = 3
    self.cameraState = 'STARTUP'
    base.cam.setPos(0,30,20)
    self.arrow.removeNode()
    self.scoreText.clearText()
    self.levelText.clearText()
    self.attemptText.clearText()
    self.cleanup()
    self.setup()
    
  def toggleWireframe(self):
    base.toggleWireframe()

  def toggleTexture(self):
    base.toggleTexture()

  def toggleDebug(self):
    if self.debugNP.isHidden():
      self.debugNP.show()
    else:
      self.debugNP.hide()

  def doScreenshot(self):
    base.screenshot('Bullet')
    
    
  def doShoot(self, ccd):
    if(self.fire and self.attempts > 0 and self.gameState == 'PLAY'):
      self.cameraState = 'LOOK'
      self.fire = False
      self.candleThrow.play()
      self.attempts -= 1
      #get from/to points from mouse click
      ## pMouse = base.mouseWatcherNode.getMouse()
      ## pFrom = Point3()
      ## pTo = Point3()
      ## base.camLens.extrude(pMouse, pFrom, pTo)
      
      ## pFrom = render.getRelativePoint(base.cam, pFrom)
      ## pTo = render.getRelativePoint(base.cam, pTo)
      
      # calculate initial velocity
      v = self.pTo - self.pFrom
      ratio = v.length() / 40
      v.normalize()
      v *= 70.0 * ratio
      torqueOffset = random.random() * 10
      
      #create bullet
      shape = BulletSphereShape(0.5)
      shape01 = BulletSphereShape(0.5)
      shape02 = BulletSphereShape(0.5)
      shape03 = BulletSphereShape(0.5)
      body = BulletRigidBodyNode('Candle')
      bodyNP = self.worldNP.attachNewNode(body)
      bodyNP.node().addShape(shape, TransformState.makePos(Point3(0,0,0)))
      bodyNP.node().addShape(shape01, TransformState.makePos(Point3(0,0.5,-0.5)))
      bodyNP.node().addShape(shape02,TransformState.makePos(Point3(0,1,-1)))
      bodyNP.node().addShape(shape03,TransformState.makePos(Point3(0,1.5,-1.5)))
      bodyNP.node().setMass(100)
      bodyNP.node().setFriction(1.0)
      bodyNP.node().setLinearVelocity(v)
      bodyNP.node().applyTorque(v*torqueOffset)
      bodyNP.setPos(self.pFrom)
      bodyNP.setCollideMask(BitMask32.allOn())
      
      visNP = loader.loadModel('models/projectile.X')
      visNP.setScale(0.7)
      visNP.clearModelNodes()
      visNP.reparentTo(bodyNP)
      
      #self.bird = bodyNP.node()
      
      if ccd:
          bodyNP.node().setCcdMotionThreshold(1e-7)
          bodyNP.node().setCcdSweptSphereRadius(0.5)
          
      self.world.attachRigidBody(bodyNP.node())
      
      #remove the bullet again after 1 sec
      self.bullets = bodyNP
      taskMgr.doMethodLater(5, self.removeBullet, 'removeBullet', extraArgs=[bodyNP], 
                            appendTask = True)
      
    
  def removeBullet(self, bulletNP, task):
    self.cameraState = 'STAY'
    self.fire = True
    self.world.removeRigidBody(bulletNP.node())
    bulletNP.removeNode()
    if(self.attempts <= 0 and len(self.snowmans)>0):
      self.gameState = 'LOSE'
      self.doContinue()
      
    return task.done

  # ____TASK___

  def processInput(self, dt):
    force = Vec3(0, 0, 0)
    torque = Vec3(0, 0, 0)
    #print self.pTo.getY()
    if inputState.isSet('forward'):
      if(self.pTo.getZ() < 40):
        self.pTo.addZ(0.5)
    if inputState.isSet('reverse'):
      if(self.pTo.getZ() > 0 ):
        self.pTo.addZ(-0.5)
    if inputState.isSet('left'):
      if(self.pTo.getY() < 100):
        self.pTo.addY(0.5)
        self.arrow.setScale(self.arrow.getSx(),self.arrow.getSy()-0.006,self.arrow.getSz())
    if inputState.isSet('right'):
      if(self.pTo.getY() > 60):
        self.pTo.addY(-0.5)
        self.arrow.setScale(self.arrow.getSx(),self.arrow.getSy()+0.006,self.arrow.getSz())
        
    self.arrow.lookAt(self.pTo)
    
  def processContacts(self, dt):
      for box in self.boxes:
        for snowman in self.snowmans:
          result = self.world.contactTestPair(box, snowman.node())
      
          if (result.getNumContacts() > 0):
            self.snowmansHit.play()
            self.score += 100
            self.text.setPos(0,0.7)
            self.text.setText("HIT")
            self.snowmans.remove(snowman)
            self.world.removeRigidBody(snowman.node())
            snowman.removeNode()
            if(len(self.snowmans)  <= 0):
              self.gameState = "NEXT"
              self.text.setText('Nice! Press space to continue')

              
      for box in self.boxes:
        for present in self.presents:
          result01 = self.world.contactTestPair(box,present.node())
          if(result01.getNumContacts() > 0):
            self.presents.remove(present)
            self.world.removeRigidBody(present.node())
            present.removeNode()
            self.presentHit.play()
            self.score += 500
            
  def doContinue(self):
    if(self.gameState == 'INIT'):
      self.gameState = 'MENU'
      self.text.clearText()
      self.musicLoop.setLoop(True)
      self.musicLoop.setVolume(0.5)
      self.musicLoop.play()
      self.startBtn = DirectButton(text=("Play"), scale = 0.1, pos = (0,0,0),command=self.playGame)
      self.helpBtn = DirectButton(text=("Help"), scale = 0.1, pos = (0,0,-0.2),command=self.help)
      self.exitBtn = DirectButton(text=("Exit"), scale = 0.1,  pos = (0,0,-0.4), command = self.doExit)
      return
    
    if self.gameState == 'NEXT':
      self.nextLevelSound.play()
      self.fire = True
      self.gameLevel += 1
      self.score += (self.attempts * 100)
      self.doReset()
      self.gameState = 'PLAY'
      return
    
    if self.gameState == 'LOSE':
      self.loseSound.play()
      self.arrow.removeNode()
      self.loseScreen.show()
      self.levelText.hide()
      self.attemptText.hide()
      self.scoreText.hide()
      self.text.hide()
      self.pauseText.hide()
      self.retryBtn.show()
      return
    
    if self.gameState == 'WIN':
      self.levelText.hide()
      self.attemptText.hide()
      self.scoreText.clearText()
      self.scoreText.setPos(0,0.6)
      self.scoreText.setText("%s"%self.score)
      self.winScreen.show()
      self.winSound.play()
      self.menuBtn.show()
      self.pauseText.hide()
      return
      
    
  def playGame(self):
    print "Play Game"
    self.attempts = 3
    self.score = 0
    self.gameLevel = 1
    self.gameState = 'PLAY'
    self.musicLoop.setVolume(0.3)
    self.imageObject.hide()
    self.startBtn.hide()
    self.exitBtn.hide()
    self.helpBtn.hide()
    self.cleanup()
    self.setup()
    
  def doBack(self):
    self.gameState = 'MENU'
    self.scoreText.setPos(0.9,0.9)
    self.scoreText.hide()
    self.imageObject.show()
    self.startBtn.show()
    self.exitBtn.show()
    self.helpBtn.show()
    self.helpScreen.hide()
    self.backBtn.hide()
    self.menuBtn.hide()
    self.winScreen.hide()
    
  def help(self):
    self.gameState = 'HELP'
    self.startBtn.hide()
    self.exitBtn.hide()
    self.helpBtn.hide()
    self.backBtn.show()
    self.helpScreen.show()
    return
    
  def doPause(self):
    self.pause  = not self.pause
    if(self.pause):
      self.text.setText("Pause")
    else:
      self.text.clearText()
      

  def update(self, task):

    dt = globalClock.getDt()
    if(not self.pause):
      if self.gameState == 'INIT':
        self.text.setPos(0,0)
        self.text.setText('Press space to continue')
        self.accept('space',self.doContinue)
          
      if self.gameState == 'PLAY':
        #print self.posZ
        #if(self.posX < -120):
        #  self.posX += 0.03
        #  self.posZ -= 0.02
        #elif(self.posZ < 70):
        #  self.posZ += 0.02;
        #elif(self.posZ > 70 and self.posX > -120):
        #  self.posZ -= 0.02
        #  self.posX -= 0.03
        #base.cam.setPos(self.posX, self.posZ, self.posY)
        self.levelText.setText('Level: %s'%self.gameLevel)
        self.attemptText.setText('Tries Left: %s'%self.attempts)
        self.scoreText.setText('Score: %s'%self.score)
        self.pauseText.show()
        self.processContacts(dt)
        self.world.doPhysics(dt, 20, 1.0/180.0)
        #self.drawLines()
        self.processInput(dt)
        
        if self.cameraState == 'STARTUP':
          oldPos = base.cam.getPos()
          pos = (oldPos*0.9) + (self.desiredCamPos*0.1)
          base.cam.setPos(pos)
          base.cam.lookAt(0,30,0)
        elif self.cameraState == 'STAY':
          #oldPos = base.cam.getPos()
          #currPos = (oldPos*0.9) + (self.desiredCamPos*0.1)
          #base.cam.setPos(currPos)
          base.cam.lookAt(0,30,0)
        elif self.cameraState == 'LOOK':
          base.cam.lookAt(self.bullets)
          #base.cam.setPos(-200,self.bullets.getZ(),20)
        
      if self.gameState == 'NEXT':
        self.world.doPhysics(dt, 20, 1.0/180.0)
        

      ## self.raycast()
    
    return task.cont
      
  def raycast(self):
    # Raycast for closest hit
    tsFrom = TransformState.makePos(Point3(0,0,0))
    tsTo = TransformState.makePos(Point3(10,0,0))
    shape = BulletSphereShape(0.5)
    penetration = 1.0
    result = self.world.sweepTestClosest(shape, tsFrom, tsTo, penetration)
    if result.hasHit():
        torque = Vec3(10,0,0)
        force = Vec3(0,0,100)
        
        ## for hit in result.getHits():
            ## hit.getNode().applyTorque(torque)
            ## hit.getNode().applyCentralForce(force)
        result.getNode().applyTorque(torque)
        result.getNode().applyCentralForce(force)
        ## print result.getClosestHitFraction()
        ## print result.getHitFraction(), \
            ## result.getNode(), \
            ## result.getHitPos(), \
            ## result.getHitNormal()

  def cleanup(self):
    self.world = None
    self.worldNP.removeNode()
    self.arrow.removeNode()
    self.lines.reset()
    self.text.clearText()

  def setup(self):
    self.attemptText.show()
    self.levelText.show()
    self.scoreText.show()
    self.text.show()
    
    self.worldNP = render.attachNewNode('World')

    # World
    self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
    self.debugNP.show()

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())
    
    #arrow
    self.scaleY = 10
    self.arrow = loader.loadModel('models/arrow.X')
    self.arrow.setScale(0.5,0.5,0.5)
    self.arrow.setAlphaScale(0.5)
    #self.arrow.setTransparency(TransparencyAttrib.MAlpha) 
    self.arrow.reparentTo(render)
    
    #SkyBox
    skybox = loader.loadModel('models/skybox.X')
    skybox.reparentTo(render)

    # Ground
    shape = BulletPlaneShape(Vec3(0, 0, 1), 0)

    np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
    np.node().addShape(shape)
    np.setPos(0, 0, -1)
    np.setCollideMask(BitMask32.allOn())

    self.world.attachRigidBody(np.node())
    
    visualNP = loader.loadModel('models/ground.X')
    visualNP.clearModelNodes()
    visualNP.reparentTo(np)
    
    #some boxes
    self.boxes = []
    self.snowmans = []
    self.platforms = []
    self.presents = []
    #TODO: Make a table
    #Table Top
    #self.createBox(Vec3(),Vec3())
    if(self.gameLevel == 1):
      self.createBox(Vec3(5,7,1),Vec3(0,5,10),1.0)
      #2 legs
      self.createBox(Vec3(4,1,4),Vec3(0,11,5),1.0)
      self.createBox(Vec3(4,1,4),Vec3(0,-1,5),1.0)
      
      # Pigs
      self.createSnowman(2.0,Vec3(0, 5, 2.0),10.0)
      self.createSnowman(1.5, Vec3(0,-10,4.0),10.0)
      
    if(self.gameLevel == 2):
      #table01
      self.createBox(Vec3(5,14,1),Vec3(0,-2,12),2.0)
      self.createBox(Vec3(5,7,1),Vec3(0,5,10),2.0)
      self.createBox(Vec3(4,1,4),Vec3(0,11,5),1.0)
      self.createBox(Vec3(4,1,4),Vec3(0,-1,5),1.0)
      #table02
      self.createBox(Vec3(5,7,1),Vec3(0,-9,10),2.0)
      self.createBox(Vec3(4,1,4),Vec3(0,-3,5),1.0)
      self.createBox(Vec3(4,1,4),Vec3(0,-15,5),1.0)
      #table03
      self.createBox(Vec3(1,1,1), Vec3(0,-1,14), 2.0)
      self.createBox(Vec3(1,1,1), Vec3(0,-3,14), 2.0)
      self.createBox(Vec3(1,1,1), Vec3(0,3,14), 2.0)
      self.createBox(Vec3(1,1,1), Vec3(0,-5,14), 2.0)
      self.createBox(Vec3(1,1,1), Vec3(0,5,14), 2.0)
      #pigs
      self.createSnowman(2.0,Vec3(0, 5, 2.0),10.0)
      self.createSnowman(2.0, Vec3(0,-9,2.0), 10.0)
      self.createSnowman(2.0,Vec3(0,-23,2.0),10.0)
      
    if(self.gameLevel == 3):
      #table01
      self.createBox(Vec3(4,2,2),Vec3(0,12,12),1.0)
      self.createBox(Vec3(4,1,4),Vec3(0,11,5),1.0)
      self.createBox(Vec3(4,1,4),Vec3(0,13,5),1.0)
      #table02
      self.createBox(Vec3(4,2,2),Vec3(0,-15,12),1.0)
      self.createBox(Vec3(4,1,4),Vec3(0,-14,5),1.0)
      self.createBox(Vec3(4,1,4),Vec3(0,-16,5),1.0)
      #table03
      self.createBox(Vec3(4,10,1),Vec3(0,-1,12),1.0)
      self.createBox(Vec3(4,10,1),Vec3(0,-1,14),1.0)
      self.createBox(Vec3(4,2,4),Vec3(0,-2,5),0.1)
      #table04
      self.createPlatform(Vec3(4,8,1),Vec3(0,7,16),1.0)
      self.createPlatform(Vec3(4,8,1),Vec3(0,-9,16),1.0)
      self.createBox(Vec3(4,1,3),Vec3(0,13,20),1.0)
      self.createBox(Vec3(4,1,3),Vec3(0,-16,20),1.0)
      #table05
      self.createBox(Vec3(4,15,1),Vec3(0,-1,24),1.0)
      self.createStoneBox(Vec3(1,1,1),Vec3(0,2,20),5.0)
      self.createStoneBox(Vec3(1,1,1),Vec3(0,-2,20),5.0)
      self.createStoneBox(Vec3(1,1,1),Vec3(0,4,20),5.0)
      self.createStoneBox(Vec3(1,1,1),Vec3(0,8,20),5.0)
      self.createStoneBox(Vec3(1,1,1),Vec3(0,6,20),5.0)
      
      #pigs
      self.createSnowman(2.0,Vec3(0, 5, 2.0),10.0)
      self.createSnowman(2.0,Vec3(0,-8.5,2.0),10.0)
      self.createSnowman(1.5, Vec3(0,-9,19.5), 7.0)
      
      #presents
      self.createPresent(Vec3(2,2,2),Vec3(0,-20,5))
         
    if(self.gameLevel == 4):
      #wall
      self.createStoneBox(Vec3(4,1.5,10), Vec3(0,20,10),20)
      #table01
      self.createBox(Vec3(4,1,5), Vec3(0,7,7),1)
      self.createBox(Vec3(4,1,5), Vec3(0,0,7),1)
      self.createBox(Vec3(4,1,4), Vec3(0,3,7),1)
      self.createPlatform(Vec3(5,8,1), Vec3(0,4,13),1)
      self.createBox(Vec3(4,1,3), Vec3(0,11,18),1)
      self.createBox(Vec3(4,1,3), Vec3(0,-3,18),1)
      self.createBox(Vec3(4,8,1), Vec3(0,4,25),1)
      self.createStoneBox(Vec3(1,1,1), Vec3(0,4,27),2)
      self.createStoneBox(Vec3(1,1,1), Vec3(0,7,27),2)
      self.createStoneBox(Vec3(1,1,1), Vec3(0,2,27),2)
      self.createStoneBox(Vec3(1,1,1), Vec3(0,2,29),2)
      #stairs
      self.createPlatform(Vec3(4,50,4), Vec3(0,-55,5),100)
      #table02
      self.createBox(Vec3(4,1,5), Vec3(0,-13,15),1)
      self.createBox(Vec3(4,1,5), Vec3(0,-20,15),1)
      self.createBox(Vec3(4,1,4), Vec3(0,-17,15),1)
      self.createPlatform(Vec3(4,8,1), Vec3(0,-16,22),1)
      self.createBox(Vec3(4,1,3), Vec3(0,-9,28),1)
      self.createBox(Vec3(4,1,3), Vec3(0,-23,28),1)
      self.createBox(Vec3(4,8,1), Vec3(0,-16,33),1)
      self.createStoneBox(Vec3(1,1,1), Vec3(0,-16,35),2)
      self.createStoneBox(Vec3(1,1,1), Vec3(0,-13,35),2)
      self.createStoneBox(Vec3(1,1,1), Vec3(0,-18,35),2)
      self.createStoneBox(Vec3(1,1,1), Vec3(0,-18,37),2)
      self.createStoneBox(Vec3(1,1,1), Vec3(0,-14,37),2)
      
      #snowman
      self.createSnowman(2.0,Vec3(0,30,5),1.0)
      self.createSnowman(1.5,Vec3(0,4,18),1.0)
      self.createSnowman(1.5,Vec3(0,-13,26),1.0)
      self.createSnowman(1.5,Vec3(0,-19,26),1.0)
      self.createSnowman(2.0,Vec3(0,12,5),1.0)
      self.createPresent(Vec3(2,2,2),Vec3(0,-25,13))
      self.createPresent(Vec3(3,3,3),Vec3(0,-30,13))
      self.createPresent(Vec3(4,4,4),Vec3(0,-36,13))
      #self.createSnowman(1.5,Vec3(0,4,20),1.0)

      
    if(self.gameLevel == 5):
      #table01
      self.createStoneBox(Vec3(4,7,3), Vec3(0,30,5),10.0)
      self.createStoneBox(Vec3(4,7,3), Vec3(0,-30,5),10.0)
      self.createBox(Vec3(4,1,3), Vec3(0,0,5), 1.0)
      self.createSnowman(1.5,Vec3(0,-6,5),1.0)
      self.createSnowman(1.5,Vec3(0,6,5),1.0)
      self.createBox(Vec3(4,1,3), Vec3(0,-12,5), 1.0)
      self.createBox(Vec3(4,1,3), Vec3(0,12,5), 1.0)
      self.createSnowman(1.5,Vec3(0,-18,5),1.0)
      self.createSnowman(1.5,Vec3(0,18,5),1.0)
      self.createStoneBox(Vec3(4,6,1),Vec3(0,-18,10), 0.1)
      self.createStoneBox(Vec3(4,6,1),Vec3(0,-6,10), 0.1)
      self.createStoneBox(Vec3(4,6,1),Vec3(0,6,10), 0.1)
      self.createStoneBox(Vec3(4,6,1),Vec3(0,18,10), 0.1)
      self.createStoneBox(Vec3(4,1,3),Vec3(0,23,14), 1.0)
      self.createStoneBox(Vec3(4,1,3),Vec3(0,-23,14), 1.0)
      self.createBox(Vec3(4,1,3),Vec3(0,18,14),1.0)
      self.createBox(Vec3(4,1,3),Vec3(0,-18,14),1.0)
      self.createStoneBox(Vec3(4,1,7),Vec3(0,13,20), 2.0)
      self.createStoneBox(Vec3(4,1,7),Vec3(0,-13,20), 2.0)
      self.createBox(Vec3(4,1,3),Vec3(0,8,14),1.0)
      self.createBox(Vec3(4,1,3),Vec3(0,-8,14),1.0)
      self.createStoneBox(Vec3(4,1,3),Vec3(0,3,14), 1.0)
      self.createStoneBox(Vec3(4,1,3),Vec3(0,-3,14), 1.0)
      self.createPlatform(Vec3(4,3.5,1),Vec3(0,-20 ,20), 1.0)
      self.createPlatform(Vec3(4,3.5,1),Vec3(0,20 ,20), 1.0)
      self.createPlatform(Vec3(4,3.5,1),Vec3(0,-5 ,20), 1.0)
      self.createPlatform(Vec3(4,3.5,1),Vec3(0,5 ,20), 1.0)
      self.createStoneBox(Vec3(4,1,3.5),Vec3(0,-18,25), 2.0)
      self.createStoneBox(Vec3(4,1,3.5),Vec3(0,18,25), 2.0)
      self.createStoneBox(Vec3(4,1,3.5),Vec3(0,-7.5,25), 2.0)
      self.createStoneBox(Vec3(4,1,3.5),Vec3(0,7.5,25), 2.0)
      self.createStoneBox(Vec3(4,6,1),Vec3(0,-12,30), 2.0)
      self.createStoneBox(Vec3(4,6,1),Vec3(0,12,30), 2.0)
      self.createBox(Vec3(4,1,5),Vec3(0,-5,30), 2.0)
      self.createBox(Vec3(4,1,5),Vec3(0,5,30), 2.0)
      self.createBox(Vec3(4,5,1),Vec3(0,0,40), 2.0)
      self.createPlatform(Vec3(4,2,0.5),Vec3(0,0,42), 2.0)
      self.createStoneBox(Vec3(4,0.5,2),Vec3(0,-3.5,45), 2.0)
      self.createStoneBox(Vec3(4,0.5,2),Vec3(0,3.5,45), 2.0)
      self.createStoneBox(Vec3(4,4,0.5),Vec3(0,0,48), 2.0)
      
      self.createPresent(Vec3(1.5,1.5,1.5),Vec3(0,22,30))
      self.createPresent(Vec3(1.5,1.5,1.5),Vec3(0,-22,30))
      self.createPresent(Vec3(2,2,1),Vec3(0,0,44))
      self.createPresent(Vec3(3,3,4),Vec3(0,0,33))
      
      
    if(self.gameLevel > 5):
      self.gameState = 'WIN'
      self.doContinue()
      return
        
    # drawing lines between the points 
    ## self.lines = LineNodePath(parent = render, thickness = 3.0, colorVec = Vec4(1, 0, 0, 1))
    ## self.pFrom = Point3(-4, 0, 0.5)
    ## self.pTo = Point3(4, 0, 0.5)
    
    # Aiming line 
    self.lines = LineNodePath(parent = render, thickness = 3.0, 
                              colorVec = Vec4(1, 0, 0, 1))
    self.pFrom = Point3(0, 100, 0.5)
    self.pTo = Point3(0, 60, 10)
    
    self.arrow.setPos(self.pFrom)
      
    
  def drawLines(self):  
    # Draws lines for the ray.
    self.lines.reset()  
    self.lines.drawLines([(self.pFrom,self.pTo)])
    self.lines.create()
    
  def createBox(self,size,pos,mass):
    shape = BulletBoxShape(size)
    body = BulletRigidBodyNode('Obstacle')
    bodyNP = self.worldNP.attachNewNode(body)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(mass)
    bodyNP.node().setFriction(1.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setPos(pos)
    bodyNP.setCollideMask(BitMask32.allOn())

    self.world.attachRigidBody(bodyNP.node())
            
    visNP = loader.loadModel('models/crate.X')
    visNP.setScale(size*2)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    self.boxes.append(body)
    
  def createStoneBox(self,size,pos,mass):
    shape = BulletBoxShape(size)
    body = BulletRigidBodyNode('Obstacle')
    bodyNP = self.worldNP.attachNewNode(body)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(mass)
    bodyNP.node().setFriction(1.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setPos(pos)
    bodyNP.setCollideMask(BitMask32.allOn())

    self.world.attachRigidBody(bodyNP.node())
            
    visNP = loader.loadModel('models/stone.X')
    visNP.setScale(size*2)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    self.boxes.append(body)
    
  def createSnowman(self, size, pos, mass):
    shape = BulletBoxShape(Vec3(size,size,size))
    shape01 = BulletSphereShape(size/2)
    body = BulletRigidBodyNode('Snowman')
    np = self.worldNP.attachNewNode(body)
    np.node().setMass(mass)
    np.node().addShape(shape, TransformState.makePos(Point3(0,0,-1)))
    np.node().addShape(shape01, TransformState.makePos(Point3(0,0,1)))
    np.node().setFriction(10.0)
    np.node().setDeactivationEnabled(False)
    np.setPos(pos)
    np.setCollideMask(BitMask32.allOn())
      
    self.world.attachRigidBody(np.node())
  
    visualNP = loader.loadModel('models/snowman.X')
    visualNP.setScale(size)
    visualNP.clearModelNodes()
    visualNP.reparentTo(np)
    self.snowmans.append(np)
    
  def createPlatform(self,size,pos,mass):
    shape = BulletBoxShape(size)
    body = BulletRigidBodyNode('Platform')
    bodyNP = self.worldNP.attachNewNode(body)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(mass)
    bodyNP.node().setFriction(1.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setPos(pos)
    bodyNP.setCollideMask(BitMask32.allOn())

    self.world.attachRigidBody(bodyNP.node())
            
    visNP = loader.loadModel('models/crate.X')
    visNP.setScale(size*2)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    self.platforms.append(body)
    
  def createPresent(self,size,pos):
    shape = BulletBoxShape(size*0.7)
    body = BulletRigidBodyNode('Present')
    bodyNP = self.worldNP.attachNewNode(body)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(1.0)
    bodyNP.node().setFriction(1.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setPos(pos)
    bodyNP.setCollideMask(BitMask32.allOn())
    
    self.world.attachRigidBody(bodyNP.node())
    
    visNP = loader.loadModel('models/present.X')
    visNP.setScale(size*2)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    self.presents.append(bodyNP)
Пример #20
0
class GUI:
    def __init__(self, rootParent=None):

        self.btnStart = DirectButton(
            frameColor=(0.8, 0.8, 0.8, 0.0),
            frameSize=(-1.63125, 1.7312501430511475, -0.21250001192092896, 0.8124999761581421),
            hpr=LVecBase3f(0, 0, 0),
            pos=LPoint3f(-0.325, 0, 0.25),
            scale=LVecBase3f(0.1, 0.1, 0.1),
            text='START',
            text_align=TextNode.A_center,
            text_scale=(1, 1),
            text_pos=(0, 0),
            text_fg=LVecBase4f(1, 1, 1, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            text_wordwrap=None,
            parent=rootParent,
            pressEffect=1,
            command=base.messenger.send,
            extraArgs=["do_start"]
        )
        self.btnStart.setTransparency(0)

        self.btnHighscore = DirectButton(
            frameColor=(0.8, 0.8, 0.8, 0.0),
            frameSize=(-2.7499998569488526, 2.8874999046325684, -0.21250001192092896, 0.8124999761581421),
            hpr=LVecBase3f(0, 0, 0),
            pos=LPoint3f(0, 0, -0.025),
            scale=LVecBase3f(0.1, 0.1, 0.1),
            text='HIGHSCORE',
            text_align=TextNode.A_center,
            text_scale=(1, 1),
            text_pos=(0, 0),
            text_fg=LVecBase4f(1, 1, 1, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            text_wordwrap=None,
            parent=rootParent,
            pressEffect=1,
            command=base.messenger.send,
            extraArgs=["do_highscore"]
        )
        self.btnHighscore.setTransparency(0)

        self.btnQuit = DirectButton(
            frameColor=(0.8, 0.8, 0.8, 0.0),
            frameSize=(-0.049999999254941946, 2.487499809265137, -0.225, 0.8124999761581421),
            hpr=LVecBase3f(0, 0, 0),
            pos=LPoint3f(0.225, 0, -0.3),
            scale=LVecBase3f(0.1, 0.1, 0.1),
            text='QUIT',
            text_align=TextNode.A_left,
            text_scale=(1, 1),
            text_pos=(0, 0),
            text_fg=LVecBase4f(1, 1, 1, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            text_wordwrap=None,
            parent=rootParent,
            pressEffect=1,
            command=base.messenger.send,
            extraArgs=["do_quit"]
        )
        self.btnQuit.setTransparency(0)


    def show(self):
        self.btnStart.show()
        self.btnHighscore.show()
        self.btnQuit.show()

    def hide(self):
        self.btnStart.hide()
        self.btnHighscore.hide()
        self.btnQuit.hide()

    def destroy(self):
        self.btnStart.destroy()
        self.btnHighscore.destroy()
        self.btnQuit.destroy()
Пример #21
0
class NewsPageButtonManager(FSM.FSM):
    notify = DirectNotifyGlobal.directNotify.newCategory(
        'NewsPageButtonManager')

    def __init__(self):
        FSM.FSM.__init__(self, 'NewsPageButtonManager')
        self.buttonsLoaded = False
        self.clearGoingToNewsInfo()
        self.__blinkIval = None
        self.load()
        return

    def load(self):
        btnGui = loader.loadModel(
            'phase_3.5/models/gui/tt_m_gui_ign_newsBtnGui')
        bookModel = loader.loadModel(
            'phase_3.5/models/gui/tt_m_gui_ign_shtickerBook')
        self.openNewNewsUp = btnGui.find('**/tt_t_gui_ign_new')
        self.openNewNewsUpBlink = btnGui.find('**/tt_t_gui_ign_newBlink')
        self.openNewNewsHover = btnGui.find('**/tt_t_gui_ign_newHover')
        self.openOldNewsUp = btnGui.find('**/tt_t_gui_ign_oldNews')
        self.openOldNewsHover = btnGui.find('**/tt_t_gui_ign_oldHover')
        self.closeNewsUp = bookModel.find('**/tt_t_gui_sbk_newsPage1')
        self.closeNewsHover = bookModel.find('**/tt_t_gui_sbk_newsPage2')
        btnGui.removeNode()
        bookModel.removeNode()
        oldScale = 0.5
        newScale = 0.9
        shtickerBookScale = 0.305
        newPos = VBase3(0.914, 0, 0.862)
        shtickerBookPos = VBase3(1.175, 0, -0.83)
        textScale = 0.06
        self.newIssueButton = DirectButton(
            relief=None,
            sortOrder=DGG.BACKGROUND_SORT_INDEX - 1,
            image=(self.openNewNewsUp, self.openNewNewsHover,
                   self.openNewNewsHover),
            text=('', TTLocalizer.EventsPageNewsTabName,
                  TTLocalizer.EventsPageNewsTabName),
            text_fg=(1, 1, 1, 1),
            text_shadow=(0, 0, 0, 1),
            text_scale=textScale,
            text_font=ToontownGlobals.getInterfaceFont(),
            pos=newPos,
            scale=newScale,
            command=self.__handleGotoNewsButton)
        self.gotoPrevPageButton = DirectButton(
            relief=None,
            image=(self.closeNewsUp, self.closeNewsHover, self.closeNewsHover),
            text_fg=(1, 1, 1, 1),
            text_shadow=(0, 0, 0, 1),
            text_scale=textScale,
            text_font=ToontownGlobals.getInterfaceFont(),
            pos=shtickerBookPos,
            scale=shtickerBookScale,
            command=self.__handleGotoPrevPageButton)
        self.goto3dWorldButton = DirectButton(
            relief=None,
            image=(self.closeNewsUp, self.closeNewsHover, self.closeNewsHover),
            text_fg=(1, 1, 1, 1),
            text_shadow=(0, 0, 0, 1),
            text_scale=textScale,
            text_font=ToontownGlobals.getInterfaceFont(),
            pos=shtickerBookPos,
            scale=shtickerBookScale,
            command=self.__handleGoto3dWorldButton)
        self.hideNewIssueButton()
        self.gotoPrevPageButton.hide()
        self.goto3dWorldButton.hide()
        self.accept('newIssueOut', self.handleNewIssueOut)
        bounce1Pos = VBase3(newPos.getX(), newPos.getY(),
                            newPos.getZ() + 0.022)
        bounce2Pos = VBase3(newPos.getX(), newPos.getY(),
                            newPos.getZ() + 0.015)
        bounceIval = Sequence(
            LerpPosInterval(self.newIssueButton,
                            0.1,
                            bounce1Pos,
                            blendType='easeOut'),
            LerpPosInterval(self.newIssueButton,
                            0.1,
                            newPos,
                            blendType='easeIn'),
            LerpPosInterval(self.newIssueButton,
                            0.07,
                            bounce2Pos,
                            blendType='easeOut'),
            LerpPosInterval(self.newIssueButton,
                            0.07,
                            newPos,
                            blendType='easeIn'))
        self.__blinkIval = Sequence(Func(self.__showOpenEyes), Wait(2),
                                    bounceIval, Wait(0.5),
                                    Func(self.__showClosedEyes), Wait(0.1),
                                    Func(self.__showOpenEyes), Wait(0.1),
                                    Func(self.__showClosedEyes), Wait(0.1))
        self.__blinkIval.loop()
        self.__blinkIval.pause()
        self.buttonsLoaded = True
        return

    def __showOpenEyes(self):
        self.newIssueButton['image'] = (self.openNewNewsUp,
                                        self.openNewNewsHover,
                                        self.openNewNewsHover)

    def __showClosedEyes(self):
        self.newIssueButton['image'] = (self.openNewNewsUpBlink,
                                        self.openNewNewsHover,
                                        self.openNewNewsHover)

    def clearGoingToNewsInfo(self):
        self.goingToNewsPageFrom3dWorld = False
        self.setGoingToNewsPageFromStickerBook(False)

    def __handleGotoNewsButton(self):
        currentState = base.localAvatar.animFSM.getCurrentState().getName()
        if currentState == 'jumpAirborne':
            return
        from toontown.toon import LocalToon
        if not LocalToon.WantNewsPage:
            return
        if base.cr and base.cr.playGame and base.cr.playGame.getPlace(
        ) and base.cr.playGame.getPlace().fsm:
            fsm = base.cr.playGame.getPlace().fsm
            curState = fsm.getCurrentState().getName()
            if curState == 'walk':
                if hasattr(localAvatar, 'newsPage'):
                    base.cr.centralLogger.writeClientEvent(
                        'news gotoNewsButton clicked')
                    localAvatar.book.setPage(localAvatar.newsPage)
                    fsm.request('stickerBook')
                    self.goingToNewsPageFrom3dWorld = True
            elif curState == 'stickerBook':
                if hasattr(localAvatar, 'newsPage'):
                    base.cr.centralLogger.writeClientEvent(
                        'news gotoNewsButton clicked')
                    fsm.request('stickerBook')
                    if hasattr(localAvatar,
                               'newsPage') and localAvatar.newsPage:
                        localAvatar.book.goToNewsPage(localAvatar.newsPage)

    def __handleGotoPrevPageButton(self):
        self.clearGoingToNewsInfo()
        localAvatar.book.setPageBeforeNews()
        self.showAppropriateButton()
        self.ignoreEscapeKeyPress()

    def __handleGoto3dWorldButton(self):
        localAvatar.book.closeBook()

    def hideNewIssueButton(self):
        if hasattr(self, 'newIssueButton') and self.newIssueButton:
            self.newIssueButton.hide()
            localAvatar.clarabelleNewsPageCollision(False)

    def __showNewIssueButton(self):
        self.newIssueButton.show()
        localAvatar.clarabelleNewsPageCollision(True)

    def hideAllButtons(self):
        if not self.buttonsLoaded:
            return
        self.gotoPrevPageButton.hide()
        self.goto3dWorldButton.hide()
        self.hideNewIssueButton()
        self.__blinkIval.pause()

    def isNewIssueButtonShown(self):
        if not base.cr.inGameNewsMgr:
            return False

        if localAvatar.getLastTimeReadNews(
        ) < base.cr.inGameNewsMgr.getLatestIssue():
            return True

        return False

    def enterHidden(self):
        self.hideAllButtons()

    def exitHidden(self):
        pass

    def enterNormalWalk(self):
        if not self.buttonsLoaded:
            return

        if not base.cr.inGameNewsMgr:
            return

        if localAvatar.getLastTimeReadNews(
        ) < base.cr.inGameNewsMgr.getLatestIssue():
            self.__showNewIssueButton()
            self.__blinkIval.resume()

        else:
            self.hideNewIssueButton()

        self.gotoPrevPageButton.hide()
        self.goto3dWorldButton.hide()

    def exitNormalWalk(self):
        if not self.buttonsLoaded:
            return
        self.hideAllButtons()

    def enterGotoWorld(self):
        if not self.buttonsLoaded:
            return
        self.hideAllButtons()
        self.goto3dWorldButton.show()

    def exitGotoWorld(self):
        if not self.buttonsLoaded:
            return
        self.hideAllButtons()
        localAvatar.book.setPageBeforeNews(enterPage=False)
        self.clearGoingToNewsInfo()

    def enterPrevPage(self):
        if not self.buttonsLoaded:
            return
        self.hideAllButtons()
        self.gotoPrevPageButton.show()

    def exitPrevPage(self):
        if not self.buttonsLoaded:
            return
        self.hideAllButtons()

    def showAppropriateButton(self):
        self.notify.debugStateCall(self)
        from toontown.toon import LocalToon
        if not LocalToon.WantNewsPage:
            return
        if not self.buttonsLoaded:
            return
        if base.cr and base.cr.playGame and base.cr.playGame.getPlace(
        ) and hasattr(base.cr.playGame.getPlace(),
                      'fsm') and base.cr.playGame.getPlace().fsm:
            fsm = base.cr.playGame.getPlace().fsm
            curState = fsm.getCurrentState().getName()
            book = localAvatar.book
            if curState == 'walk':
                if localAvatar.tutorialAck and not localAvatar.isDisguised and not isinstance(
                        base.cr.playGame.getPlace(),
                        CogHQBossBattle.CogHQBossBattle):
                    self.request('NormalWalk')
                else:
                    self.request('Hidden')
            elif curState == 'stickerBook':
                if self.goingToNewsPageFrom3dWorld:
                    if localAvatar.tutorialAck:
                        self.request('GotoWorld')
                    else:
                        self.request('Hidden')
                elif self.goingToNewsPageFromStickerBook or hasattr(
                        localAvatar, 'newsPage') and localAvatar.book.isOnPage(
                            localAvatar.newsPage):
                    if localAvatar.tutorialAck:
                        self.request('PrevPage')
                    else:
                        self.request('Hidden')
                elif localAvatar.tutorialAck:
                    self.request('NormalWalk')
                else:
                    self.request('Hidden')

    def setGoingToNewsPageFromStickerBook(self, newVal):
        self.goingToNewsPageFromStickerBook = newVal

    def enterOff(self):
        self.ignoreAll()
        if not self.buttonsLoaded:
            return
        if self.__blinkIval:
            self.__blinkIval.finish()
            self.__blinkIval = None
        self.newIssueButton.destroy()
        self.gotoPrevPageButton.destroy()
        self.goto3dWorldButton.destroy()
        del self.openNewNewsUp
        del self.openNewNewsUpBlink
        del self.openNewNewsHover
        del self.openOldNewsUp
        del self.openOldNewsHover
        del self.closeNewsUp
        del self.closeNewsHover
        return

    def exitOff(self):
        self.notify.warning(
            'Should not get here. NewsPageButtonManager.exitOff')

    def simulateEscapeKeyPress(self):
        if self.goingToNewsPageFrom3dWorld:
            self.__handleGoto3dWorldButton()
        if self.goingToNewsPageFromStickerBook:
            self.__handleGotoPrevPageButton()

    def handleNewIssueOut(self):
        if localAvatar.isReadingNews():
            pass
        else:
            self.showAppropriateButton()

    def acceptEscapeKeyPress(self):
        self.accept(ToontownGlobals.StickerBookHotkey,
                    self.simulateEscapeKeyPress)
        self.accept(ToontownGlobals.OptionsPageHotkey,
                    self.simulateEscapeKeyPress)

    def ignoreEscapeKeyPress(self):
        self.ignore(ToontownGlobals.StickerBookHotkey)
        self.ignore(ToontownGlobals.OptionsPageHotkey)
Пример #22
0
class RonnieRacer(DirectObject):
  
  gameState = 'INIT'
  gameLevel = 1
  distanceTravelled = 0
  speed = 0
  score = 0
  triesLeft = 3
  count = 0
  rot = 0
  time = 0
  pause = False
  
  def __init__(self):
    self.imageObject = OnscreenImage(image = 'media/images/splashscreen.png', pos=(0,0,0), scale=(1.4,1,1))
    self.loseScreen = OnscreenImage(image = 'media/images/gameover.png', pos=(0,0,0), scale=(1,1,0.8))
    self.loseScreen.hide()
    self.retryScreen = OnscreenImage(image = 'media/images/retry.png', pos=(0,0,0), scale=(1,1,0.8))
    self.retryScreen.hide()
    self.congratScreen = OnscreenImage(image = 'media/images/congratulations.png', pos=(0,0,0), scale = (1,1,0.8))
    self.congratScreen.hide()
    self.winScreen = OnscreenImage(image = 'media/images/victory.png', pos=(0,0,0), scale = (1,1,0.8))
    self.winScreen.hide()
    self.pauseScreen = OnscreenImage(image = 'media/images/pause.png', pos=(0,0,0), scale = (1,1,0.8))
    self.pauseScreen.hide()
    self.instructionScreen = OnscreenImage(image = 'media/images/instructions.png', pos=(0,0,0), scale = (1,1,0.8))
    self.instructionScreen.hide()
    preloader = Preloader()
    base.setBackgroundColor(0, 0, 0, 1)
    base.setFrameRateMeter(True)
    
    # Audio
    self.loseSound = base.loader.loadSfx("media/audio/sfxboo.wav")
    self.winSound = base.loader.loadSfx("media/audio/cheer2.aif")
    self.menuMusic = base.loader.loadSfx("media/audio/Scattershot.mp3")
    self.gameMusic = base.loader.loadSfx("media/audio/Ghostpocalypse - 7 Master.mp3")
    
    self.menuMusic.setLoop(True)
    self.menuMusic.setLoopCount(0)
    
    self.gameMusic.setLoop(True)
    self.gameMusic.setLoopCount(0)

    #setup buttons
    self.retryBtn = DirectButton(text="Retry", scale = 0.1, pos = (0,0,0), command = self.doRetry)
    self.retryBtn.hide()
    self.menuBtn = DirectButton(text="Main Menu", scale = 0.1, pos = (0,0,0), command = self.doMenu)
    self.menuBtn.hide()
    self.nextBtn = DirectButton(text='Next', scale = 0.1, pos = (0,0,0), command = self.doNext)
    self.nextBtn.hide()
    self.backBtn = DirectButton(text='back', scale = 0.1, pos = (-0.7,0,-0.7), command = self.doBack)
    self.backBtn.hide()
    
    #setup font
    self.font = loader.loadFont('media/SHOWG.TTF')
    self.font.setPixelsPerUnit(60)
    
    #setup text
    self.text = OnscreenText(text = '', pos = (0, 0), scale = 0.07, font = self.font)
    
    self.rpmText = OnscreenText(text = '', 
                            pos = (-0.9, -0.9), scale = 0.07, font = self.font)
                            
    self.speedText = OnscreenText(text = '', 
                            pos = (0, -0.9), scale = 0.07, font = self.font)
                            
    self.distanceText = OnscreenText(text = '', 
                            pos = (0.9, -0.9), scale = 0.07, font = self.font)
    
    self.triesLeftText = OnscreenText(text = '', 
                            pos = (1.0, 0.9), scale = 0.07, font = self.font)
    
    self.gameLevelText = OnscreenText(text = '', 
                            pos = (-1.0, 0.9), scale = 0.07, font = self.font)
    
    self.timeText = OnscreenText(text = '', 
                            pos = (0, 0.9), scale = 0.07, font = self.font)
    
    self.scoreText = OnscreenText(text = '', 
                            pos = (1.0, 0.8), scale = 0.07, font = self.font)
    
    self.finalScoreText = OnscreenText(text = '', 
                            pos = (0, 0.2), scale = 0.07, font = self.font)
    # Light
    alight = AmbientLight('ambientLight')
    alight.setColor(Vec4(0.5, 0.5, 0.5, 1))
    alightNP = render.attachNewNode(alight)

    dlight = DirectionalLight('directionalLight')
    dlight.setDirection(Vec3(1, 1, -1))
    dlight.setColor(Vec4(0.7, 0.7, 0.7, 1))
    dlightNP = render.attachNewNode(dlight)

    render.clearLight()
    render.setLight(alightNP)
    render.setLight(dlightNP)

    # Input
    self.accept('escape', self.doExit)
    self.accept('r', self.doReset)
    self.accept('f1', self.toggleWireframe)
    self.accept('f2', self.toggleTexture)
    self.accept('f3', self.toggleDebug)
    self.accept('f5', self.doScreenshot)

    inputState.watchWithModifiers('forward', 'w')
    inputState.watchWithModifiers('left', 'a')
    inputState.watchWithModifiers('reverse', 's')
    inputState.watchWithModifiers('right', 'd')
    inputState.watchWithModifiers('turnLeft', 'a')
    inputState.watchWithModifiers('turnRight', 'd')

    # Task
    taskMgr.add(self.update, 'updateWorld')

  # _____HANDLER_____
  def doExit(self):
    sys.exit(1)

  def doReset(self):
    self.cleanup()
    self.terrain.getRoot().removeNode()
    self.setup()

  def doBack(self):
    self.backBtn.hide()
    self.instructionScreen.hide()
    
    self.imageObject.show()
    self.helpBtn.show()
    self.startBtn.show()
    self.exitBtn.show()

  def toggleWireframe(self):
    base.toggleWireframe()

  def toggleTexture(self):
    base.toggleTexture()

  def toggleDebug(self):
    if self.debugNP.isHidden():
      self.debugNP.show()
    else:
      self.debugNP.hide()

  def doScreenshot(self):
    base.screenshot('Bullet')

  # ____TASK___

  def processInput(self, dt):
    # Process input
    engineForce = 0.0
    brakeForce = 0.0
    
    self.accept('p', self.doPause)
  
    if inputState.isSet('forward'):
       engineForce = 15.0
       brakeForce = 0.0
   
    if inputState.isSet('reverse'):
       engineForce = -25.0
       brakeForce = 25.0
   
    if inputState.isSet('turnLeft'):
       self.steering += dt * self.steeringIncrement
       self.steering = min(self.steering, self.steeringClamp)
   
    if inputState.isSet('turnRight'):
       self.steering -= dt * self.steeringIncrement
       self.steering = max(self.steering, -self.steeringClamp)
   
    # Apply steering to front wheels
    self.vehicle.setSteeringValue(self.steering, 0)
    self.vehicle.setSteeringValue(self.steering, 1)
   
    # Apply engine and brake to rear wheels
    self.vehicle.applyEngineForce(engineForce, 2)
    self.vehicle.applyEngineForce(engineForce, 3)
    self.vehicle.setBrake(brakeForce, 2)
    self.vehicle.setBrake(brakeForce, 3)
    
  def processContacts(self, dt):
    result = self.world.contactTestPair(self.vehicleNP.node(), self.flagNP.node())
    if(result.getNumContacts() > 0):
      self.gameState = 'WIN'
      self.doContinue()
      
  def doContinue(self):
    if(self.gameState == 'INIT'):
      self.gameState = 'MENU'
      self.menuMusic.play()
      self.text.hide()
      self.startBtn = DirectButton(text=("Play"), scale = 0.1, pos = (0.5,0,0),command=self.playGame)
      self.helpBtn = DirectButton(text=("Help"), scale = 0.1, pos = (0.5,0,-0.2),command=self.help)
      self.exitBtn = DirectButton(text=("Exit"), scale = 0.1,  pos = (0.5,0,-0.4), command = self.doExit)
      return
      
    if(self.gameState == 'RETRY'):
      self.retryScreen.show()
      self.retryBtn.show()
      
      self.loseSound.play()
      return
    
    if(self.gameState == 'LOSE'):
      self.loseScreen.show()
      self.menuBtn.show()
      return
    
    if(self.gameState == 'WIN'):
      if(self.gameLevel < 3):
        self.congratScreen.show()
        self.nextBtn.show()
      elif(self.gameLevel >= 3):
        self.winScreen.show()
        self.menuBtn.show()
      self.finalScoreText.setText('Your Score: '+str(int(self.score)))
      self.finalScoreText.show()
        
      self.winSound.play()
      
  def help(self):
    self.gameState = 'HELP'
    self.startBtn.hide()
    self.exitBtn.hide()
    self.helpBtn.hide()
    self.imageObject.hide()
    self.instructionScreen.show()
    self.backBtn.show()
    
  def doNext(self):
    self.nextBtn.hide()
    self.finalScoreText.hide()
    self.congratScreen.hide()
    self.gameLevel += 1
    if(self.gameLevel == 2):
      self.score += 2000
    elif(self.gameLevel == 3):
      self.score += 3000
    self.doReset()
    self.triesLeft = 3
    self.gameState = 'PLAY'
    
  def doRetry(self):
    self.doReset()
    self.gameState = 'PLAY'
    self.retryScreen.hide()
    self.retryBtn.hide()
    self.triesLeft -= 1
  
  def doMenu(self):
    self.cleanup()
    self.terrain.getRoot().removeNode()
    self.gameState = 'MENU'
    
    self.score = 0
    
    self.imageObject.show()
    self.startBtn.show()
    self.exitBtn.show()
    self.helpBtn.show()
    
    self.loseScreen.hide()
    self.menuBtn.hide()
    self.winScreen.hide()
    self.finalScoreText.hide()
    
    self.speedText.hide()
    self.distanceText.hide()
    self.rpmText.hide()
    self.scoreText.hide()
    self.gameLevelText.hide()
    self.timeText.hide()
    self.triesLeftText.hide()
    
    self.gameMusic.stop()
    self.menuMusic.play()
      
  def doPause(self):
    self.pause  = not self.pause
    if(self.pause):
      self.pauseScreen.show()
    else:
      self.pauseScreen.hide()
      
  def playGame(self):
    self.gameState = 'PLAY'
    
    self.triesLeft = 3
    self.gameLevel = 1
    
    self.imageObject.hide()
    self.startBtn.hide()
    self.exitBtn.hide()
    self.helpBtn.hide()
    
    self.menuMusic.stop()
    self.gameMusic.play()
    
    self.speedText.show()
    self.distanceText.show()
    self.rpmText.show()
    self.scoreText.show()
    self.gameLevelText.show()
    self.triesLeftText.show()
    self.timeText.show()
    
    # Physics
    self.setup()

  def update(self, task):
    dt = globalClock.getDt()
    if(not self.pause):
      if(self.gameState == 'RETRY'):
        return task.cont
      
      if (self.gameState == 'INIT'):
        self.accept('space', self.doContinue)
        self.text.setText('Press Space to Continue')
        
      if(self.gameState == 'PLAY'):
        if (self.steering > 0):
            self.steering -= dt * 50
        if (self.steering < 0):
            self.steering += dt * 50
            
        playerOldSpeed = self.vehicle.getCurrentSpeedKmHour()
        
        self.processInput(dt)
        self.processContacts(dt)
        self.world.doPhysics(dt, 10, 0.008)
  
        #calculate speed,rpm,distance and display text
        self.speed = self.vehicle.getCurrentSpeedKmHour()
        if(self.speed<0):
            self.speed = -self.speed
        self.speedText.setText('Speed: ' + str(int(self.speed)) + 'Km/h')
        self.distanceTravelled += self.speed*(dt/3600)
        self.distanceText.setText('Distance: '+str(float(int(self.distanceTravelled * 1000))/1000) + 'Km')
  
        playerNewSpeed = self.vehicle.getCurrentSpeedKmHour()
  
        playerAcceleration = (playerNewSpeed - playerOldSpeed) / (dt/60)
        #playerPosText = self.vehicleNP.getPos()
        #self.text.setText('Player position: %s'%playerPosText)
        self.rpmText.setText('Engine RPM: ' + str(int(((self.vehicle.getCurrentSpeedKmHour() / 60) * 1000) / (2 * 0.4 * 3.14159265))) + ' Rpm')
        
        self.triesLeftText.setText('Tries Left: ' + str(self.triesLeft))
  
        self.gameLevelText.setText('Level: '+ str(self.gameLevel))
        
        #update camera
        #position
        d = self.vehicleNP.getPos() - base.cam.getPos()
        if(d.length() > 8):
          base.cam.setX(base.cam.getX() + d.getX()*dt)
          base.cam.setY(base.cam.getY() + d.getY()*dt)
        base.cam.setZ(self.vehicleNP.getZ() + 4)
        #lookat
        base.cam.lookAt(self.vehicleNP.getPos()+Vec3(0,0,1))
        
        if(self.gameLevel == 1):
          if(self.vehicleNP.getZ() < -17):
            if(self.triesLeft > 0):
              self.gameState = 'RETRY'
            else:
              self.gameState = 'LOSE'
            self.doContinue()
        elif(self.gameLevel == 2):
          if(self.vehicleNP.getZ() < -20):
            if(self.triesLeft > 0):
              self.gameState = 'RETRY'
            else:
              self.gameState = 'LOSE'
            self.doContinue()
        elif(self.gameLevel == 3):
          if(self.vehicleNP.getZ() < -17):
            if(self.triesLeft > 0):
              self.gameState = 'RETRY'
            else:
              self.gameState = 'LOSE'
            self.doContinue()
            
        if(self.speed < 5):
          self.steeringIncrement = 120
        elif(self.speed >= 5 and self.speed < 10):
          self.steeringIncrement = 100
        elif(self.speed >= 10 and self.speed < 15):
          self.steeringIncrement = 80
        elif(self.speed >=15 and self.speed < 30):
          self.steeringIncrement = 60
          
        #spin the flag
        self.rot += 1
        self.flagNP.setHpr(self.rot,0,0)
        
        #time
        self.time += dt
        self.timeText.setText('Time: ' + str(int(self.time)))
        if(self.score > 0):
          self.score -= dt
        self.scoreText.setText('Score: '+str(int(self.score)))

    return task.cont

  def cleanup(self):
    self.world = None
    self.worldNP.removeNode()

  def setup(self):
    # Steering info
    self.steering = 0.0            # degree
    self.steeringClamp = 30.0      # degree
    self.steeringIncrement = 80.0 # degree per second
    
    self.worldNP = render.attachNewNode('World')

    # World
    self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
    #self.debugNP.show()

    self.world = BulletWorld()
    self.world.setGravity(Vec3(0, 0, -9.81))
    self.world.setDebugNode(self.debugNP.node())
    
    if(self.gameLevel == 1):
      #set score
      print('GameLevel')
      self.score = 1000
      self.distanceTravelled = 0
      self.time = 0
      # Plane
      img = PNMImage(Filename('media/terrain/SIMP_Assignment_2_Terrain_1.png'))
      shape = BulletHeightfieldShape(img, 50.0, ZUp)

      np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
      np.node().addShape(shape)
      np.setPos(0, 0, 0)
      np.setCollideMask(BitMask32.allOn())

      self.world.attachRigidBody(np.node())
    
      #skybox
      skybox = loader.loadModel('media/models/skybox/skybox_01.X')
      skybox.reparentTo(render)

    # Chassis
      shape = BulletBoxShape(Vec3(0.6, 1.4, 0.5))
      ts = TransformState.makePos(Point3(0, 0, 1.0))

      self.vehicleNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Vehicle'))
      self.vehicleNP.node().addShape(shape, ts)
      self.vehicleNP.setPos(-93, -88, -7)#-93, -88, -7) #(-82,65.8,-8) #(55,8.38,-6)#(45, -19, -8)#(-93, -88, -7)
      self.vehicleNP.setHpr(-90,0,0)
      self.vehicleNP.node().setMass(5.0)
      self.vehicleNP.node().setDeactivationEnabled(False)
      
      base.cam.setPos(self.vehicleNP.getPos().getX()+2,self.vehicleNP.getPos().getY()+2,self.vehicleNP.getPos().getZ()+2)

      self.world.attachRigidBody(self.vehicleNP.node())

      # Vehicle
      self.vehicle = BulletVehicle(self.world, self.vehicleNP.node())
      self.vehicle.setCoordinateSystem(ZUp)
      self.world.attachVehicle(self.vehicle)

      self.hummerNP = loader.loadModel('media/models/vehicle/body.X')
      self.hummerNP.reparentTo(self.vehicleNP)
  
      # Right front wheel
      np = loader.loadModel('media/models/vehicle/front_right.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3( 0.8,  0.9, 0.8), True, np)
  
      # Left front wheel
      np = loader.loadModel('media/models/vehicle/front_left.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3(-0.8,  0.9, 0.8), True, np)
  
      # Right rear wheel
      np = loader.loadModel('media/models/vehicle/back_right.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3( 0.8, -0.7, 0.8), False, np)
  
      # Left rear wheel
      np = loader.loadModel('media/models/vehicle/back_left.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3(-0.8, -0.7, 0.8), False, np)
      
      #Obstacles
      self.setupObstacleOne(Vec3(50, -5, -4), 1.8, Vec3(60, 0, 0))
      self.setupObstacleFour(Vec3(63.3, 59.2, -10), 1.5, Vec3(0,0,0))
      self.setupObstacleFour(Vec3(41, 57, -10), 1.5, Vec3(0,0,0))
      self.setupObstacleFour(Vec3(7.5, 53.8, -10), 1.5, Vec3(0,0,0))
      self.setupObstacleFour(Vec3(-28, 81.4, -10), 1.5, Vec3(0,0,0))
      self.setupObstacleSix(Vec3(-91, 81 , -6), 1, Vec3(60,0,0))
      
      #Goal
      self.setupGoal(Vec3(-101,90.6,-6.5))
      
      #self.vehicleNP.setPos(Vec3(6,52,-6))
      self.setupTerrain()
    elif(self.gameLevel == 2):
      self.distanceTravelled = 0
      self.time  = 0 
      # Plane
      img = PNMImage(Filename('media/terrain/SIMP_Assignment_2_Terrain_2.png'))
      shape = BulletHeightfieldShape(img, 50.0, ZUp)

      np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
      np.node().addShape(shape)
      np.setPos(0, 0, 0)
      np.setCollideMask(BitMask32.allOn())

      self.world.attachRigidBody(np.node())
      
      #skybox
      skybox = loader.loadModel('media/models/skybox/skybox_01.X')
      skybox.reparentTo(render)

      # Chassis
      shape = BulletBoxShape(Vec3(0.6, 1.4, 0.5))
      ts = TransformState.makePos(Point3(0, 0, 1.0))

      self.vehicleNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Vehicle'))
      self.vehicleNP.node().addShape(shape, ts)
      self.vehicleNP.setPos(-99.6,105,-11.8)#(88, 21, -11)#(34.3,8.4,-11.8)#(-99.6,105,-11.8)#(86.4,41.2,-12)
      self.vehicleNP.setHpr(-130,0,0)
      self.vehicleNP.node().setMass(5.0)
      self.vehicleNP.node().setDeactivationEnabled(False)
      
      base.cam.setPos(self.vehicleNP.getPos().getX()+2,self.vehicleNP.getPos().getY()+2,self.vehicleNP.getPos().getZ()+2)

      self.world.attachRigidBody(self.vehicleNP.node())

      # Vehicle
      self.vehicle = BulletVehicle(self.world, self.vehicleNP.node())
      self.vehicle.setCoordinateSystem(ZUp)
      self.world.attachVehicle(self.vehicle)

      self.hummerNP = loader.loadModel('media/models/vehicle/body.X')
      self.hummerNP.reparentTo(self.vehicleNP)
  
      # Right front wheel
      np = loader.loadModel('media/models/vehicle/front_right.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3( 0.8,  0.9, 0.8), True, np)
  
      # Left front wheel
      np = loader.loadModel('media/models/vehicle/front_left.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3(-0.8,  0.9, 0.8), True, np)
  
      # Right rear wheel
      np = loader.loadModel('media/models/vehicle/back_right.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3( 0.8, -0.7, 0.8), False, np)
  
      # Left rear wheel
      np = loader.loadModel('media/models/vehicle/back_left.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3(-0.8, -0.7, 0.8), False, np)
      
      self.setupObstacleFive(Vec3(91, 3, -9),1,Vec3(90,0,0))
      self.setupObstacleFive(Vec3(94,-19, -10),0.9,Vec3(90,0,0))
      self.setupObstacleFive(Vec3(85,-40, -10),1,Vec3(90,0,0))
      self.setupObstacleFour(Vec3(-33.5, 23.4,-14.5),1,Vec3(0,0,0))
      self.setupObstacleFour(Vec3(-43.3, 24.2,-14.5),1,Vec3(0,0,0))
      self.setupObstacleTwo(Vec3(34.7,20.9,-8.5),1,Vec3(90,0,0))
      self.setupObstacleTwo(Vec3(26.8,20.3,-8.5),1,Vec3(90,0,0))
      self.setupObstacleTwo(Vec3(42.1,22.5,-8.5),1,Vec3(90,0,0))
      #self.setupObstacleFive(Vec3(91,0.2, -8),2.1,Vec3(90,0,0))
            
      #Goal
      self.setupGoal(Vec3(94,-89.7,-10))
      self.setupTerrain()
    elif(self.gameLevel == 3):
      self.distanceTravelled = 0
      self.time  = 0 
      # Plane
      img = PNMImage(Filename('media/terrain/SIMP_Assignment_2_Terrain_3.png'))
      shape = BulletHeightfieldShape(img, 50.0, ZUp)

      np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground'))
      np.node().addShape(shape)
      np.setPos(0, 0, 0)
      np.setCollideMask(BitMask32.allOn())

      self.world.attachRigidBody(np.node())
      
      #skybox
      skybox = loader.loadModel('media/models/skybox/skybox_01.X')
      skybox.reparentTo(render)

      # Chassis
      shape = BulletBoxShape(Vec3(0.6, 1.4, 0.5))
      ts = TransformState.makePos(Point3(0, 0, 1.0))

      self.vehicleNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Vehicle'))
      self.vehicleNP.node().addShape(shape, ts)
      self.vehicleNP.setPos(-110, -110, 0)
      self.vehicleNP.setHpr(-40,0,0)
      self.vehicleNP.node().setMass(5.0)
      self.vehicleNP.node().setDeactivationEnabled(False)
      
      base.cam.setPos(self.vehicleNP.getPos().getX()+2,self.vehicleNP.getPos().getY()+2,self.vehicleNP.getPos().getZ()+2)

      self.world.attachRigidBody(self.vehicleNP.node())

      # Vehicle
      self.vehicle = BulletVehicle(self.world, self.vehicleNP.node())
      self.vehicle.setCoordinateSystem(ZUp)
      self.world.attachVehicle(self.vehicle)

      self.hummerNP = loader.loadModel('media/models/vehicle/body.X')
      self.hummerNP.reparentTo(self.vehicleNP)
  
      # Right front wheel
      np = loader.loadModel('media/models/vehicle/front_right.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3( 0.8,  0.9, 0.8), True, np)
  
      # Left front wheel
      np = loader.loadModel('media/models/vehicle/front_left.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3(-0.8,  0.9, 0.8), True, np)
  
      # Right rear wheel
      np = loader.loadModel('media/models/vehicle/back_right.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3( 0.8, -0.7, 0.8), False, np)
  
      # Left rear wheel
      np = loader.loadModel('media/models/vehicle/back_left.X')
      np.reparentTo(self.worldNP)
      self.addWheel(Point3(-0.8, -0.7, 0.8), False, np)

      self.setupTerrain()
      
      #Goal
      self.setupGoal(Vec3(114,100,-13))
      
      #Obstacles
      self.setupObstacleFour(Vec3(-60, -73, -9), 1, Vec3(0, 0, 0))
      self.setupObstacleFour(Vec3(-63, -77, -9), 1, Vec3(0, 0, 0))
      self.setupObstacleTwo(Vec3(-15, -40, -3), 1, Vec3(0, 0, 0))
      self.setupObstacleFour(Vec3(-60, 12, -11), 1, Vec3(0, 0, 0))
      self.setupObstacleSix(Vec3(-15, 90, -6), 1.5, Vec3(-30, 0, 0))
      self.setupObstacleFour(Vec3(28, 87, -11), 1, Vec3(0, 0, 0))
      self.setupObstacleFour(Vec3(32, 90, -11), 1, Vec3(0, 0, 0))



  def addWheel(self, pos, front, np):
    wheel = self.vehicle.createWheel()

    wheel.setNode(np.node())
    wheel.setChassisConnectionPointCs(pos)
    wheel.setFrontWheel(front)

    wheel.setWheelDirectionCs(Vec3(0, 0, -1))
    wheel.setWheelAxleCs(Vec3(1, 0, 0))
    wheel.setWheelRadius(0.4)
    wheel.setMaxSuspensionTravelCm(40.0)

    wheel.setSuspensionStiffness(40.0)
    wheel.setWheelsDampingRelaxation(2.3)
    wheel.setWheelsDampingCompression(4.4)
    wheel.setFrictionSlip(100.0);
    wheel.setRollInfluence(0.1)

  def setupTerrain(self):
    if(self.gameLevel == 1):
      #terrain setting
      img = PNMImage(Filename('media/terrain/SIMP_Assignment_2_Terrain_1.png'))
      self.terrain = GeoMipTerrain("myTerrain") 
      self.terrain.setHeightfield(img) 
      self.terrain.getRoot().setSz(50) 
      self.terrain.setBlockSize(4) 
      #self.terrain.setFactor(10) 
      #self.terrain.setMinLevel(0)
      self.terrain.setNear(50)
      self.terrain.setFar(1000)
      self.terrain.setFocalPoint(base.camera)
      self.terrain.getRoot().reparentTo(render)
      offset = img.getXSize() / 2.0 - 0.5
      self.terrain.getRoot().setPos(-offset, -offset, -50 / 2.0) 
      self.terrain.generate() 
    
      #load textures 
      tex0 = loader.loadTexture("media/terrain/SIMP_Assignment_2_Terrain_1_d.png") 
      tex0.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex1 = loader.loadTexture("media/terrain/longGrass.png") 
      tex1.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex2 = loader.loadTexture("media/terrain/bigRockFace.png") 
      tex2.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex3 = loader.loadTexture("media/terrain/greenrough.png") 
      tex3.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex4 = loader.loadTexture("media/terrain/grayRock.png") 
      tex4.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex5 = loader.loadTexture("media/terrain/SIMP_Assignment_2_Terrain_1_c.png") 
      tex5.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex6 = loader.loadTexture("media/terrain/SIMP_Assignment_2_Terrain_1_l.png") 
      tex6.setMinfilter(Texture.FTLinearMipmapLinear) 
      #set mutiltextures 
      self.terrain.getRoot().setTexture( TextureStage('tex0'),tex0 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex1'),tex1 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex2'),tex2 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex3'),tex3 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex4'),tex4 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex5'),tex5 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex6'),tex6 ) 
      #load shader 
      self.terrain.getRoot().setShader(loader.loadShader('terraintexture.sha'))
    elif(self.gameLevel == 2):
      #terrain setting
      img = PNMImage(Filename('media/terrain/SIMP_Assignment_2_Terrain_2.png'))
      self.terrain = GeoMipTerrain("myTerrain") 
      self.terrain.setHeightfield(img) 
      self.terrain.getRoot().setSz(50) 
      self.terrain.setBlockSize(4) 
      #self.terrain.setFactor(10) 
      #self.terrain.setMinLevel(0)
      self.terrain.setNear(50)
      self.terrain.setFar(100)
      self.terrain.setFocalPoint(base.camera)
      self.terrain.getRoot().reparentTo(render)
      offset = img.getXSize() / 2.0 - 0.5
      self.terrain.getRoot().setPos(-offset, -offset, -50 / 2.0) 
      self.terrain.generate() 
    
      #load textures 
      tex0 = loader.loadTexture("media/terrain/SIMP_Assignment_2_Terrain_2_d.png") 
      tex0.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex1 = loader.loadTexture("media/terrain/sandripple.png") 
      tex1.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex2 = loader.loadTexture("media/terrain/orangesand.png") 
      tex2.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex3 = loader.loadTexture("media/terrain/grayRock.png") 
      tex3.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex4 = loader.loadTexture("media/terrain/bigRockFace.png") 
      tex4.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex5 = loader.loadTexture("media/terrain/SIMP_Assignment_2_Terrain_2_c.png") 
      tex5.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex6 = loader.loadTexture("media/terrain/SIMP_Assignment_2_Terrain_2_l.png") 
      tex6.setMinfilter(Texture.FTLinearMipmapLinear) 
      #set mutiltextures 
      self.terrain.getRoot().setTexture( TextureStage('tex0'),tex0 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex1'),tex1 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex2'),tex2 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex3'),tex3 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex4'),tex4 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex5'),tex5 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex6'),tex6 ) 
      #load shader 
      self.terrain.getRoot().setShader(loader.loadShader('terraintexture.sha'))
    elif(self.gameLevel == 3):
      #terrain setting
      img = PNMImage(Filename('media/terrain/SIMP_Assignment_2_Terrain_3.png'))
      self.terrain = GeoMipTerrain("myTerrain") 
      self.terrain.setHeightfield(img) 
      self.terrain.getRoot().setSz(50) 
      self.terrain.setBlockSize(4) 
      #self.terrain.setFactor(10) 
      #self.terrain.setMinLevel(0)
      self.terrain.setNear(50)
      self.terrain.setFar(100)
      self.terrain.setFocalPoint(base.camera)
      self.terrain.getRoot().reparentTo(render)
      offset = img.getXSize() / 2.0 - 0.5
      self.terrain.getRoot().setPos(-offset, -offset, -50 / 2.0) 
      self.terrain.generate() 
    
      #load textures 
      tex0 = loader.loadTexture("media/terrain/SIMP_Assignment_2_Terrain_3_d.png") 
      tex0.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex1 = loader.loadTexture("media/terrain/hardDirt.png") 
      tex1.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex2 = loader.loadTexture("media/terrain/littlerocks.png") 
      tex2.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex3 = loader.loadTexture("media/terrain/greenrough.png") 
      tex3.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex4 = loader.loadTexture("media/terrain/bigRockFace.png") 
      tex4.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex5 = loader.loadTexture("media/terrain/SIMP_Assignment_2_Terrain_3_c.png") 
      tex5.setMinfilter(Texture.FTLinearMipmapLinear) 
      tex6 = loader.loadTexture("media/terrain/SIMP_Assignment_2_Terrain_3_l.png") 
      tex6.setMinfilter(Texture.FTLinearMipmapLinear) 
      #set mutiltextures 
      self.terrain.getRoot().setTexture( TextureStage('tex0'),tex0 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex1'),tex1 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex2'),tex2 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex3'),tex3 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex4'),tex4 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex5'),tex5 ) 
      self.terrain.getRoot().setTexture( TextureStage('tex6'),tex6 ) 
      #load shader 
      self.terrain.getRoot().setShader(loader.loadShader('terraintexture.sha'))

  def setupObstacleOne(self, pos, scale, turn):
    
    #box A
    shape = BulletBoxShape(Vec3(3, 0.1, 0.1) * scale)
    
    bodyA = BulletRigidBodyNode('Box A')
    bodyNP= self.worldNP.attachNewNode(bodyA)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(3, 0.1, 0.1)*2 * scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyA)
    
    # Box C
    shape = BulletBoxShape(Vec3(0.1, 0.1, 0.9)*scale)
    
    bodyC = BulletRigidBodyNode('Box C')
    bodyNP = self.worldNP.attachNewNode(bodyC)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(1.0)
    bodyNP.node().setLinearDamping(0.5)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(0.1, 0.1, 0.9)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyC)
    
    pivotA = Point3(0, 0, -0.1 * scale)
    pivotB = Point3(0, 0, 1 * scale)
    axisA = Vec3(1, 0, 0)
    axisB = Vec3(1, 0, 0)
    
    hinge = BulletHingeConstraint(bodyA, bodyC, pivotA, pivotB, axisA, axisB, True)
    hinge.setDebugDrawSize(2.0)
    hinge.setLimit(-90,90, softness=1.0, bias=0.3, relaxation=1.0)
    self.world.attachConstraint(hinge)
    
    # Box B
    shape = BulletBoxShape(Vec3(3, 2, 0.1)*scale)
    
    bodyB = BulletRigidBodyNode('Box B')
    bodyNP = self.worldNP.attachNewNode(bodyB)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(1.0)
    bodyNP.node().setLinearDamping(0.5)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn);
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(3, 2, 0.1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyB)
    
    # Hinge
    pivotA = Point3(0, 0, 0)
    pivotB = Point3(0, 0, -1 * scale)
    
    hinge = BulletHingeConstraint(bodyB, bodyC, pivotA, pivotB, axisA, axisB, True)
    hinge.setLimit(0,360, softness=1.0, bias=0.3, relaxation=1.0)
    self.world.attachConstraint(hinge)
  
  def setupObstacleTwo(self,pos,scale,turn):
    
    #box A
    shape = BulletBoxShape(Vec3(3, 0.1, 0.1)*scale)
    
    bodyA = BulletRigidBodyNode('Box A')
    bodyNP= self.worldNP.attachNewNode(bodyA)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(3, 0.1, 0.1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyA)
    
    # Box B
    shape = BulletBoxShape(Vec3(0.1, 1, 1)*scale)
    
    bodyB = BulletRigidBodyNode('Box B')
    bodyNP = self.worldNP.attachNewNode(bodyB)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(100.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(0.1, 1, 1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyB)
    
    # Hinge
    pivotA = Point3(2, 0, 0)
    pivotB = Point3(0, 0, 2)
    axisA = Vec3(1, 0, 0)
    axisB = Vec3(1, 0, 0)
    
    hinge = BulletHingeConstraint(bodyA, bodyB, pivotA, pivotB, axisA, axisB, True)
    hinge.setDebugDrawSize(2.0)
    hinge.setLimit(-90,90, softness=1.0, bias=0.3, relaxation=1.0)
    self.world.attachConstraint(hinge)
    
    # Box C
    shape = BulletBoxShape(Vec3(0.1, 1, 1)*scale)
    
    bodyC = BulletRigidBodyNode('Box C')
    bodyNP = self.worldNP.attachNewNode(bodyC)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(100.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(0.1, 1, 1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyC)
    
    pivotA = Point3(-2, 0, 0)
    pivotB = Point3(0, 0, 2)
    
    hinge = BulletHingeConstraint(bodyA, bodyC, pivotA, pivotB, axisA, axisB, True)
    self.world.attachConstraint(hinge)
  
  def setupObstacleThree(self, pos, scale, turn):
    # Box A
    shape = BulletBoxShape(Vec3(0.1, 0.1, 0.1))
    
    bodyA = BulletRigidBodyNode('Box A')
    bodyA.setRestitution(1.0)
    bodyNP = self.worldNP.attachNewNode(bodyA)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(0.1, 0.1, 0.1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyA)
    
    #Box B
    shape = BulletBoxShape(Vec3(0.1,0.1,0.1))
    
    bodyB = BulletRigidBodyNode('Box B')
    bodyB.setRestitution(1.0)
    bodyNP = self.worldNP.attachNewNode(bodyB)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(0.1,0.1,0.1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyB)
    
    # Slider
    frameA = TransformState.makePosHpr(Point3(0, 0, 0), Vec3(0, 0, 0))
    frameB = TransformState.makePosHpr(Point3(0, 0, 0), Vec3(0, 0, 0))
    
    slider = BulletSliderConstraint(bodyA, bodyB, frameA, frameB, True)
    slider.setDebugDrawSize(2.0)
    slider.setLowerLinearLimit(0)
    slider.setUpperLinearLimit(12)
    slider.setLowerAngularLimit(-90)
    slider.setUpperAngularLimit(-85)
    self.world.attachConstraint(slider)
    
    # Box C
    shape = BulletBoxShape(Vec3(1, 3, 0.1))
    
    bodyC = BulletRigidBodyNode('Box C')
    bodyC.setRestitution(1.0)
    bodyNP = self.worldNP.attachNewNode(bodyC)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(0.1)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())  
    bodyNP.setPos(Vec3(pos.getX() + 3, pos.getY() - 4, pos.getZ()))
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(1, 3, 0.1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyC)
    
    bodyNP.node().setLinearVelocity(-100)
    
    # Slider
    frameA = TransformState.makePosHpr(Point3(0, 0, 0), Vec3(0, 0, 0))
    frameB = TransformState.makePosHpr(Point3(0, 0, 0), Vec3(0, 0, 0))
    
    slider = BulletSliderConstraint(bodyA, bodyC, frameA, frameB, True)
    slider.setDebugDrawSize(2.0)
    slider.setLowerLinearLimit(2)
    slider.setUpperLinearLimit(6)
    slider.setLowerAngularLimit(-90)
    slider.setUpperAngularLimit(-85)
    self.world.attachConstraint(slider)
  
  def setupObstacleFour(self, pos, scale, turn):
    #Start Here
    # Box A
    shape = BulletBoxShape(Vec3(0.01, 0.01, 0.01) * scale)
    bodyA = BulletRigidBodyNode('Box A')
    bodyNP = self.worldNP.attachNewNode(bodyA)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos.getX(), pos.getY(), pos.getZ() + 4) #(0, 0, 4)

    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(0.01, 0.01, 0.01)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)

    self.world.attachRigidBody(bodyA)

    # Box B
    shape = BulletSphereShape(0.5*scale)

    bodyB = BulletRigidBodyNode('Sphere B')
    bodyNP = self.worldNP.attachNewNode(bodyB)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(10.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos.getX(), pos.getY(), pos.getZ() + 5) #(0, 0, 0.001)

    visNP = loader.loadModel('media/models/ball.egg')
    visNP.clearModelNodes()
    visNP.setScale(1.25*scale)
    visNP.reparentTo(bodyNP)
    
    bodyNP.node().setLinearVelocity(100)

    self.world.attachRigidBody(bodyB)

    # Cone
    frameA = TransformState.makePosHpr(Point3(0, 0, 0), Vec3(0, 0, 90))
    frameB = TransformState.makePosHpr(Point3(2, 0, 0)*scale, Vec3(0, 0, 0))

    cone = BulletConeTwistConstraint(bodyA, bodyB, frameA, frameB)
    cone.setDebugDrawSize(2.0)
    cone.setLimit(30, 90, 270, softness=1.0, bias=0.3, relaxation=10.0)
    self.world.attachConstraint(cone)
    
    # Box C
    shape = BulletBoxShape(Vec3(0.1, 0.1, 1)*scale)

    bodyC = BulletRigidBodyNode('Box C')
    bodyNP = self.worldNP.attachNewNode(bodyC)
    bodyNP.node().addShape(shape)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos.getX(), pos.getY(), pos.getZ() + 3)
    
    self.world.attachRigidBody(bodyC)

    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(0.1, 0.1, 1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
  def setupObstacleSix(self, pos, scale, turn):
    #box A
    shape = BulletBoxShape(Vec3(0.1, 0.1, 0.1)*scale)
    
    bodyA = BulletRigidBodyNode('Box A')
    bodyNP= self.worldNP.attachNewNode(bodyA)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOff())
    bodyNP.setPos(pos.getX()-2,pos.getY(),pos.getZ()+2.5)#-2,0,2.5)
    bodyNP.setHpr(turn)
    
    # Box B
    shape = BulletBoxShape(Vec3(2, 0.1, 3)*scale)
    
    bodyB = BulletRigidBodyNode('Box B')
    bodyNP = self.worldNP.attachNewNode(bodyB)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(1.0)
    bodyNP.node().setLinearDamping(0.5)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos.getX()-3,pos.getY(), pos.getZ())#, 0, 0)
    bodyNP.setHpr(turn)
    
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(2, 0.1, 3)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyB)
    
    
    # Hinge
    pivotA = Point3(-2, 0, -3)
    pivotB = Point3(-2, 0, -3)
    axisA = Vec3(0, 0, 1)
    axisB = Vec3(0, 0, 1)
    
    hinge = BulletHingeConstraint(bodyA, bodyB, pivotA, pivotB, axisA, axisB, True)
    hinge.setDebugDrawSize(2.0)
    hinge.setLimit(0,90, softness=1.0, bias=0.3, relaxation=1.0)
    self.world.attachConstraint(hinge)
    
    #box A
    shape = BulletBoxShape(Vec3(0.1, 0.1, 0.1)*scale)
    
    bodyA = BulletRigidBodyNode('Box A')
    bodyNP= self.worldNP.attachNewNode(bodyA)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOff())
    bodyNP.setPos(pos.getX()+2,pos.getY(),pos.getZ()+2.5)#2,0,2.5)
    bodyNP.setHpr(turn)
    
    # Box B
    shape = BulletBoxShape(Vec3(2, 0.1, 3)*scale)
    
    bodyB = BulletRigidBodyNode('Box B')
    bodyNP = self.worldNP.attachNewNode(bodyB)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(1.0)
    bodyNP.node().setLinearDamping(0.5)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos.getX()+4, pos.getY(), pos.getZ())# 0, 0)
    bodyNP.setHpr(turn)
    
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(2, 0.1, 3)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyB)
    
    pivotA = Point3(2, 0, -3)
    pivotB = Point3(2, 0, -3)
    
    hinge = BulletHingeConstraint(bodyA, bodyB, pivotA, pivotB, axisA, axisB, True)
    hinge.setLimit(-90,0, softness=1.0, bias=0.3, relaxation=1.0)
    self.world.attachConstraint(hinge)
    
  def setupObstacleFive(self, pos, scale, turn):
    #box A
    shape = BulletBoxShape(Vec3(3, 0.1, 0.1)*scale)
    
    bodyA = BulletRigidBodyNode('Box A')
    bodyNP= self.worldNP.attachNewNode(bodyA)
    bodyNP.node().addShape(shape)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(3, 0.1, 0.1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyA)
    
    # Box B
    shape = BulletBoxShape(Vec3(3, 2, 0.1)*scale)
    
    bodyB = BulletRigidBodyNode('Box B')
    bodyNP = self.worldNP.attachNewNode(bodyB)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(1.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(3, 2, 0.1)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyB)
    
    # Hinge
    pivotA = Point3(0, 0, 0)
    pivotB = Point3(0, 0, 5)
    axisA = Vec3(1, 0, 0)
    axisB = Vec3(1, 0, 0)
    
    hinge = BulletHingeConstraint(bodyA, bodyB, pivotA, pivotB, axisA, axisB, True)
    hinge.setDebugDrawSize(2.0)
    hinge.setLimit(-50,50, softness=0.5, bias=0.3, relaxation=0.6)
    self.world.attachConstraint(hinge)
    
    # Box C
    shape = BulletBoxShape(Vec3(0.1, 0.1, 0.9)*scale)
    
    bodyC = BulletRigidBodyNode('Box C')
    bodyNP = self.worldNP.attachNewNode(bodyC)
    bodyNP.node().addShape(shape)
    bodyNP.node().setMass(1.0)
    bodyNP.node().setDeactivationEnabled(False)
    bodyNP.setCollideMask(BitMask32.allOn())
    bodyNP.setPos(pos)
    bodyNP.setHpr(turn)
    
    visNP = loader.loadModel('media/models/box.egg')
    visNP.setScale(Vec3(0.1, 0.1, 0.9)*2*scale)
    visNP.clearModelNodes()
    visNP.reparentTo(bodyNP)
    
    self.world.attachRigidBody(bodyC)
    
    pivotA = Point3(0, 0, -1.1)
    pivotB = Point3(0, 0, 1)
    
    hinge = BulletHingeConstraint(bodyA, bodyC, pivotA, pivotB, axisA, axisB, True)
    hinge.setLimit(-90,90, softness=1.0, bias=0.3, relaxation=1.0)
    self.world.attachConstraint(hinge)
    
  def setupGoal(self, pos):
      # Goal
      shape = BulletBoxShape(Vec3(1, 1, 1))

      body = BulletRigidBodyNode('Flag')

      self.flagNP = self.worldNP.attachNewNode(body)
      self.flagNP.node().addShape(shape)
      self.flagNP.setCollideMask(BitMask32.allOn())
      self.flagNP.setPos(pos)
      
      visNP = loader.loadModel('media/models/Flag.X')
      visNP.clearModelNodes()
      visNP.reparentTo(self.flagNP)
    
      self.world.attachRigidBody(body)
Пример #23
0
class TeamActivityGui:
    COUNTDOWN_TASK_NAME = 'updateCountdownTask'
    timer = None
    statusText = None
    countdownText = None
    exitButton = None
    switchButton = None

    def __init__(self, activity):
        self.activity = activity

    def load(self):
        buttonModels = loader.loadModel('phase_3.5/models/gui/inventory_gui')
        upButton = buttonModels.find('**//InventoryButtonUp')
        downButton = buttonModels.find('**/InventoryButtonDown')
        rolloverButton = buttonModels.find('**/InventoryButtonRollover')
        self.exitButton = DirectButton(
            relief=None,
            text=TTLocalizer.PartyTeamActivityExitButton,
            text_fg=(1, 1, 0.65, 1),
            text_pos=(0, -0.15),
            text_scale=0.5,
            image=(upButton, downButton, rolloverButton),
            image_color=(1, 0, 0, 1),
            image_scale=(14.5, 1, 9),
            pos=(0, 0, 0.8),
            scale=0.15,
            command=self.handleExitButtonClick)
        self.exitButton.hide()
        if self.activity.toonsCanSwitchTeams():
            self.switchButton = DirectButton(
                relief=None,
                text=TTLocalizer.PartyTeamActivitySwitchTeamsButton,
                text_fg=(1, 1, 1, 1),
                text_pos=(0, 0.1),
                text_scale=0.5,
                image=(upButton, downButton, rolloverButton),
                image_color=(0, 1, 0, 1),
                image_scale=(15, 1, 15),
                pos=(0, 0, 0.5),
                scale=0.15,
                command=self.handleSwitchButtonClick)
            self.switchButton.hide()
        else:
            self.switchButton = None
        buttonModels.removeNode()
        self.countdownText = OnscreenText(
            text='',
            pos=(0.0, -0.2),
            scale=PartyGlobals.TeamActivityTextScale * 1.2,
            fg=(1.0, 1.0, 0.65, 1.0),
            align=TextNode.ACenter,
            font=ToontownGlobals.getSignFont(),
            mayChange=True)
        self.countdownText.hide()
        self.statusText = OnscreenText(
            text='',
            pos=(0.0, 0.0),
            scale=PartyGlobals.TeamActivityTextScale,
            fg=PartyGlobals.TeamActivityStatusColor,
            align=TextNode.ACenter,
            font=ToontownGlobals.getSignFont(),
            mayChange=True)
        self.statusText.hide()
        self.timer = PartyUtils.getNewToontownTimer()
        self.timer.hide()
        return

    def unload(self):
        self.hideWaitToStartCountdown()
        if self.exitButton is not None:
            self.exitButton.destroy()
            self.exitButton = None
        if self.switchButton is not None:
            self.switchButton.destroy()
            self.switchButton = None
        if self.countdownText is not None:
            self.countdownText.destroy()
            self.countdownText.removeNode()
            self.countdownText = None
        if self.statusText is not None:
            self.statusText.destroy()
            self.statusText.removeNode()
            self.statusText = None
        if self.timer is not None:
            self.timer.destroy()
            del self.timer
        return

    def showStatus(self, text):
        self.statusText.setText(text)
        self.statusText.show()

    def hideStatus(self):
        self.statusText.hide()

    def enableExitButton(self):
        self.exitButton.show()

    def disableExitButton(self):
        self.exitButton.hide()

    def handleExitButtonClick(self):
        self.disableExitButton()
        self.disableSwitchButton()
        self.activity.d_toonExitRequest()

    def enableSwitchButton(self):
        self.switchButton.show()

    def disableSwitchButton(self):
        if self.switchButton is not None:
            self.switchButton.hide()
        return

    def handleSwitchButtonClick(self):
        self.disableSwitchButton()
        self.disableExitButton()
        self.activity.d_toonSwitchTeamRequest()

    def showWaitToStartCountdown(self,
                                 duration,
                                 waitToStartTimestamp,
                                 almostDoneCallback=None):
        self._countdownAlmostDoneCallback = almostDoneCallback
        currentTime = globalClock.getRealTime()
        waitTimeElapsed = currentTime - waitToStartTimestamp
        if duration - waitTimeElapsed > 1.0:
            countdownTask = Task(self._updateCountdownTask)
            countdownTask.duration = duration - waitTimeElapsed
            self.countdownText.setText(str(int(countdownTask.duration)))
            self.countdownText.show()
            taskMgr.remove(TeamActivityGui.COUNTDOWN_TASK_NAME)
            taskMgr.add(countdownTask, TeamActivityGui.COUNTDOWN_TASK_NAME)

    def hideWaitToStartCountdown(self):
        taskMgr.remove(TeamActivityGui.COUNTDOWN_TASK_NAME)
        self._countdownAlmostDoneCallback = None
        if self.countdownText is not None:
            self.countdownText.hide()
        return

    def _updateCountdownTask(self, task):
        countdownTime = int(task.duration - task.time)
        seconds = str(countdownTime)
        if self.countdownText['text'] != seconds:
            self.countdownText['text'] = seconds
            if countdownTime == 3 and self._countdownAlmostDoneCallback is not None:
                self._countdownAlmostDoneCallback()
                self._countdownAlmostDoneCallback = None
        if task.time >= task.duration:
            return Task.done
        else:
            return Task.cont
        return

    def showTimer(self, duration):
        self.timer.setTime(duration)
        self.timer.countdown(duration, self._handleTimerExpired)
        self.timer.show()

    def hideTimer(self):
        self.timer.hide()
        self.timer.stop()

    def _handleTimerExpired(self):
        self.activity.handleGameTimerExpired()
Пример #24
0
class MPBtn(GameObject):

    tooltip_align = TextNode.A_right
    tooltip_offset = (.01, 0, -.08)

    def __init__(self, parent, owner, menu_args, img_path, msg_btn_x, cb,
                 usr_name, tooltip):
        GameObject.__init__(self)
        self.owner = owner
        lab_args = menu_args.label_args
        lab_args['scale'] = .046
        #lab_args['text_fg'] = menu_args.text_normal
        self.btn = ImgBtn(parent=parent,
                          scale=.024,
                          pos=(msg_btn_x, 1, .01),
                          frameColor=(1, 1, 1, 1),
                          frameTexture=img_path,
                          command=cb,
                          extraArgs=[usr_name],
                          **menu_args.imgbtn_args)
        self.btn.bind(ENTER, self.on_enter)
        self.btn.bind(EXIT, self.on_exit)
        self.tooltip_btn = DirectButton(parent=parent,
                                        scale=.024,
                                        pos=(msg_btn_x, 1, .01),
                                        frameColor=(1, 1, 1, 0),
                                        frameSize=(-1, 1, -1, 1),
                                        command=None,
                                        **menu_args.imgbtn_args)
        self.tooltip_btn.bind(ENTER, self.on_enter)
        self.tooltip_btn.bind(EXIT, self.on_exit)
        self.on_create()
        self.tooltip = DirectLabel(text=tooltip,
                                   pos=self.btn.get_pos() +
                                   self.tooltip_offset,
                                   parent=parent,
                                   text_wordwrap=10,
                                   text_bg=(.2, .2, .2, .8),
                                   text_align=self.tooltip_align,
                                   **lab_args)
        self.tooltip.set_bin('gui-popup', 10)
        self.tooltip.hide()

    def on_create(self):
        self.btn.hide()
        self.tooltip_btn.hide()

    def is_hidden(self):
        return self.btn.is_hidden()

    def show(self):
        if self.btn['state'] == DISABLED:
            self.tooltip_btn.show()
        else:
            self.tooltip_btn.hide()
        return self.btn.show()

    def hide(self):
        self.tooltip_btn.hide()
        return self.btn.hide()

    def enable(self):
        self.tooltip_btn.hide()
        return self.btn.enable()

    def disable(self):
        self.tooltip_btn.show()
        return self.btn.disable()

    def on_enter(self, pos):
        self.owner.on_enter(pos)
        self.tooltip.show()

    def on_exit(self, pos):
        self.owner.on_exit(pos)
        self.tooltip.hide()
class NewsPageButtonManager(FSM.FSM):
    notify = DirectNotifyGlobal.directNotify.newCategory('NewsPageButtonManager')

    def __init__(self):
        FSM.FSM.__init__(self, 'NewsPageButtonManager')
        self.buttonsLoaded = False
        self.clearGoingToNewsInfo()
        self.__blinkIval = None
        self.load()
        return

    def load(self):
        btnGui = loader.loadModel('phase_3.5/models/gui/tt_m_gui_ign_newsBtnGui')
        bookModel = loader.loadModel('phase_3.5/models/gui/tt_m_gui_ign_shtickerBook')
        self.openNewNewsUp = btnGui.find('**/tt_t_gui_ign_new')
        self.openNewNewsUpBlink = btnGui.find('**/tt_t_gui_ign_newBlink')
        self.openNewNewsHover = btnGui.find('**/tt_t_gui_ign_newHover')
        self.openOldNewsUp = btnGui.find('**/tt_t_gui_ign_oldNews')
        self.openOldNewsHover = btnGui.find('**/tt_t_gui_ign_oldHover')
        self.closeNewsUp = bookModel.find('**/tt_t_gui_sbk_newsPage1')
        self.closeNewsHover = bookModel.find('**/tt_t_gui_sbk_newsPage2')
        btnGui.removeNode()
        bookModel.removeNode()
        oldScale = 0.5
        newScale = 0.9
        shtickerBookScale = 0.305
        newPos = VBase3(0.914, 0, 0.862)
        shtickerBookPos = VBase3(1.175, 0, -0.83)
        textScale = 0.06
        self.newIssueButton = DirectButton(relief=None, sortOrder=DGG.BACKGROUND_SORT_INDEX - 1, image=(self.openNewNewsUp, self.openNewNewsHover, self.openNewNewsHover), text=('', TTLocalizer.EventsPageNewsTabName, TTLocalizer.EventsPageNewsTabName), text_fg=(1, 1, 1, 1), text_shadow=(0, 0, 0, 1), text_scale=textScale, text_font=ToontownGlobals.getInterfaceFont(), pos=newPos, scale=newScale, command=self.__handleGotoNewsButton)
        self.gotoPrevPageButton = DirectButton(relief=None, image=(self.closeNewsUp, self.closeNewsHover, self.closeNewsHover), text_fg=(1, 1, 1, 1), text_shadow=(0, 0, 0, 1), text_scale=textScale, text_font=ToontownGlobals.getInterfaceFont(), pos=shtickerBookPos, scale=shtickerBookScale, command=self.__handleGotoPrevPageButton)
        self.goto3dWorldButton = DirectButton(relief=None, image=(self.closeNewsUp, self.closeNewsHover, self.closeNewsHover), text_fg=(1, 1, 1, 1), text_shadow=(0, 0, 0, 1), text_scale=textScale, text_font=ToontownGlobals.getInterfaceFont(), pos=shtickerBookPos, scale=shtickerBookScale, command=self.__handleGoto3dWorldButton)
        self.hideNewIssueButton()
        self.gotoPrevPageButton.hide()
        self.goto3dWorldButton.hide()
        self.accept('newIssueOut', self.handleNewIssueOut)
        bounce1Pos = VBase3(newPos.getX(), newPos.getY(), newPos.getZ() + 0.022)
        bounce2Pos = VBase3(newPos.getX(), newPos.getY(), newPos.getZ() + 0.015)
        bounceIval = Sequence(LerpPosInterval(self.newIssueButton, 0.1, bounce1Pos, blendType='easeOut'), LerpPosInterval(self.newIssueButton, 0.1, newPos, blendType='easeIn'), LerpPosInterval(self.newIssueButton, 0.07, bounce2Pos, blendType='easeOut'), LerpPosInterval(self.newIssueButton, 0.07, newPos, blendType='easeIn'))
        self.__blinkIval = Sequence(Func(self.__showOpenEyes), Wait(2), bounceIval, Wait(0.5), Func(self.__showClosedEyes), Wait(0.1), Func(self.__showOpenEyes), Wait(0.1), Func(self.__showClosedEyes), Wait(0.1))
        self.__blinkIval.loop()
        self.__blinkIval.pause()
        self.buttonsLoaded = True
        return

    def __showOpenEyes(self):
        self.newIssueButton['image'] = (self.openNewNewsUp, self.openNewNewsHover, self.openNewNewsHover)

    def __showClosedEyes(self):
        self.newIssueButton['image'] = (self.openNewNewsUpBlink, self.openNewNewsHover, self.openNewNewsHover)

    def clearGoingToNewsInfo(self):
        self.goingToNewsPageFrom3dWorld = False
        self.setGoingToNewsPageFromStickerBook(False)

    def __handleGotoNewsButton(self):
        currentState = base.localAvatar.animFSM.getCurrentState().getName()
        if currentState == 'jumpAirborne':
            return
        from toontown.toon import LocalToon
        if not LocalToon.WantNewsPage:
            return
        if base.cr and base.cr.playGame and base.cr.playGame.getPlace() and base.cr.playGame.getPlace().fsm:
            fsm = base.cr.playGame.getPlace().fsm
            curState = fsm.getCurrentState().getName()
            if curState == 'walk':
                if hasattr(localAvatar, 'newsPage'):
                    base.cr.centralLogger.writeClientEvent('news gotoNewsButton clicked')
                    localAvatar.book.setPage(localAvatar.newsPage)
                    fsm.request('stickerBook')
                    self.goingToNewsPageFrom3dWorld = True
            elif curState == 'stickerBook':
                if hasattr(localAvatar, 'newsPage'):
                    base.cr.centralLogger.writeClientEvent('news gotoNewsButton clicked')
                    fsm.request('stickerBook')
                    if hasattr(localAvatar, 'newsPage') and localAvatar.newsPage:
                        localAvatar.book.goToNewsPage(localAvatar.newsPage)

    def __handleGotoPrevPageButton(self):
        self.clearGoingToNewsInfo()
        localAvatar.book.setPageBeforeNews()
        self.showAppropriateButton()
        self.ignoreEscapeKeyPress()

    def __handleGoto3dWorldButton(self):
        localAvatar.book.closeBook()

    def hideNewIssueButton(self):
        if hasattr(self, 'newIssueButton') and self.newIssueButton:
            self.newIssueButton.hide()
            localAvatar.clarabelleNewsPageCollision(False)

    def __showNewIssueButton(self):
        self.newIssueButton.show()
        localAvatar.clarabelleNewsPageCollision(True)

    def hideAllButtons(self):
        if not self.buttonsLoaded:
            return
        self.gotoPrevPageButton.hide()
        self.goto3dWorldButton.hide()
        self.hideNewIssueButton()
        self.__blinkIval.pause()

    def isNewIssueButtonShown(self):
        if not base.cr.inGameNewsMgr:
            return False
            
        if localAvatar.getLastTimeReadNews() < base.cr.inGameNewsMgr.getLatestIssue():
            return True
            
        return False

    def enterHidden(self):
        self.hideAllButtons()

    def exitHidden(self):
        pass

    def enterNormalWalk(self):
        if not self.buttonsLoaded:
            return
            
        if not base.cr.inGameNewsMgr:
            return
            
        if localAvatar.getLastTimeReadNews() < base.cr.inGameNewsMgr.getLatestIssue():
            self.__showNewIssueButton()
            self.__blinkIval.resume()
            
        else:
            self.hideNewIssueButton()
            
        self.gotoPrevPageButton.hide()
        self.goto3dWorldButton.hide()

    def exitNormalWalk(self):
        if not self.buttonsLoaded:
            return
        self.hideAllButtons()

    def enterGotoWorld(self):
        if not self.buttonsLoaded:
            return
        self.hideAllButtons()
        self.goto3dWorldButton.show()

    def exitGotoWorld(self):
        if not self.buttonsLoaded:
            return
        self.hideAllButtons()
        localAvatar.book.setPageBeforeNews(enterPage=False)
        self.clearGoingToNewsInfo()

    def enterPrevPage(self):
        if not self.buttonsLoaded:
            return
        self.hideAllButtons()
        self.gotoPrevPageButton.show()

    def exitPrevPage(self):
        if not self.buttonsLoaded:
            return
        self.hideAllButtons()

    def showAppropriateButton(self):
        self.notify.debugStateCall(self)
        from toontown.toon import LocalToon
        if not LocalToon.WantNewsPage:
            return
        if not self.buttonsLoaded:
            return
        if base.cr and base.cr.playGame and base.cr.playGame.getPlace() and hasattr(base.cr.playGame.getPlace(), 'fsm') and base.cr.playGame.getPlace().fsm:
            fsm = base.cr.playGame.getPlace().fsm
            curState = fsm.getCurrentState().getName()
            book = localAvatar.book
            if curState == 'walk':
                if localAvatar.tutorialAck and not localAvatar.isDisguised and not isinstance(base.cr.playGame.getPlace(), CogHQBossBattle.CogHQBossBattle):
                    self.request('NormalWalk')
                else:
                    self.request('Hidden')
            elif curState == 'stickerBook':
                if self.goingToNewsPageFrom3dWorld:
                    if localAvatar.tutorialAck:
                        self.request('GotoWorld')
                    else:
                        self.request('Hidden')
                elif self.goingToNewsPageFromStickerBook or hasattr(localAvatar, 'newsPage') and localAvatar.book.isOnPage(localAvatar.newsPage):
                    if localAvatar.tutorialAck:
                        self.request('PrevPage')
                    else:
                        self.request('Hidden')
                elif localAvatar.tutorialAck:
                    self.request('NormalWalk')
                else:
                    self.request('Hidden')

    def setGoingToNewsPageFromStickerBook(self, newVal):
        self.goingToNewsPageFromStickerBook = newVal

    def enterOff(self):
        self.ignoreAll()
        if not self.buttonsLoaded:
            return
        if self.__blinkIval:
            self.__blinkIval.finish()
            self.__blinkIval = None
        self.newIssueButton.destroy()
        self.gotoPrevPageButton.destroy()
        self.goto3dWorldButton.destroy()
        del self.openNewNewsUp
        del self.openNewNewsUpBlink
        del self.openNewNewsHover
        del self.openOldNewsUp
        del self.openOldNewsHover
        del self.closeNewsUp
        del self.closeNewsHover
        return

    def exitOff(self):
        self.notify.warning('Should not get here. NewsPageButtonManager.exitOff')

    def simulateEscapeKeyPress(self):
        if self.goingToNewsPageFrom3dWorld:
            self.__handleGoto3dWorldButton()
        if self.goingToNewsPageFromStickerBook:
            self.__handleGotoPrevPageButton()

    def handleNewIssueOut(self):
        if localAvatar.isReadingNews():
            pass
        else:
            self.showAppropriateButton()

    def acceptEscapeKeyPress(self):
        self.accept(ToontownGlobals.StickerBookHotkey, self.simulateEscapeKeyPress)
        self.accept(ToontownGlobals.OptionsPageHotkey, self.simulateEscapeKeyPress)

    def ignoreEscapeKeyPress(self):
        self.ignore(ToontownGlobals.StickerBookHotkey)
        self.ignore(ToontownGlobals.OptionsPageHotkey)
Пример #26
0
class GUI:
    def __init__(self, rootParent=None):

        self.frmMain = DirectFrame(
            frameColor=(1.0, 1.0, 1.0, 0.0),
            frameSize=(-0.436, 0.45, -0.5, 0.5),
            hpr=LVecBase3f(0, 0, 0),
            image='./assets/inventory/InventoryPlate.png',
            pos=LPoint3f(-0.4, 0, 0.52),
            image_scale=LVecBase3f(0.436, 1, 0.5),
            image_pos=LPoint3f(0, 0, 0),
            parent=rootParent,
        )
        self.frmMain.setTransparency(1)

        self.frmWeapon = DirectFrame(
            frameColor=(1.0, 0.0, 1.0, 0.0),
            frameSize=(-0.09, 0.09, -0.242, 0.242),
            hpr=LVecBase3f(0, 0, 0),
            image='./assets/inventory/thief/weapon1.png',
            pos=LPoint3f(-0.165, 0, 0.15),
            image_scale=LVecBase3f(0.09, 0, 0.242),
            image_pos=LPoint3f(0, 0, 0),
            parent=self.frmMain,
        )
        self.frmWeapon.setTransparency(1)

        self.frmArmor = DirectFrame(
            frameColor=(1.0, 0.0, 1.0, 0.0),
            frameSize=(-0.09, 0.09, -0.242, 0.242),
            hpr=LVecBase3f(0, 0, 0),
            image='./assets/inventory/thief/weapon1.png',
            pos=LPoint3f(0.18, 0, 0.15),
            image_scale=LVecBase3f(0.09, 0, 0.242),
            image_pos=LPoint3f(0, 0, 0),
            parent=self.frmMain,
        )
        self.frmArmor.setTransparency(1)

        self.frmPotion1 = DirectFrame(
            frameColor=(0.0, 1.0, 1.0, 0.0),
            frameSize=(-0.1, 0.1, -0.1, 0.1),
            hpr=LVecBase3f(0, 0, 0),
            image='./assets/inventory/potions/Potion1.png',
            pos=LPoint3f(-0.23, 0, -0.315),
            image_scale=LVecBase3f(0.09, 0.09, 0.09),
            image_pos=LPoint3f(0, 0, 0),
            parent=self.frmMain,
        )
        self.frmPotion1.setTransparency(1)

        self.frmPotion2 = DirectFrame(
            frameColor=(0.0, 1.0, 1.0, 0.0),
            frameSize=(-0.1, 0.1, -0.1, 0.1),
            hpr=LVecBase3f(0, 0, 0),
            image='./assets/inventory/potions/Potion2.png',
            pos=LPoint3f(0, 0, -0.325),
            image_scale=LVecBase3f(0.09, 0.09, 0.09),
            image_pos=LPoint3f(0, 0, 0),
            parent=self.frmMain,
        )
        self.frmPotion2.setTransparency(1)

        self.frmPotion3 = DirectFrame(
            frameColor=(0.0, 1.0, 1.0, 0.0),
            frameSize=(-0.1, 0.1, -0.1, 0.1),
            hpr=LVecBase3f(0, 0, 0),
            image='./assets/inventory/potions/Potion3.png',
            pos=LPoint3f(0.25, 0, -0.315),
            image_scale=LVecBase3f(0.09, 0.1, 0.09),
            image_pos=LPoint3f(0, 0, 0),
            parent=self.frmMain,
        )
        self.frmPotion3.setTransparency(1)

        self.btnToggleInventory = DirectButton(
            frameColor=(0.15, 0.15, 0.15, 1.0),
            frameSize=(-0.4, 0.4, -0.02, 0.05),
            hpr=LVecBase3f(0, 0, 0),
            pos=LPoint3f(-0.4, 0, 0.02),
            relief=1,
            scale=LVecBase3f(1, 1, 1),
            text='Toggle Inventory',
            text_align=TextNode.A_center,
            text_scale=(0.05, 0.05),
            text_pos=(0, 0),
            text_fg=LVecBase4f(0.8, 0.8, 0.8, 1),
            text_bg=LVecBase4f(0, 0, 0, 0),
            parent=rootParent,
            command=base.messenger.send,
            extraArgs=["toggleInventory"],
            pressEffect=1,
        )
        self.btnToggleInventory.setTransparency(0)

    def show(self):
        self.frmMain.show()
        self.btnToggleInventory.show()

    def hide(self):
        self.frmMain.hide()
        self.btnToggleInventory.hide()

    def destroy(self):
        self.frmMain.destroy()
        self.btnToggleInventory.destroy()