Beispiel #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()
class CatalogRadioButton(NodePath):
    def __init__(self, parent, nodeName, clickEvent):
        NodePath.__init__(self, parent.attachNewNode(nodeName))

        self.radioButtons = []
        self.clickEvent = clickEvent

        self.normalNode = CatalogGlobals.CatalogNodePath.find('**/'+nodeName+'_UP').copyTo(self)
        self.clickedNode = CatalogGlobals.CatalogNodePath.find('**/'+nodeName+'_DN').copyTo(self)
        self.hoverNode = CatalogGlobals.CatalogNodePath.find('**/'+nodeName+'_OVR').copyTo(self)

        self.statusIndicator = CatalogGlobals.CatalogNodePath.find('**/'+nodeName+'Radio_ON').copyTo(self)
        self.statusIndicator.hide()

        self.radioButton = DirectButton(parent=self, relief=None, image=(self.normalNode, self.clickedNode, self.hoverNode), command=self.enable)

    def setOthers(self, radioButtons):
        self.radioButtons = radioButtons

    def enable(self):
        for radioButton in self.radioButtons:
            radioButton.disable()

        self.statusIndicator.show()
        self.clickEvent()

    def disable(self):
        self.statusIndicator.hide()

    def cleanup(self):
        self.radioButton.destroy()

        NodePath.removeNode(self)
Beispiel #3
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()
Beispiel #4
0
class cApplication( DirectObject ):
    def __init__( self ):
        # create world
        self.world = cWorld( )
        # setup controls
        self.setupControls( )
        # display title information
        self.title = OnscreenText( text = 'BOIDS.PY - SEEK & ARRIVE', fg = ( 1.0, 1.0, 1.0, 1.0), pos = ( -.98, .9 ), scale = 0.06 )
        # display copright information
        self.copyRight = OnscreenText( text = 'Copyright (C) 2016 David Lettier.', fg = ( 1.0, 1.0, 1.0, 1.0), pos = ( .98, -.98 ), scale = 0.05 )
        # display panda version text
        self.pandaVersion = OnscreenText( text = 'Panda Version 1.9.2', fg = ( 1.0, 1.0, 1.0, 1.0), pos = ( -1.18, -.98 ), scale = 0.04 )
        # display print debug button
        # this button calls the prntDebug function
        self.prntDebugButton = DirectButton( text = "Print Debug", relief = DGG.RAISED, scale = .1, pad = ( .5, .5 ), pos = Vec3( -1.0, 0.0, -.8 ), command = self.prntDebug )
    def setupControls( self ):
        # accept the esc key to exit application
        self.accept( 'escape', sys.exit )
    def prntDebug( self ):
        # destory debug button
        self.prntDebugButton.destroy( )
        # create new clear debug button
        # this button calls the clearDebug function
        self.clearDebugButton = DirectButton( text = "Clear Debug", relief = DGG.RAISED, scale = .1, pad = ( .5, .5 ), pos = Vec3( -1.0, 0.0, -.8 ), command = self.clearDebug )
        # create green target position text
        self.greenPos = OnscreenText( text = 'Green Target Pos: ' + str( int( self.world.target.getX( ) ) ) + ", " + str( int( self.world.target.getY( ) ) ) + ", " + str( int( self.world.target.getZ( ) ) ), fg = ( 1.0, 1.0, 1.0, 1.0), pos = ( -.8, .8 ), scale = 0.05, mayChange = True )
        # create blue boid position text
        self.bluePos = OnscreenText( text = 'Blue Boid (Arrive) Pos: ' + str( int( self.world.blueBoid.boidModel.getX( ) ) ) + ", " + str( int( self.world.blueBoid.boidModel.getY( ) ) ) + ", " + str( int( self.world.blueBoid.boidModel.getZ( ) ) ), fg = ( 1.0, 1.0, 1.0, 1.0), pos = ( -.8, .7 ), scale = 0.05, mayChange = True )
        # create green boid position text
        self.redPos = OnscreenText( text = 'Red Boid (Seek) Pos: ' + str( int( self.world.redBoid.boidModel.getX( ) ) ) + ", " + str( int( self.world.redBoid.boidModel.getY( ) ) ) + ", " + str( int( self.world.redBoid.boidModel.getZ( ) ) ), fg = ( 1.0, 1.0, 1.0, 1.0), pos = ( -.8, .6 ), scale = 0.05, mayChange = True )
        # add the update on screen text task
        taskMgr.add( self.updateOSTxt, 'updateOSTxt' )
    def updateOSTxt( self, Task ):
        # update green target position text
        self.greenPos.setText( 'Green Target Pos: ' + str( int( self.world.target.getX( ) ) ) + ", " + str( int( self.world.target.getY( ) ) ) + ", " + str( int( self.world.target.getZ( ) ) ) )
        # update blue boid position text
        self.bluePos.setText( 'Blue Boid (Arrive) Pos: ' + str( int( self.world.blueBoid.boidModel.getX( ) ) ) + ", " + str( int( self.world.blueBoid.boidModel.getY( ) ) ) + ", " + str( int( self.world.blueBoid.boidModel.getZ( ) ) ) )
        # update red boid position text
        self.redPos.setText( 'Red Boid (Seek) Pos: ' + str( int( self.world.redBoid.boidModel.getX( ) ) ) + ", " + str( int( self.world.redBoid.boidModel.getY( ) ) ) + ", " + str( int( self.world.redBoid.boidModel.getZ( ) ) ) )
        # call task next frame
        return Task.cont
    def clearDebug( self ):
        # destory button
        self.clearDebugButton.destroy( )
        # destory all debug on screen text
        self.greenPos.destroy( )
        self.bluePos.destroy( )
        self.redPos.destroy( )
        # remove task
        taskMgr.remove( 'updateOSTxt' )
        # create again the print debug button to start the cycle all over again
        self.prntDebugButton = DirectButton( text = "Print Debug", relief = DGG.RAISED, scale = .1, pad = ( .5, .5 ), pos = Vec3( -1.0, 0.0, -.8 ), command = self.prntDebug )
class CatalogArrowButton(NodePath):
    def __init__(self, parent, nodeName, clickEvent):
        NodePath.__init__(self, parent.attachNewNode(nodeName))

        self.clickEvent = clickEvent

        self.normalNode = CatalogGlobals.CatalogNodePath.find('**/arrow_UP_'+nodeName).copyTo(self)
        self.clickedNode = CatalogGlobals.CatalogNodePath.find('**/arrow_DN_'+nodeName).copyTo(self)
        self.hoverNode = CatalogGlobals.CatalogNodePath.find('**/arrow_OVR_'+nodeName).copyTo(self)

        self.arrowButton = DirectButton(parent=self, relief=None, image=(self.normalNode, self.clickedNode, self.hoverNode), command=self.clickEvent)

    def cleanup(self):
        self.arrowButton.destroy()

        NodePath.removeNode(self)
Beispiel #6
0
class CatalogRadioButton(NodePath):
    def __init__(self, parent, nodeName, clickEvent):
        NodePath.__init__(self, parent.attachNewNode(nodeName))

        self.radioButtons = []
        self.clickEvent = clickEvent

        self.normalNode = CatalogGlobals.CatalogNodePath.find(
            '**/' + nodeName + '_UP').copyTo(self)
        self.clickedNode = CatalogGlobals.CatalogNodePath.find(
            '**/' + nodeName + '_DN').copyTo(self)
        self.hoverNode = CatalogGlobals.CatalogNodePath.find(
            '**/' + nodeName + '_OVR').copyTo(self)

        self.statusIndicator = CatalogGlobals.CatalogNodePath.find(
            '**/' + nodeName + 'Radio_ON').copyTo(self)
        self.statusIndicator.hide()

        self.radioButton = DirectButton(parent=self,
                                        relief=None,
                                        image=(self.normalNode,
                                               self.clickedNode,
                                               self.hoverNode),
                                        command=self.enable)

    def setOthers(self, radioButtons):
        self.radioButtons = radioButtons

    def enable(self):
        for radioButton in self.radioButtons:
            radioButton.disable()

        self.statusIndicator.show()
        self.clickEvent()

    def disable(self):
        self.statusIndicator.hide()

    def cleanup(self):
        self.radioButton.destroy()

        NodePath.removeNode(self)
class CatalogArrowButton(NodePath):
    def __init__(self, parent, nodeName, clickEvent):
        NodePath.__init__(self, parent.attachNewNode(nodeName))
        self.clickEvent = clickEvent
        self.normalNode = CatalogGlobals.CatalogNodePath.find(
            '**/arrow_UP_' + nodeName).copyTo(self)
        self.clickedNode = CatalogGlobals.CatalogNodePath.find(
            '**/arrow_DN_' + nodeName).copyTo(self)
        self.hoverNode = CatalogGlobals.CatalogNodePath.find(
            '**/arrow_OVR_' + nodeName).copyTo(self)
        self.arrowButton = DirectButton(parent=self,
                                        relief=None,
                                        image=(self.normalNode,
                                               self.clickedNode,
                                               self.hoverNode),
                                        command=self.clickEvent)

    def cleanup(self):
        self.arrowButton.destroy()
        NodePath.removeNode(self)
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()
Beispiel #9
0
class Connect4:
    def __init__(self, p_base):

        self.base = p_base
        self.render = p_base.render

        # Keyboard inputs map
        self.keyMap = {"left": False, "right": False, "down": False, "drop": False}

        # Global parameters
        self.player = 1
        self.speed = 15
        self.movement_V = False
        self.movement_H = False
        self.axes_H = [-3.6, -2.4, -1.2, 0, 1.2, 2.4, 3.6]
        self.axes_V = [0.25, -1.0, -2.25, -3.5, -4.75, -6]
        self.column = 3
        self.line = 5
        self.quit_game_bool = False
        self.round = 0

        # Initialization of audio coin
        self.audio_coin = self.base.loader.loadMusic("connect4/audio/coin.ogg")

        # Initialization of the table
        self.table = self.base.loader.loadModel("connect4/models/table")
        self.table.reparentTo(self.render)
        self.table.setScale(2, 2, 2)
        self.table.setHpr(90, 0, 0)
        self.table_anim_start = self.table.posInterval(3, Point3(0, 30, -8), startPos=Point3(0, 0, -8))
        self.table_anim_end = self.table.posInterval(3, Point3(0, 0, -8), startPos=Point3(0, 30, -8))

        # Initialization of the grid
        self.grid = self.base.loader.loadModel("connect4/models/grid")
        self.grid.reparentTo(self.render)
        self.grid.setColor(0.1, 0.2, 0.8, 1.0)
        self.grid.setHpr(90, 0, 0)
        self.grid.setScale(0.6, 0.6, 0.625)
        self.grid_anim_start = self.grid.posInterval(3, Point3(3.6, 30, -6), startPos=Point3(3.6, 30, 0))
        self.grid_anim_end = self.grid.posInterval(3, Point3(3.6, 30, 0), startPos=Point3(3.6, 30, -6))
        self.gridContent = np.zeros(6 * 7)

        # Initialization of the discs
        self.discs = []
        self.nb_discs = 44
        for i in range(0, self.nb_discs):
            disc = self.base.loader.loadModel("connect4/models/disc")
            disc.reparentTo(self.render)
            if i % 2 == 0:
                color_disc = Disc(i, disc, 1.0, 0.0, 0.0)
            else:
                color_disc = Disc(i, disc, 1.0, 1.0, 0.0)
            self.discs.append(color_disc)
        self.first_disc_anim = self.discs[self.round].disc.posInterval(3, Point3(0, 30, 1.5), startPos=Point3(0, 0, 8))

        # Initialization of start sequences
        self.init_sequence = Parallel(self.table_anim_start, self.grid_anim_start, self.first_disc_anim, name="p_start")
        self.init_sequence.start()

        # Initialization of keys
        self.base.accept("arrow_left", self.updateKeyMap, ["left", True])
        self.base.accept("arrow_left-up", self.updateKeyMap, ["left", False])
        self.base.accept("arrow_right", self.updateKeyMap, ["right", True])
        self.base.accept("arrow_right-up", self.updateKeyMap, ["right", False])
        self.base.accept("arrow_down", self.updateKeyMap, ["down", True])
        self.base.accept("arrow_down-up", self.updateKeyMap, ["down", False])
        self.base.accept("space", self.updateKeyMap, ["drop", True])
        self.base.accept("space-up", self.updateKeyMap, ["drop", False])

        # Initialization of winning cases
        self.results = []
        with open("connect4/csv/cases.csv") as csvfile:
            reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNUMERIC)
            for row in reader:
                self.results.append(row)

        # Initialization of fonts
        self.font = self.base.loader.loadFont("connect4/font/Roboto-Medium.ttf")
        self.font.setPixelsPerUnit(60)

        # Initialization of the victory text
        self.text_victory = OnscreenText(text='', pos=(1.4, -0.8), scale=0.1)
        self.text_victory.setFg((0, 0, 0, 1))
        self.text_victory.setBg((1, 1, 1, 0))
        self.text_victory.setShadow((0.5, 0.5, 0.5, 1))

        # Initialization of buttons
        self.load_game_button = DirectButton(text="Load", pos=(-1.5, 0, 0.75), frameSize=(-3, 3, -0.5, 1), scale=.1,
                                             text_scale=0.9, command=self.load_game)

        self.new_game_button = DirectButton(text="New game", pos=(-1.5, 0, 0.9), frameSize=(-3, 3, -0.5, 1), scale=.1,
                                            text_scale=0.9, command=self.new_game)
        self.button_changed = False

        self.save_game_button = DirectButton(text="Save", pos=(-1.5, 0, 0.6), frameSize=(-3, 3, -0.5, 1), scale=.1,
                                             text_scale=0.9, command=self.save_game)

        self.quit_game_button = DirectButton(text="Quit", pos=(-1.5, 0, -0.95), frameSize=(-3, 3, -0.5, 1), scale=.1,
                                             text_scale=0.9, command=self.quit_game)

        self.hand_control_button = DirectButton(text="Activer le contrôle \n visuel", pos=(1.5, 0, -0.9), frameSize=(-3, 3, -1, 0.8), scale=.1,
                                             text_scale=0.5, command=self.activate_hand_control)
        # Mode
        # (mode 0 : default mode)
        # (mode 1 : hand control mode)
        self.mode = 0

        self.disc_caught = -1
        self.disc_dropped = -1

        # Initialization of the right hand
        self.right_hand = self.base.loader.loadModel("connect4/models/hand")
        self.right_hand.reparentTo(self.render)
        self.right_hand.setPos(3.6, -20, 0)
        self.right_hand.setColor(0.88, 0.67, 0.41, 1.0)
        self.right_hand.setHpr(90, -90, 0)
        self.right_hand.setScale(0.2, 0.2, 0.2)

        # self.left_hand = self.base.loader.loadModel("connect4/models/hand")
        # self.left_hand.reparentTo(self.render)
        # self.left_hand.setPos(-3.6, -20, 0)
        # self.left_hand.setColor(0.88, 0.67, 0.41, 1.0)
        # self.left_hand.setHpr(90, -90, 180)
        # self.left_hand.setScale(0.2, 0.2, 0.2)

    def activate_hand_control(self):
        if self.mode == 0:
            self.mode = 1
            self.hand_control_button.setText("Désactiver le contrôle \n visuel")
            self.right_hand.setPos(3.6, 30, 0)
            self.new_game()
            # self.left_hand.setPos(-3.6, 20, 0)
        else:
            self.mode = 0
            self.hand_control_button.setText("Activer le contrôle \n visuel")
            self.right_hand.setPos(3.6, -20, 0)
            self.new_game()
            # self.left_hand.setPos(-3.6, -20, 0)

    def updateKeyMap(self, key, state):
        """ Function that updates the input map """
        self.keyMap[key] = state

    def load_game(self):
        """ Load game functions used for load game button """
        print("Connect 4 > Load a game")
        f1 = open("connect4/safeguard/safeguard.txt", "r")
        last_line = f1.readlines()[-1]
        f1.close()
        last_line_list = last_line.split(',')
        k = 0
        p = 1
        round = 0
        for i in range(0, 42):
            col = i % 7
            line = i // 7
            if last_line_list[i] == '1':
                self.discs[k].disc.setPos(self.axes_H[col], 30, self.axes_V[line])
                k += 2
                round += 1
            elif last_line_list[i] == '2':
                self.discs[p].disc.setPos(self.axes_H[col], 30, self.axes_V[line])
                p += 2
                round += 1
        self.round = round
        self.discs[self.round].disc.setPos(0, 30, 1.5)
        self.gridContent = [int(j) for j in last_line_list]

    def new_game(self):
        """ New game functions used for new game button """
        print("Connect 4 > New game")

        self.gridContent = np.zeros(6 * 7)
        self.round = 0
        self.text_victory.setText('')

        if self.mode == 0:
            for i in range(0, 42):
                self.discs[i].disc.setPos(100, 100, 100)
            self.discs[self.round].disc.setPos(0, 30, 1.5)

        elif self.mode == 1:
            pos_xr = [-8.4, -7.2, -6.0,
                      -12, -10.8, -9.6, -8.4, -7.2, -6.0,
                      -12, -10.8, -9.6, -8.4, -7.2, -6.0,
                      -12, -10.8, -9.6, -8.4, -7.2, -6.0]
            pos_xy = [8.4, 7.2, 6.0,
                      12, 10.8, 9.6, 8.4, 7.2, 6.0,
                      12, 10.8, 9.6, 8.4, 7.2, 6.0,
                      12, 10.8, 9.6, 8.4, 7.2, 6.0]
            pos_z = [-6.4, -6.4, -6.4,
                     -5.2, -5.2, -5.2, -5.2, -5.2, -5.2,
                     -4.0, -4.0, -4.0, -4.0, -4.0, -4.0,
                     -2.8, -2.8, -2.8, -2.8, -2.8, -2.8]
            n = 0
            p = 0
            for i in range(0, 42):
                if i % 2 == 0:
                    self.discs[i].disc.setPos(pos_xr[n], 30, pos_z[n])
                    n += 1
                else:
                    self.discs[i].disc.setPos(pos_xy[p], 30, pos_z[p])
                    p += 1

    def save_game(self):
        """ Save game functions used for save game button """
        print("Connect 4 > Save the game")
        grid = [int(j) for j in self.gridContent]
        grid_content_str = ','.join([str(elem) for elem in grid])
        f = open("connect4/safeguard/safeguard.txt", "a")
        f.write(grid_content_str + "\n")
        f.close()

    def quit_game(self):
        """ Quit game functions used for quit game button """
        print("Connect 4 > Quit the game")
        for i in range(0, self.nb_discs):
            self.discs[i].disc.removeNode()
        self.grid.removeNode()
        self.table.removeNode()
        self.new_game_button.destroy()
        self.save_game_button.destroy()
        self.load_game_button.destroy()
        self.quit_game_button.destroy()
        self.quit_game_bool = True

    def check_victory(self):
        """
        Function that check if there is a victory case
        @return 1 if red wins and 2 if yellow wins
        """

        if self.mode == 0:
            num_disc = self.round
        elif self.mode == 1:
            num_disc = self.disc_dropped

        if num_disc % 2 == 0:
            disc_type = 1
        else:
            disc_type = 2
        self.gridContent[7 * self.line + self.column] = disc_type

        for i in range(69):
            for j in range(4):
                if self.results[i][j] == 7 * self.line + self.column:
                    if (self.gridContent[int(self.results[i][0])] == disc_type) and (
                            self.gridContent[int(self.results[i][1])] == disc_type) and (
                            self.gridContent[int(self.results[i][2])] == disc_type) and (
                            self.gridContent[int(self.results[i][3])] == disc_type):
                        return disc_type
        return 0

    def mainloop(self):
        """ Main loop of the connect 4 game """

        # If quit_button is clicked
        if self.quit_game_bool:
            return 0

        # Get the clock
        dt = globalClock.getDt()

        # Change the button "New game" to "Restart" for the first round
        if self.round == 1 and self.button_changed == False:
            self.new_game_button["text"] = "Restart"
            self.button_changed = True
            print("Connect 4 > Main loop")

        # Default mode
        if self.mode == 0:

            # Get the position of the current disc
            pos = self.discs[self.round].disc.getPos()

            # Left click
            if self.keyMap["left"] and self.column != 0 and not self.movement_V:
                self.keyMap["left"] = False
                self.column -= 1
                self.movement_H = True

            # Right click
            if self.keyMap["right"] and self.column != 6 and not self.movement_V:
                self.keyMap["right"] = False
                self.column += 1
                self.movement_H = True

            # down clic
            if self.keyMap["down"] and self.gridContent[self.column] == 0 and not self.movement_V:
                # To have only one click
                self.keyMap["down"] = False

                # Find the final disc line
                line_fixed = 0
                self.line = 5
                while line_fixed == 0 and self.line >= 0:
                    if self.gridContent[7 * self.line + self.column] != 0:
                        self.line -= 1
                    else:
                        line_fixed = 1
                self.movement_V = True

                # check if there is a victory or not
                victory = self.check_victory()
                if victory == 1:
                    self.text_victory.setText('Red wins')
                if victory == 2:
                    self.text_victory.setText('Yellow wins')

            # Progressive vertical movement
            if self.movement_V and pos.z >= self.axes_V[self.line]:
                pos.z -= self.speed * dt
                self.discs[self.round].disc.setPos(pos)

            # Set the disc position / Prepare next disc
            if self.movement_V and pos.z <= self.axes_V[self.line]:
                pos.z = self.axes_V[self.line]
                self.discs[self.round].disc.setPos(pos)
                self.audio_coin.play()
                self.movement_V = False
                self.line = 0
                self.column = 3
                self.round += 1
                if self.round < 42 and self.mode == 0:
                    self.discs[self.round].disc.setPos(0, 30, 1.5)

            # Horizontal movement
            if self.mode == 0 and self.movement_H:
                pos.x = self.axes_H[self.column]
                self.discs[self.round].disc.setPos(pos)
                self.movement_H = False

        # Handplay mode
        if self.mode == 1:

            # Detect hand position
            if cap.isOpened():
                success, image = cap.read()

                image = cv2.cvtColor(cv2.flip(image, 1), cv2.COLOR_BGR2RGB)

                image.flags.writeable = False
                results = hands.process(image)

                # Draw the hand annotations on the image.
                image.flags.writeable = True
                image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

                # If a hand is detected
                if results.multi_hand_landmarks:
                    for hand_landmarks in results.multi_hand_landmarks:
                        for idx, landmark in enumerate(hand_landmarks.landmark):
                            if idx == 9:
                                x = 24 * landmark.x - 12
                                z = - 14 * landmark.y + 7
                                self.right_hand.setPos(x, 30, z)

                # If a is caught
                if self.disc_caught != -1:
                    self.discs[self.disc_caught].disc.setPos(self.right_hand.getPos().x - 0.5, 30, self.right_hand.getPos().z + 0.5)
                else:
                    for i in range(0, 42):
                        if (abs(self.right_hand.getPos().x - 0.5 - self.discs[i].disc.getPos().x) < 0.5) \
                                and abs(self.right_hand.getPos().z - self.discs[i].disc.getPos().z) < 0.5:
                            self.disc_caught = self.discs[i].id
                            print("Connect 4 > Disc n°", self.disc_caught, " is caught")
                            self.discs[self.disc_caught].disc.setPos(x - 0.5, 30, z + 0.5)

                # If space touch is pressed
                if self.keyMap["drop"]:
                    print("Connect 4 > Disc n°", self.disc_caught, " is dropped")
                    self.keyMap["drop"] = False
                    pos_x = self.discs[self.disc_caught].disc.getPos().x
                    min = 10
                    for i in range(len(self.axes_H)):
                        if abs(self.axes_H[i] - pos_x) < min:
                            self.column = i
                            min = abs(self.axes_H[i] - pos_x)

                    # Find the final disc line
                    line_fixed = 0
                    self.line = 5
                    while line_fixed == 0 and self.line >= 0:
                        if self.gridContent[7 * self.line + self.column] != 0:
                            self.line -= 1
                        else:
                            line_fixed = 1
                    self.movement_V = True

                    self.discs[self.disc_caught].disc.setPos(self.axes_H[self.column], 30, self.axes_V[0])
                    self.disc_dropped = self.disc_caught
                    self.disc_caught = -1

                    # check if there is a victory or not
                    victory = self.check_victory()
                    if victory == 1:
                        self.text_victory.setText('Red wins')
                    if victory == 2:
                        self.text_victory.setText('Yellow wins')

                # Progressive vertical movement
                pos = self.discs[self.disc_dropped].disc.getPos()
                if self.movement_V and pos.z >= self.axes_V[self.line]:
                    pos.z -= self.speed * dt
                    self.discs[self.disc_dropped].disc.setPos(pos)

                # Set the disc position
                if self.movement_V and pos.z <= self.axes_V[self.line]:
                    pos.z = self.axes_V[self.line]
                    self.discs[self.disc_dropped].disc.setPos(pos)
                    self.audio_coin.play()
                    self.movement_V = False
                    self.line = 0
                    self.column = 3
                    self.round += 1







        return 1
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()
Beispiel #11
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()
Beispiel #12
0
def test_button_destroy():
    btn = DirectButton(text="Test")
    btn.destroy()
Beispiel #13
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()
Beispiel #14
0
class MainMenu(ShowBase):

    def __init__(self):

        ShowBase.__init__(self)

        #load background image
        self.__image = OnscreenImage(image='../../resources/images/main_menu.jpg', pos=(0, 0, 0), scale=1)
        self.__image.setSx(self.getAspectRatio())
        self.__image.setTransparency(TransparencyAttrib.MAlpha)

        #Three main opertaions
        self.__newGameButton = DirectButton(pos=(-0.9, 0, 0.5,), text=("新的游戏"), scale=0.1,
                                            command=self.new_game,frameColor=(0,0,0,0),
                                            image=("../../resources/images/main_menu.jpg","../../resources/images/main_menu.jpg",
                                                   "../../resources/images/main_menu.jpg"))
        self.__selectArchiveButton = DirectButton(pos=(-0.9, 0, 0.3,), text="选择存档", scale=0.1,text_fg=(1,1,1,1),
                                            command=self.select_archives, frameColor=(0, 0, 0, 0),
                                            image=("../../resources/images/main_menu.jpg", "../../resources/images/main_menu.jpg",
                                                   "../../resources/images/main_menu.jpg"))
        self.__exitGameButton = DirectButton(pos=(-0.9, 0, 0.1,), text="退出游戏", scale=0.1,text_fg=(1,1,1,1),
                                            command=self.exit_game, frameColor=(0, 0, 0, 0),
                                            image=("../../resources/images/main_menu.jpg", "../../resources/images/main_menu.jpg",
                                                   "../../resources/images/main_menu.jpg"))

        #add task to update background-image scale
        self.taskMgr.add(self.example_task, 'exampleTask')

        self.__rm=ResourcesManager()


    # 移除界面上的按钮与图片
    def destroy_all(self):
        self.__newGameButton.destroy()
        self.__selectArchiveButton.destroy()
        self.__exitGameButton.destroy()
        self.__image.destroy()
        self.taskMgr.remove('exampleTask')

    def new_game(self):
        self.destroy_all()

        self.__blood = Blood()
        # self.__rm.show_dialog(1)
        self.accept("a", self.__rm.show_dialog, [1])
        self.accept("b", self.__rm.show_dialog, [2])
        self.accept("x", self.__rm.show_dialog, [3])
        self.accept("c", self.__rm.dialog_next)
        # self.accept("d", self.__rm.play_sound,[2])
        # self.accept("e", self.__rm.stop_sound,[2])
        # self.accept("f", self.__rm.play_sound,[4])
        # self.accept("g", self.__rm.stop_sound,[4])

        self.accept("z",self.__rm.set_path,["123"])
        self.accept("y", self.__rm.show_dialog, [4])
        self.accept("k", self.__rm.show_dialog, [9])

        self.accept("0", self.__blood.init_blood)
        self.accept("1",self.__blood.bloodAdd)
        self.accept("2", self.__blood.bloodMinu)

        #调用对话
        # lp=LoadPlot()
        # lp.init_interface()
        #调用声音
        # ms=MySound()
        # ms.volume_slider()
        #调用视频
        self.accept("h", self.__rm.play_media, [self.render2d,1])
        self.accept("i", self.__rm.play_media, [self.render2d,2])
        self.accept("i", self.__rm.destroy_media)

    def select_archives(self):
        self.destroy__all()

    def exit_game(self):
        self.destroy__all()

    def example_task(self,task):
        self.__image.setSx(self.getAspectRatio())
        return Task.cont
Beispiel #15
0
class CustomizeScreen(DirectFrame):
    notify = directNotify.newCategory('CustomizeScreen')

    def __init__(self, callback, **kw):
        self._callback = callback
        geom = loader.loadModel('phase_6/models/gui/ui_frame')
        optiondefs = (('relief', None, None), ('geom', geom,
                                               None), ('geom_scale', 1.5, 1.5),
                      ('text', base.localAvatar.getName(),
                       None), ('text_align', TextNode.ACenter, None),
                      ('text_font', FONT, None), ('text_scale', 0.075, None),
                      ('text_pos', (0, 0.65), None), ('pos', (-0.7, 0, 0.16),
                                                      None))
        self.defineoptions(kw, optiondefs)
        DirectFrame.__init__(self, aspect2d)
        self.initialiseoptions(CustomizeScreen)

        self.genderOptions = None
        self.genderLabel = None
        self.speciesOptions = None
        self.speciesLabel = None
        self.legOptions = None
        self.legLabel = None
        self.torsoOptions = None
        self.torsoLabel = None
        self.headOptions = None
        self.headLabel = None
        self.muzzleOptions = None
        self.muzzleLabel = None
        self.gloveOptions = None
        self.gloveLabel = None
        self.headColorOptions = None
        self.headColorLabel = None
        self.armColorOptions = None
        self.armColorLabel = None
        self.legColorOptions = None
        self.legColorLabel = None
        self.shirtColorOptions = None
        self.shirtColorLabel = None
        self.bottomsColorOptions = None
        self.bottomsColorLabel = None
        self.shirtLabel = None
        self.shirtEntry = None
        self.shortsLabel = None
        self.shortsEntry = None
        self.doneButton = None

        geom.removeNode()
        rotateGeoms = loader.loadModel('phase_6/models/gui/ui_arrow_buttons')
        leftGeom = (rotateGeoms.find('**/*ArrowLeft*Up'),
                    rotateGeoms.find('**/*ArrowLeft*Down'),
                    rotateGeoms.find('**/*ArrowLeft*Rollover'))

        rightGeom = (rotateGeoms.find('**/*ArrowRight*Up'),
                     rotateGeoms.find('**/*ArrowRight*Down'),
                     rotateGeoms.find('**/*ArrowRight*Rollover'))
        self.leftButton = DirectButton(parent=self,
                                       relief=None,
                                       image=leftGeom,
                                       pos=(-0.11, 0, -0.07))
        self.rightButton = DirectButton(parent=self,
                                        relief=None,
                                        image=rightGeom,
                                        pos=(0.11, 0, -0.07))

        self.leftButton.bind(DGG.B1PRESS, self.__rotateToon, [-3])
        self.leftButton.bind(DGG.B1RELEASE, self.__stopRotation)
        self.rightButton.bind(DGG.B1PRESS, self.__rotateToon, [3])
        self.rightButton.bind(DGG.B1RELEASE, self.__stopRotation)
        rotateGeoms.removeNode()

        self.toon = None
        self.dna = None
        self.pitch = self.attachNewNode('pitch')
        self.rotate = self.pitch.attachNewNode('rotate')
        self.scale = self.rotate.attachNewNode('scale')
        self.pitch.setP(0)

        self.makeToon()

    def makeToon(self, dna=None):
        if self.toon:
            self.toon.cleanup()
            self.toon.delete()
            self.toon.removeNode()
            self.toon = None
            self.dna = None

        if not dna:
            dna = base.localAvatar.getDNAString()

        self.toon = Toon.Toon()
        self.dna = ToonDNA.ToonDNA()
        self.dna.makeFromNetString(dna)
        self.toon.setDNA(self.dna)
        self.toon.getGeomNode().setDepthWrite(1)
        self.toon.getGeomNode().setDepthTest(1)
        self.toon.setHpr(180, 0, 0)
        self.toon.setZ(-0.45)

        scaleFactor = 0.2
        if self.dna.legs == 'l':
            scaleFactor = 0.19

        self.toon.setScale(scaleFactor)
        self.toon.reparentTo(self.scale)

    def __rotateToon(self, *args):
        taskMgr.add(self.__rotateTask,
                    'toonRotateTask',
                    extraArgs=[args[0]],
                    appendTask=True)

    def __rotateTask(self, direction, task):
        if hasattr(self, 'pitch'):
            self.pitch.setH((self.pitch.getH() % 360) + 0.4 * direction)
            return task.cont
        else:
            return task.done

    def __stopRotation(self, *args):
        taskMgr.remove('toonRotateTask')

    def __selectHead(self, *args):
        species = name2code.get(args[0].lower())

        newDNA = ToonDNA.ToonDNA()
        newDNA.makeFromNetString(self.dna.makeNetString())
        newDNA.updateToonProperties(head=species + self.dna.head[1:])
        self.makeToon(newDNA.makeNetString())

    def __selectLegs(self, *args):
        legs = args[0].lower()
        if legs == 'long':
            legs = 'l'
        elif legs == 'medium':
            legs = 'm'
        else:
            legs = 's'

        newDNA = ToonDNA.ToonDNA()
        newDNA.makeFromNetString(self.dna.makeNetString())

        newDNA.updateToonProperties(legs=legs)
        self.makeToon(newDNA.makeNetString())

    def __selectGloves(self, *args):
        color = args[0]

        if color == 'White':
            index = len(ToonDNA.NumToColor) + 1
        else:
            index = ToonDNA.NumToColor.index(color)

        newDNA = ToonDNA.ToonDNA()
        newDNA.makeFromNetString(self.dna.makeNetString())
        newDNA.updateToonProperties(gloveColor=index)
        self.makeToon(newDNA.makeNetString())

    def __selectTorso(self, *args):
        torso = args[0][0].lower()
        if self.dna.gender == 'f':
            torso += 'd'
        else:
            torso += 's'

        newDNA = ToonDNA.ToonDNA()
        newDNA.makeFromNetString(self.dna.makeNetString())
        newDNA.updateToonProperties(torso=torso)
        self.makeToon(newDNA.makeNetString())

    def __selectHeadSize(self, *args):
        size = args[0][0].lower()
        head = self.dna.head

        newDNA = ToonDNA.ToonDNA()
        newDNA.makeFromNetString(self.dna.makeNetString())
        newDNA.updateToonProperties(head=head[0] + size + head[2])
        self.makeToon(newDNA.makeNetString())

    def __selectMuzzleSize(self, *args):
        size = args[0][0].lower()
        head = self.dna.head

        newDNA = ToonDNA.ToonDNA()
        newDNA.makeFromNetString(self.dna.makeNetString())
        newDNA.updateToonProperties(head=head[0] + head[1] + size)
        if newDNA.head in ToonDNA.toonHeadTypes:
            self.makeToon(newDNA.makeNetString())

    def __selectGender(self, *args):
        gender = args[0].lower()
        if gender == 'boy':
            gender = 'm'
        else:
            gender = 'f'

        newDNA = ToonDNA.ToonDNA()
        newDNA.makeFromNetString(self.dna.makeNetString())
        #newDNA.updateToonProperties(gender=gender)
        newDNA.updateToonProperties(gender=gender, bottomTexture=0)
        self.makeToon(newDNA.makeNetString())

    def __choseHeadColor(self, *args):
        color = args[0]

        if color == 'White':
            index = len(ToonDNA.NumToColor) + 1
        else:
            index = ToonDNA.NumToColor.index(color)
        newDNA = ToonDNA.ToonDNA()
        newDNA.makeFromNetString(self.dna.makeNetString())
        newDNA.updateToonProperties(headColor=index)
        self.makeToon(newDNA.makeNetString())

    def __choseArmColor(self, *args):
        color = args[0]

        if color == 'White':
            index = len(ToonDNA.NumToColor) + 1
        else:
            index = ToonDNA.NumToColor.index(color)
        newDNA = ToonDNA.ToonDNA()
        newDNA.makeFromNetString(self.dna.makeNetString())
        newDNA.updateToonProperties(armColor=index)
        self.makeToon(newDNA.makeNetString())

    def __choseLegColor(self, *args):
        color = args[0]

        if color == 'White':
            index = len(ToonDNA.NumToColor) + 1
        else:
            index = ToonDNA.NumToColor.index(color)
        newDNA = ToonDNA.ToonDNA()
        newDNA.makeFromNetString(self.dna.makeNetString())
        newDNA.updateToonProperties(legColor=index)
        self.makeToon(newDNA.makeNetString())

    def __choseShirtColor(self, *args):
        color = args[0]
        index = ToonDNA.ClothesColorNames.index(color)
        newDNA = ToonDNA.ToonDNA()
        newDNA.makeFromNetString(self.dna.makeNetString())
        newDNA.updateToonProperties(topTextureColor=index,
                                    sleeveTextureColor=index)
        self.makeToon(newDNA.makeNetString())

    def __choseShortsColor(self, *args):
        color = args[0]
        index = ToonDNA.ClothesColorNames.index(color)
        newDNA = ToonDNA.ToonDNA()
        newDNA.makeFromNetString(self.dna.makeNetString())
        newDNA.updateToonProperties(bottomTextureColor=index)
        self.makeToon(newDNA.makeNetString())

    def __changeShirt(self, *args):
        index = int(args[0])
        if index not in range(0, len(ToonDNA.Shirts)):
            return

        newDNA = ToonDNA.ToonDNA()
        newDNA.makeFromNetString(self.dna.makeNetString())
        newDNA.updateToonProperties(topTexture=index)
        self.makeToon(newDNA.makeNetString())

    def __changeShorts(self, *args):
        index = int(args[0])

        bottoms = ToonDNA.BoyShorts if self.dna.gender == 'm' else ToonDNA.GirlBottoms
        if index not in range(0, len(bottoms)):
            return

        newDNA = ToonDNA.ToonDNA()
        newDNA.makeFromNetString(self.dna.makeNetString())
        newDNA.updateToonProperties(bottomTexture=index)
        self.makeToon(newDNA.makeNetString())

    def load(self):
        genders = ['Boy', 'Girl']
        gMap = {'m': genders[0], 'f': genders[1]}
        gIndex = gMap.get(self.dna.gender)
        self.genderOptions = CustomizeOption(parent=self,
                                             command=self.__selectGender,
                                             initialitem=gIndex,
                                             items=genders,
                                             pos=(1.15, 0, 0.7))
        self.genderLabel = DirectLabel(parent=self.genderOptions,
                                       relief=None,
                                       text_font=FONT,
                                       text='Gender:',
                                       text_scale=0.85,
                                       pos=(-2.59, 0, 0))

        species = [
            'Bear', 'Cat', 'Dog', 'Duck', 'Horse', 'Monkey', 'Mouse', 'Pig',
            'Rabbit'
        ]
        sIndex = species.index(code2name.get(self.dna.head[0]).capitalize())
        self.speciesOptions = CustomizeOption(parent=self,
                                              command=self.__selectHead,
                                              initialitem=sIndex,
                                              items=species,
                                              pos=(1.15, 0, 0.55))
        self.speciesLabel = DirectLabel(parent=self.speciesOptions,
                                        relief=None,
                                        text_font=FONT,
                                        text='Species:',
                                        text_scale=0.85,
                                        pos=(-2.7, 0, 0))

        headOptions = ['Short', 'Long']
        types = {'s': headOptions[0], 'l': headOptions[1]}
        hIndex = headOptions.index(types.get(self.dna.head[1]))

        self.headOptions = CustomizeOption(parent=self,
                                           command=self.__selectHeadSize,
                                           initialitem=hIndex,
                                           items=headOptions,
                                           pos=(1.15, 0, 0.4))
        self.headLabel = DirectLabel(parent=self.headOptions,
                                     relief=None,
                                     text_font=FONT,
                                     text='Head Size:',
                                     text_scale=0.85,
                                     pos=(-3.07, 0, 0))

        mIndex = headOptions.index(types.get(self.dna.head[2]))
        self.muzzleOptions = CustomizeOption(parent=self,
                                             command=self.__selectMuzzleSize,
                                             initialitem=mIndex,
                                             items=headOptions,
                                             pos=(1.15, 0, 0.25))
        self.muzzleLabel = DirectLabel(parent=self.muzzleOptions,
                                       relief=None,
                                       text_font=FONT,
                                       text='Muzzle Size:',
                                       text_scale=0.85,
                                       pos=(-3.4, 0, 0))

        legs = ['Small', 'Medium', 'Long']
        legType = {'s': 'Small', 'm': 'Medium', 'l': 'Long'}
        lIndex = legs.index(legType.get(self.dna.legs))

        self.legOptions = CustomizeOption(parent=self,
                                          command=self.__selectLegs,
                                          initialitem=lIndex,
                                          items=legs,
                                          pos=(1.15, 0, 0.1))
        self.legLabel = DirectLabel(parent=self.legOptions,
                                    relief=None,
                                    text_font=FONT,
                                    text='Leg Length:',
                                    text_scale=0.85,
                                    pos=(-3.21, 0, 0))

        tIndex = legs.index(legType.get(self.dna.torso[0]))
        self.torsoOptions = CustomizeOption(parent=self,
                                            command=self.__selectTorso,
                                            initialitem=tIndex,
                                            items=legs,
                                            pos=(1.15, 0, -0.05))
        self.torsoLabel = DirectLabel(parent=self.torsoOptions,
                                      relief=None,
                                      text_font=FONT,
                                      text='Torso Length:',
                                      text_scale=0.85,
                                      pos=(-3.57, 0, 0))

        gloveColor = self.dna.gloveColor
        length = len(ToonDNA.NumToColor)
        if gloveColor > length:
            gloveColor = 0
        headColor = self.dna.headColor
        if headColor > length:
            headColor = 0
        armColor = self.dna.armColor
        if armColor > length:
            armColor = 0
        legColor = self.dna.legColor
        if legColor > length:
            legColor = 0

        self.gloveOptions = CustomizeOption(parent=self,
                                            command=self.__selectGloves,
                                            initialitem=gloveColor,
                                            items=ToonDNA.NumToColor,
                                            pos=(1.15, 0, -0.2),
                                            image_pos=(1.55, 0, 0.15),
                                            text_pos=(-0.13, -.1))
        self.gloveLabel = DirectLabel(parent=self.gloveOptions,
                                      relief=None,
                                      text_font=FONT,
                                      text='Glove Color:',
                                      text_scale=0.85,
                                      pos=(-3.35, 0, 0))

        self.headColorOptions = CustomizeOption(parent=self,
                                                command=self.__choseHeadColor,
                                                initialitem=headColor,
                                                items=ToonDNA.NumToColor,
                                                pos=(1.15, 0, -0.35),
                                                image_pos=(1.55, 0, 0.15),
                                                text_pos=(-0.13, -.1))
        self.headColorLabel = DirectLabel(parent=self.headColorOptions,
                                          relief=None,
                                          text_font=FONT,
                                          text='Head Color:',
                                          text_scale=0.85,
                                          pos=(-3.27, 0, 0))

        self.armColorOptions = CustomizeOption(parent=self,
                                               command=self.__choseArmColor,
                                               initialitem=armColor,
                                               items=ToonDNA.NumToColor,
                                               pos=(1.15, 0, -0.5),
                                               image_pos=(1.55, 0, 0.15),
                                               text_pos=(-0.13, -.1))
        self.armColorLabel = DirectLabel(parent=self.armColorOptions,
                                         relief=None,
                                         text_font=FONT,
                                         text='Arm Color:',
                                         text_scale=0.85,
                                         pos=(-3.074, 0, 0))

        self.legColorOptions = CustomizeOption(parent=self,
                                               command=self.__choseLegColor,
                                               initialitem=legColor,
                                               items=ToonDNA.NumToColor,
                                               pos=(1.15, 0, -0.65),
                                               image_pos=(1.55, 0, 0.15),
                                               text_pos=(-0.13, -.1))
        self.legColorLabel = DirectLabel(parent=self.legColorOptions,
                                         relief=None,
                                         text_font=FONT,
                                         text='Leg Color:',
                                         text_scale=0.85,
                                         pos=(-3, 0, 0))

        self.shirtColorOptions = CustomizeOption(
            parent=self,
            command=self.__choseShirtColor,
            initialitem=self.dna.topTexColor - 1,
            items=ToonDNA.ClothesColorNames[1:],
            pos=(1.15, 0, -0.8),
            image_pos=(1.55, 0, 0.15),
            text_pos=(-0.13, -.1))
        self.shirtColorLabel = DirectLabel(parent=self.shirtColorOptions,
                                           relief=None,
                                           text_font=FONT,
                                           text='Shirt Color:',
                                           text_scale=0.85,
                                           pos=(-3, 0, 0))

        self.bottomsColorOptions = CustomizeOption(
            parent=self,
            command=self.__choseShortsColor,
            initialitem=self.dna.botTexColor - 1,
            items=ToonDNA.ClothesColorNames[1:],
            pos=(1.15, 0, -0.95),
            image_pos=(1.55, 0, 0.15),
            text_pos=(-0.13, -.1))
        self.bottomsColorLabel = DirectLabel(parent=self.bottomsColorOptions,
                                             relief=None,
                                             text_font=FONT,
                                             text='Shorts Color:',
                                             text_scale=0.85,
                                             pos=(-3, 0, 0))

        self.shirtEntry = DirectEntry(parent=self,
                                      relief=DGG.GROOVE,
                                      scale=0.08,
                                      pos=(1.6, 0, 0.3),
                                      borderWidth=(0.05, 0.05),
                                      state=DGG.NORMAL,
                                      text_font=FONT,
                                      frameColor=((1, 1, 1, 1), (1, 1, 1, 1),
                                                  (0.5, 0.5, 0.5, 0.5)),
                                      text_align=TextNode.ALeft,
                                      text_scale=0.8,
                                      width=3.5,
                                      numLines=1,
                                      focus=1,
                                      backgroundFocus=0,
                                      cursorKeys=1,
                                      text_fg=(0, 0, 0, 1),
                                      suppressMouse=1,
                                      autoCapitalize=0,
                                      command=self.__changeShirt)
        self.shirtEntry.enterText(str(self.dna.topTex))
        self.shirtLabel = DirectLabel(parent=self.shirtEntry,
                                      relief=None,
                                      text_font=FONT,
                                      text='Shirt:',
                                      text_scale=0.85,
                                      pos=(1.25, 0, 1.25))

        self.shortsEntry = DirectEntry(parent=self,
                                       relief=DGG.GROOVE,
                                       scale=0.08,
                                       pos=(1.6, 0, 0.0),
                                       borderWidth=(0.05, 0.05),
                                       state=DGG.NORMAL,
                                       text_font=FONT,
                                       frameColor=((1, 1, 1, 1), (1, 1, 1, 1),
                                                   (0.5, 0.5, 0.5, 0.5)),
                                       text_align=TextNode.ALeft,
                                       text_scale=0.8,
                                       width=3.5,
                                       numLines=1,
                                       focus=1,
                                       backgroundFocus=0,
                                       cursorKeys=1,
                                       text_fg=(0, 0, 0, 1),
                                       suppressMouse=1,
                                       autoCapitalize=0,
                                       command=self.__changeShorts)
        self.shortsEntry.enterText(str(self.dna.botTex))
        self.shortsLabel = DirectLabel(parent=self.shortsEntry,
                                       relief=None,
                                       text_font=FONT,
                                       text='Shorts:',
                                       text_scale=0.85,
                                       pos=(1.25, 0, 1.25))

        buttonModels = loader.loadModel('phase_3.5/models/gui/inventory_gui')
        upButton = buttonModels.find('**//InventoryButtonUp')
        downButton = buttonModels.find('**/InventoryButtonDown')
        rolloverButton = buttonModels.find('**/InventoryButtonRollover')
        self.doneButton = DirectButton(parent=self,
                                       text_font=FONT,
                                       text='Done',
                                       command=self.__handleDone,
                                       scale=0.2,
                                       image=(upButton, downButton,
                                              rolloverButton),
                                       relief=None,
                                       text_fg=(1, 1, 0.65, 1),
                                       pos=(0, 0, -0.94),
                                       text_pos=(0, -.23),
                                       image_color=(1, 0, 0, 1),
                                       image_scale=(20, 1, 15),
                                       sortOrder=DGG.GEOM_SORT_INDEX)
        buttonModels.removeNode()

    def __handleDone(self):
        base.localAvatar.b_setDNAString(self.dna.makeNetString())
        self.unload()

    def unload(self):
        if self.genderLabel:
            self.genderLabel.destroy()
            self.genderLabel = None

        if self.genderOptions:
            self.genderOptions.destroy()
            self.genderOptions = None

        if self.speciesLabel:
            self.speciesLabel.destroy()
            self.speciesLabel = None

        if self.speciesOptions:
            self.speciesOptions.destroy()
            self.speciesOptions = None

        if self.headLabel:
            self.headLabel.destroy()
            self.headLabel = None

        if self.headOptions:
            self.headOptions.destroy()
            self.headOptions = None

        if self.muzzleLabel:
            self.muzzleLabel.destroy()
            self.muzzleLabel = None

        if self.muzzleOptions:
            self.muzzleOptions.destroy()
            self.muzzleOptions = None

        if self.torsoLabel:
            self.torsoLabel.destroy()
            self.torsoLabel = None

        if self.torsoOptions:
            self.torsoOptions.destroy()
            self.torsoOptions = None

        if self.legLabel:
            self.legLabel.destroy()
            self.legLabel = None

        if self.legOptions:
            self.legOptions.destroy()
            self.legOptions = None

        if self.gloveLabel:
            self.gloveLabel.destroy()
            self.gloveLabel = None

        if self.gloveOptions:
            self.gloveOptions.destroy()
            self.gloveOptions = None

        if self.headColorOptions:
            self.headColorOptions.destroy()
            self.headColorOptions = None

        if self.headColorLabel:
            self.headColorLabel.destroy()
            self.headColorLabel = None

        if self.armColorOptions:
            self.armColorOptions.destroy()
            self.armColorOptions = None

        if self.armColorLabel:
            self.armColorLabel.destroy()
            self.armColorLabel = None

        if self.legColorOptions:
            self.legColorOptions.destroy()
            self.legColorOptions = None

        if self.legColorLabel:
            self.legColorLabel.destroy()
            self.legColorLabel = None

        if self.shirtColorLabel:
            self.shirtColorLabel.destroy()
            self.shirtColorLabel = None

        if self.shirtColorOptions:
            self.shirtColorOptions.destroy()
            self.shirtColorOptions = None

        if self.bottomsColorLabel:
            self.bottomsColorLabel.destroy()
            self.bottomsColorLabel = None

        if self.bottomsColorOptions:
            self.bottomsColorOptions.destroy()
            self.bottomsColorOptions = None

        if self.shirtLabel:
            self.shirtLabel.destroy()
            self.shirtLabel = None

        if self.shirtEntry:
            self.shirtEntry.destroy()
            self.shirtEntry = None

        if self.shortsLabel:
            self.shortsLabel.destroy()
            self.shortsLabel = None

        if self.shortsEntry:
            self.shortsEntry.destroy()
            self.shortsEntry = None

        if self.doneButton:
            self.doneButton.destroy()
            self.doneButton = None

        if self.toon:
            self.toon.cleanup()
            self.toon.delete()
            self.toon.removeNode()
            self.toon = None
            self.dna = None

        self._callback(self)
        self.destroy()
class CatalogTabButton(NodePath):
    def __init__(self, catalogGui, nodeName, clickEvent):
        NodePath.__init__(self, catalogGui.attachNewNode(nodeName))
        self.active = False
        self.activePage = 0
        self.catalogGui = catalogGui
        self.catalogItemPages = []
        self.otherTabs = []
        self.clickEvent = clickEvent
        self.clickedNode = CatalogGlobals.CatalogNodePath.find(
            '**/' + nodeName + '_DN').copyTo(self)
        self.hoverNode = CatalogGlobals.CatalogNodePath.find(
            '**/' + nodeName + '_OVR').copyTo(self)
        self.tabButton = DirectButton(parent=self,
                                      relief=None,
                                      image=(self.clickedNode,
                                             self.clickedNode, self.hoverNode),
                                      command=self.tabClicked)

    def tabClicked(self):
        if self.active:
            return
        for tab in self.otherTabs:
            tab.disableTab()

        self.active = True
        self.catalogGui.setCurrentTab(self)
        self.showPages()
        self.updateArrows()
        self.clickEvent()

    def setOtherTabs(self, otherTabs):
        self.otherTabs = otherTabs

    def setCatalogItemPages(self, catalogItemPages):
        self.catalogItemPages = catalogItemPages

    def showPages(self):
        self.hidePages()
        if self.catalogItemPages:
            self.catalogItemPages[self.activePage].show()
            self.catalogGui.setActivePage(self.activePage)

    def hidePages(self):
        for page in self.catalogItemPages:
            page.hide()

    def disableTab(self):
        if not self.active:
            return
        self.active = False
        self.hidePages()
        self.activePage = 0

    def updateArrows(self):
        self.catalogGui.enableBothArrows()
        if self.activePage == 0:
            self.catalogGui.disableLeftArrow()
        if self.activePage == len(self.catalogItemPages) - 1:
            self.catalogGui.disableRightArrow()

    def moveLeft(self):
        self.activePage -= 1
        self.showPages()
        self.updateArrows()

    def moveRight(self):
        self.activePage += 1
        self.showPages()
        self.updateArrows()

    def lockItems(self):
        for page in self.catalogItemPages:
            page.lockItems()

    def updateItems(self, gifting):
        for page in self.catalogItemPages:
            page.updateItems(gifting)

    def cleanup(self):
        for page in self.catalogItemPages:
            page.cleanup()

        self.tabButton.destroy()
        NodePath.removeNode(self)
Beispiel #17
0
 def destroy(self, *args, **kwargs):
     self.__checkstatedumpnp.removeNode()
     return DirectButton.destroy(self, *args, **kwargs)
Beispiel #18
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())
Beispiel #19
0
 def destroy(self, *args, **kwargs):
     self.__checkstatedumpnp.removeNode()
     return DirectButton.destroy(self, *args, **kwargs)
Beispiel #20
0
 def destroy(self):
     self.ignoreAll()
     DirectButton.destroy(self)
Beispiel #21
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()
Beispiel #22
0
class Ground(ShowBase):
    def __init__(self):
        # Initialize the ShowBase class from which we inherit,which will
        # create a window and set up everything we need for rendering into it.
        ShowBase.__init__(self)

        self.setBackgroundColor(240, 35, 35, 1)

        # Make a variable to store the unique collision string count
        self.collCount = 0

        #set scale of ground
        self.scaleBy = 120

        #disable mouse control of camera and manually place it
        base.disableMouse()
        camera.setPos(self.scaleBy // 2, self.scaleBy // 2, 2)

        #quit program when Escapse key pressed
        self.accept("escape", sys.exit)
        self.accept("a", self.runMiniGame)
        #set default settings of game
        self.setting = "forest"
        self.music = base.loader.loadSfx("music1.ogg")
        self.music.setVolume(.5)

        self.miniGameRun = False

        #initialization starting screen
        self.loadStartScreen()

    #display start screen w/ text and buttons
    def loadStartScreen(self):
        self.startBG = OnscreenImage(image='world.jpg', pos=(0, 0, 0), scale=3)
        self.title = OnscreenText(text="Onwards,Term Project",
                                  align=TextNode.ACenter,
                                  fg=(1, 1, 1, 1),
                                  pos=(0, 0.5),
                                  scale=.08,
                                  shadow=(0, 0, 0, 0.5))
        self.chooseGround = OnscreenText(text="Choose Land:",
                                         align=TextNode.ACenter,
                                         fg=(1, 1, 1, 1),
                                         pos=(-0.8, 0.25),
                                         scale=.08,
                                         shadow=(0, 0, 0, 0.5))
        self.buttonForest = DirectButton(pos=(-0.2, 0, 0.24),
                                         text="Forest",
                                         scale=.1,
                                         pad=(.2, .2),
                                         rolloverSound=None,
                                         clickSound=None,
                                         command=self.selected,
                                         extraArgs=["forest"],
                                         relief=SUNKEN)
        self.buttonDesert = DirectButton(pos=(0.4, 0, 0.24),
                                         text="Desert",
                                         scale=.1,
                                         pad=(.2, .2),
                                         rolloverSound=None,
                                         clickSound=None,
                                         command=self.selected,
                                         extraArgs=["desert"])
        self.chooseMusic = OnscreenText(text="Choose Music:",
                                        align=TextNode.ACenter,
                                        fg=(1, 1, 1, 1),
                                        pos=(-0.8, 0),
                                        scale=.08,
                                        shadow=(0, 0, 0, 0.5))
        self.buttonMusic1 = DirectButton(pos=(-0.2, 0, -0.01),
                                         text="Piano 1",
                                         scale=.1,
                                         pad=(.2, .2),
                                         rolloverSound=None,
                                         clickSound=None,
                                         command=self.selected,
                                         extraArgs=["piano1"],
                                         relief=SUNKEN)
        self.buttonMusic2 = DirectButton(pos=(0.35, 0, -0.01),
                                         text="Piano 2",
                                         scale=.1,
                                         pad=(.2, .2),
                                         rolloverSound=None,
                                         clickSound=None,
                                         command=self.selected,
                                         extraArgs=["piano2"])
        self.buttonMusic3 = DirectButton(pos=(0.8, 0, -0.01),
                                         text="None",
                                         scale=.1,
                                         pad=(.2, .2),
                                         rolloverSound=None,
                                         clickSound=None,
                                         command=self.selected,
                                         extraArgs=["stop"])
        self.volume = OnscreenText(text="Volume:",
                                   align=TextNode.ACenter,
                                   fg=(1, 1, 1, 1),
                                   pos=(-0.8, -0.3),
                                   scale=.08,
                                   shadow=(0, 0, 0, 0.5))
        self.volumeSlider = DirectSlider(pos=(0.3, 0, -0.3),
                                         scale=0.7,
                                         value=.5,
                                         command=self.setMusicVolume)
        self.enterInstruction = OnscreenText(text="Press 'Enter' to Begin",
                                             align=TextNode.ACenter,
                                             fg=(1, 1, 1, 1),
                                             pos=(0, -0.5),
                                             scale=.08,
                                             shadow=(0, 0, 0, 0.5))
        self.accept("enter", self.loadModels)

    #change button reliefs if clicked or not & game settings based on button
    def selected(self, pressed):
        if pressed == "desert":
            self.setting = "desert"
            self.buttonForest['relief'] = RAISED
            self.buttonDesert['relief'] = SUNKEN
        elif pressed == "forest":
            self.setting = "forest"
            self.buttonForest['relief'] = SUNKEN
            self.buttonDesert['relief'] = RAISED
        if pressed == "piano1":
            self.music.stop()
            self.music = base.loader.loadSfx("music1.ogg")
            self.music.setLoop(True)
            self.music.play()
            self.buttonMusic1['relief'] = SUNKEN
            self.buttonMusic2['relief'] = RAISED
            self.buttonMusic3['relief'] = RAISED
        elif pressed == "piano2":
            self.music.stop()
            self.music = base.loader.loadSfx("music2.ogg")
            self.music.setLoop(True)
            self.music.play()
            self.buttonMusic1['relief'] = RAISED
            self.buttonMusic2['relief'] = SUNKEN
            self.buttonMusic3['relief'] = RAISED
        elif pressed == "stop":
            self.music.stop()
            self.buttonMusic1['relief'] = RAISED
            self.buttonMusic2['relief'] = RAISED
            self.buttonMusic3['relief'] = SUNKEN

    #change volume based on slider position
    def setMusicVolume(self):
        vol = self.volumeSlider.guiItem.getValue()
        self.music.setVolume(vol)

    #load models when 'enter' pressed
    def loadModels(self):
        self.startBG.destroy()
        self.title.destroy()
        self.chooseGround.destroy()
        self.buttonForest.destroy()
        self.buttonDesert.destroy()
        self.chooseMusic.destroy()
        self.buttonMusic1.destroy()
        self.buttonMusic2.destroy()
        self.buttonMusic3.destroy()
        self.enterInstruction.destroy()
        self.volumeSlider.destroy()
        self.volume.destroy()

        self.cTrav = CollisionTraverser()

        self.lastHitEntry = "is an entry"
        self.plants = []
        self.plantColls = []
        self.animals = []
        self.animalColls = []

        self.miniGameBoxes = []

        self.axes = []
        self.planters = []
        self.haveAxe = False
        self.havePlanter = False
        self.selectedPlanterOpt = 0

        self.planterOptionsForest = [("plants/foliage01.egg.pz", 11, 12),
                                     ("plants/foliage02.egg.pz", -12, 14),
                                     ("plants/foliage03.egg.pz", 14, 23),
                                     ("plants/foliage04.egg.pz", 0, 0),
                                     ("plants/foliage05.egg.pz", 6, 22),
                                     ("plants/foliage09.egg.pz", -3, 10),
                                     ("chicken.egg", 0, 0)]

        self.planterOptionsDesert = [("plants/shrubbery.egg.pz", 1, 14),
                                     ("plants/cactus1.egg", 0, 12),
                                     ("plants/cactus2.egg", 2.5, 11),
                                     ("chicken.egg", 0, 0)]

        #display instructions
        self.loadText()

        #respond when arrow keys are pressed
        self.accept("arrow_up", self.eventArrowPressed, ["up"])
        self.accept("arrow_up-repeat", self.eventArrowPressed, ["up"])
        self.accept("arrow_right", self.eventArrowPressed, ["right"])
        self.accept("arrow_right-repeat", self.eventArrowPressed, ["right"])
        self.accept("arrow_left", self.eventArrowPressed, ["left"])
        self.accept("arrow_left-repeat", self.eventArrowPressed, ["left"])
        self.accept("arrow_down", self.eventArrowPressed, ["down"])
        self.accept("arrow_down-repeat", self.eventArrowPressed, ["down"])
        self.accept("f", self.eventAerielView)
        self.accept("0", self.restartGame)
        self.accept("enter", self.doNothing)

        groundTexture = loader.loadTexture(self.setting + ".jpg")

        #load starting square of land
        land = loader.loadModel("box")
        land.setPos(0, 0, 0)
        land.setSy(self.scaleBy)
        land.setSx(self.scaleBy)
        land.setSz(0.5)
        land.setTexture(groundTexture, 1)

        self.spanGround = [(0, 0)]
        self.ground = land
        self.ground.reparentTo(render)

        #load main char
        self.mainChar = loader.loadModel("box")
        self.mainChar.reparentTo(camera)
        self.mainChar.setPos(0, 10, -2)
        self.mainChar.setColorScale(0.6, 0.6, 1.0, 1.0)
        self.moveMainCharX = 0.5
        self.moveMainCharY = 0.75

        #load main char's collision ray onto screen & make char a collider
        self.mainCharGroundRay = CollisionRay()
        self.mainCharGroundRay.setOrigin(0.5, 0, 30)
        self.mainCharGroundRay.setDirection(0, 0, -1)
        self.mainCharGroundCol = CollisionNode('mainCharRay')
        self.mainCharGroundCol.addSolid(self.mainCharGroundRay)
        self.mainCharGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.mainCharGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.mainCharGroundColNp = self.mainChar.attachNewNode(\
                                                        self.mainCharGroundCol)
        self.mainCharGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.mainCharGroundColNp,\
                                                    self.mainCharGroundHandler)
        #load camera's collision ray & make it a collider
        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0, 0, 30)
        self.camGroundRay.setDirection(0, 0, -1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.camGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        #shows collision nodes (for debugging)
        # self.mainCharGroundColNp.show()
        # self.camGroundColNp.show()

        self.curPos = self.mainChar.getPos()
        self.cameraCurPos = camera.getPos()

        # shows collisions occuring (for debugging)
        # self.cTrav.showCollisions(render)

        #continuously check for collisions
        taskMgr.add(self.checkCollisions, "checkCollisionsTask")

        #initialize fog so that scene in distance is blocked from view
        color = (240, 35, 35)
        expfog = Fog("Scene-wide exponential Fog object")
        expfog.setColor(*color)
        expfog.setExpDensity(0.006)
        render.setFog(expfog)
        base.setBackgroundColor(color)

    #display instructions on screen top & title on botton
    def loadText(self):
        self.bottomTitle = \
            OnscreenText(text="Onwards,Term Project",
                         parent=base.a2dBottomRight,align=TextNode.ARight,
                         fg=(1,1,1,1),pos=(-0.1,0.1),scale=.08,
                         shadow=(0,0,0,0.5))
        self.startInstructions = \
           OnscreenText(text="Press Arrow Keys to explore. Press and hold 'f' "+
                              "to activate Aeriel View. Press Esc to exit."+
                              "\nPress '0' to go to Start Screen",
                         parent=base.a2dTopLeft,align=TextNode.ALeft,
                         pos=(0.05,-0.08),fg=(1,1,1,1),scale=.06,
                         shadow=(0,0,0,0.5))

    #set what happens when arrow keys pressed
    def eventArrowPressed(self, dir):
        self.curPos = self.mainChar.getPos()
        self.cameraCurPos = camera.getPos()
        x, y, z = base.camera.getPos()
        if dir == "up":
            camera.setPos(x, y + self.moveMainCharY, z)
        elif dir == "down":
            camera.setPos(x, y - self.moveMainCharY, z)
        elif dir == "right":
            camera.setPos(x + self.moveMainCharX, y, z)
        elif dir == "left":
            camera.setPos(x - self.moveMainCharX, y, z)
        self.checkExtend(dir)

    #set what happens when x pressed & axe activated
    def eventAxe(self):
        deleted = False
        if len(self.plantColls) > 0:
            for i in range(len(self.plantColls)):
                if (self.lastHitEntry in self.plantColls[i][0].getName()):
                    self.plantColls[i][0].remove_node()
                    self.plants[i].remove_node()
                    self.plantColls = self.plantColls[:i] + self.plantColls[i +
                                                                            1:]
                    self.plants = self.plants[:i] + self.plants[i + 1:]
                    deleted = True
                    break
        if len(self.animalColls) > 0 and deleted == False:
            for i in range(len(self.animalColls)):
                if (self.lastHitEntry in self.animalColls[i][0].getName()):
                    self.animalColls[i][0].remove_node()
                    self.animals[i][0].remove_node()
                    self.animalColls = self.animalColls[:i]+\
                                       self.animalColls[i+1:]
                    self.animals = self.animals[:i] + self.animals[i + 1:]
                    deleted = True
                    break
        if len(self.miniGameBoxes) > 0 and deleted == False:
            for i in range(len(self.miniGameBoxes)):
                if (self.lastHitEntry
                        in self.miniGameBoxes[i][1][0].getName()):
                    self.miniGameBoxes[i][1][0].remove_node()
                    self.miniGameBoxes[i][0].remove_node()
                    self.miniGameBoxes = self.miniGameBoxes[:i]+\
                                         self.miniGameBoxes[i+1:]
                    deleted = True
                    self.acceptMiniGame()
                    break

    #set what happens when w pressed & planter activated
    def eventPlanter(self):
        #create new object and position it in front of main character
        x, y, z = camera.getPos()
        if self.setting == "forest":
            plantType,shiftX,shiftY = \
                            self.planterOptionsForest[self.selectedPlanterOpt]
        else:
            plantType,shiftX,shiftY = \
                            self.planterOptionsDesert[self.selectedPlanterOpt]
        if plantType == "chicken.egg":
            self.newAnimal()
        else:
            plant = loader.loadModel(plantType)
            plant.setScale(0.2)
            plant.setPos(x + shiftX, y + shiftY, 0)
            plant.reparentTo(render)
            if plantType == "plants/cactus1.egg":
                plant.setTexture(loader.loadTexture("cactusskin.png"), 1)
                plant.setScale(1)
                plantColl = self.initCollisionSphere(plant, 0.1, False)
            elif plantType == "plants/cactus2.egg":
                plant.setScale(1)
                plant.setZ(0.5)
                plantColl = self.initCollisionSphere(plant, 0.8, False)
            elif plantType == "plants/shrubbery.egg.pz":
                plant.setScale(0.15)
                plantColl = self.initCollisionSphere(plant, 0.2, False)
            else:
                plantColl = self.initCollisionSphere(plant, 0.08, False)
            self.plants += [plant]
            self.plantColls += [plantColl]

    #shift camera upwards to show aeriel view
    def eventAerielView(self):
        self.x, self.y, self.z = camera.getPos()
        shiftPos = camera.posInterval(0.1,\
                                     Point3(self.x,self.y + 30,self.z + 150))
        shiftAngle = camera.hprInterval(0.2, Vec3(0, -90, 0))
        aerielView = Sequence(shiftPos, shiftAngle)
        aerielView.start()
        self.moveMainCharX = 2
        self.moveMainCharY = 3
        self.accept("f-up", self.eventNormalView)

    #shift camera back to normal view
    def eventNormalView(self):
        shiftPos = camera.posInterval(0.1, Point3(self.x, self.y, self.z))
        shiftAngle = camera.hprInterval(0.2, Vec3(0, 0, 0))
        aerielView = Sequence(shiftPos, shiftAngle)
        aerielView.start()
        self.moveMainCharX = 0.5
        self.moveMainCharY = 0.75

    #check whether or not to extend ground
    def checkExtend(self, dir):
        x, y, z = base.camera.getPos()
        checkV = (0, 0)
        whole = self.scaleBy
        #Up
        checkX = x // self.scaleBy
        checkY = (y + whole) // self.scaleBy
        cUp = (checkX, checkY)
        if cUp not in self.spanGround:
            self.spanGround += [cUp]
            self.extendScene()
        #Down
        checkX = x // self.scaleBy
        checkY = (y - whole) // self.scaleBy
        cDown = (checkX, checkY)
        if cDown not in self.spanGround:
            self.spanGround += [cDown]
            self.extendScene()
        #Right
        checkX = (x + whole) // self.scaleBy
        checkY = y // self.scaleBy
        cRight = (checkX, checkY)
        if cRight not in self.spanGround:
            self.spanGround += [cRight]
            self.extendScene()
        #Left
        checkX = (x - whole) // self.scaleBy
        checkY = y // self.scaleBy
        cLeft = (checkX, checkY)
        if cLeft not in self.spanGround:
            self.spanGround += [cLeft]
            self.extendScene()
        #Upper Right Diagonal
        checkX = (x + whole) // self.scaleBy
        checkY = (y + whole) // self.scaleBy
        cUpRight = (checkX, checkY)
        if cUpRight not in self.spanGround:
            self.spanGround += [cUpRight]
            self.extendScene()
        #Upper Left Diagonal
        checkX = (x - whole) // self.scaleBy
        checkY = (y + whole) // self.scaleBy
        cUpLeft = (checkX, checkY)
        if cUpLeft not in self.spanGround:
            self.spanGround += [cUpLeft]
            self.extendScene()
        #Lower Right Diagonal
        checkX = (x + whole) // self.scaleBy
        checkY = (y - whole) // self.scaleBy
        cUpRight = (checkX, checkY)
        if cUpRight not in self.spanGround:
            self.spanGround += [cUpRight]
            self.extendScene()
        #Lower Left Diagonal
        checkX = (x - whole) // self.scaleBy
        checkY = (y - whole) // self.scaleBy
        cUpLeft = (checkX, checkY)
        if cUpLeft not in self.spanGround:
            self.spanGround += [cUpLeft]
            self.extendScene()

    #extend ground
    def extendScene(self):
        #add square of ground
        groundTexture = loader.loadTexture(self.setting + ".jpg")
        new = loader.loadModel("box")
        new.setSy(self.scaleBy)
        new.setSx(self.scaleBy)
        new.setSz(0.5)
        new.setTexture(groundTexture, 1)
        newPos = self.spanGround[-1]
        newPosX = newPos[0] * self.scaleBy
        newPosY = newPos[1] * self.scaleBy
        new.setPos(newPosX, newPosY, 0)
        self.newground = new
        self.newground.reparentTo(render)

        #load axe if haven't collided with one yet
        if not self.haveAxe:
            axe = loader.loadModel("axe")
            axe.setColor(0, 0, 0, 1.0)
            axe.setScale(0.5, 1, 0.5)
            axe.setPos(randint(newPosX, newPosX + self.scaleBy),
                       randint(newPosY, newPosY + self.scaleBy), 0.3)
            axe.reparentTo(render)
            axeObject = loader.loadModel("axe01")
            axeObject.setScale(3)
            axeObject.setPos(0.5, 0, 2)
            axeObject.setHpr(0, 65, 35)
            axeObject.reparentTo(axe)
            axeColl = self.initCollisionSphere(axe, 1, False)
            self.axes += [axe]

        #load planter if haven't collided with one yet
        if not self.havePlanter:
            planter = loader.loadModel("planter")
            planter.setColor(0, 0, 1, 1)
            planter.setScale(1, 1, 1)
            planter.setPos(randint(newPosX, newPosX + self.scaleBy),
                           randint(newPosY, newPosY + self.scaleBy), 0.3)
            planter.reparentTo(render)
            planterBag = loader.loadModel("planter01")
            planterBag.setScale(1.5)
            planterBag.setHpr(0, 30, 0)
            planterBag.setPos(0.75, 0, 1.25)
            planterBag.reparentTo(planter)
            planterColl = self.initCollisionSphere(planter, 1, False)
            self.planters += [planter]

        #load random number of mini game boxes
        for i in range(randint(1, 4)):
            miniGameBox = loader.loadModel("box")
            miniGameBox.setPos(randint(newPosX, newPosX + self.scaleBy),
                               randint(newPosY, newPosY + self.scaleBy), 0.5)
            miniGameBox.reparentTo(render)
            miniGameBoxColl = self.initCollisionSphere(miniGameBox, 1.3, False)
            self.miniGameBoxes += [[miniGameBox, miniGameBoxColl]]

        #load certain plants in forest setting
        if self.setting == "forest":
            for i in range(randint(3, 15)):
                #place plant 1
                plant1 = loader.loadModel("plants/foliage01.egg.pz")
                plant1.setScale(0.2)
                plant1.setPos(randint(newPosX, newPosX + self.scaleBy),
                              randint(newPosY, newPosY + self.scaleBy), 0)
                plant1.reparentTo(render)
                plantColl = self.initCollisionSphere(plant1, 0.08, False)
                self.plants += [plant1]
                self.plantColls += [plantColl]
            for i in range(randint(3, 15)):
                #place plant2
                plant2 = loader.loadModel("plants/foliage02.egg.pz")
                plant2.setScale(0.2)
                plant2.setPos(randint(newPosX, newPosX + self.scaleBy),
                              randint(newPosY, newPosY + self.scaleBy), 0)
                plant2.reparentTo(render)
                plantColl = self.initCollisionSphere(plant2, 0.06, False)
                self.plants += [plant2]
                self.plantColls += [plantColl]
            for i in range(randint(3, 15)):
                #place plant3
                plant3 = loader.loadModel("plants/foliage03.egg.pz")
                plant3.setScale(0.8)
                plant3.setPos(randint(newPosX, newPosX + self.scaleBy),
                              randint(newPosY, newPosY + self.scaleBy), 0)
                plant3.reparentTo(render)
                plantColl = self.initCollisionSphere(plant3, 0.06, False)
                self.plants += [plant3]
                self.plantColls += [plantColl]
            for i in range(randint(3, 15)):
                #place plant4
                plant4 = loader.loadModel("plants/foliage04.egg.pz")
                plant4.setScale(0.6)
                plant4.setPos(randint(newPosX, newPosX + self.scaleBy),
                              randint(newPosY, newPosY + self.scaleBy), 0)
                plant4.reparentTo(render)
                plantColl = self.initCollisionSphere(plant4, 0.07, False)
                self.plants += [plant4]
                self.plantColls += [plantColl]
            for i in range(randint(3, 15)):
                #place plant5
                plant5 = loader.loadModel("plants/foliage05.egg.pz")
                plant5.setScale(0.6)
                plant5.setPos(randint(newPosX, newPosX + self.scaleBy),
                              randint(newPosY, newPosY + self.scaleBy), 0)
                plant5.reparentTo(render)
                plantColl = self.initCollisionSphere(plant5, 0.05, False)
                self.plants += [plant5]
                self.plantColls += [plantColl]
            for i in range(randint(3, 15)):
                #place plant6
                plant6 = loader.loadModel("plants/foliage09.egg.pz")
                plant6.setScale(0.6)
                plant6.setPos(randint(newPosX, newPosX + self.scaleBy),
                              randint(newPosY, newPosY + self.scaleBy), 0)
                plant6.reparentTo(render)
                plantColl = self.initCollisionSphere(plant6, 0.08, False)
                self.plants += [plant6]
                self.plantColls += [plantColl]
            #load walking animals
            if newPos[0] % 4 == 0 and newPos[1] % 3 == 0:
                animal = loader.loadModel("box")
                animal.setScale(1)
                animal.setPos(randint(newPosX, newPosX + self.scaleBy),
                              randint(newPosY, newPosY + self.scaleBy), -0.75)
                animal.reparentTo(render)
                animalColl = self.initCollisionSphere(animal, 0.75, False)
                chicken = loader.loadModel("chicken")
                chicken.setScale(0.15)
                chicken.setPos(0.5, 0.5, 1.25)
                chicken.setHpr(0, 0, 0)
                chicken.reparentTo(animal)
                self.animalColls += [animalColl]
                animalGroundHandler = CollisionHandlerQueue()
                self.animals += [[animal, randint(0, 4), animalGroundHandler]]
                self.cTrav.addCollider(animalColl[0], animalGroundHandler)
        #load certain plants in desert setting
        elif self.setting == "desert":
            for i in range(randint(0, 6)):
                #place shrubbery
                plant0 = loader.loadModel("plants/shrubbery.egg.pz")
                plant0.setScale(0.1)
                plant0.setPos(randint(newPosX, newPosX + self.scaleBy),
                              randint(newPosY, newPosY + self.scaleBy), 0)
                plant0.reparentTo(render)
                plantColl = self.initCollisionSphere(plant0, 0.3, False)
                self.plants += [plant0]
                self.plantColls += [plantColl]
            for i in range(randint(0, 6)):
                #place cactus1
                plant1 = loader.loadModel("plants/cactus1.egg")
                plant1.setScale(1)
                plant1.setPos(randint(newPosX, newPosX + self.scaleBy),
                              randint(newPosY, newPosY + self.scaleBy), 0)
                plant1.setTexture(loader.loadTexture("cactusskin.png"), 1)
                plant1.reparentTo(render)
                plantColl = self.initCollisionSphere(plant1, 0.1, False)
                self.plants += [plant1]
                self.plantColls += [plantColl]
            for i in range(randint(0, 6)):
                #place cactus2
                plant2 = loader.loadModel("plants/cactus2.egg")
                plant2.setScale(1)
                plant2.setPos(randint(newPosX, newPosX + self.scaleBy),
                              randint(newPosY, newPosY + self.scaleBy), 0.5)
                plant2.reparentTo(render)
                plantColl = self.initCollisionSphere(plant2, 0.8, False)
                self.plants += [plant2]
                self.plantColls += [plantColl]
            #load walking animals
            if newPos[0] % 4 == 0 and newPos[1] % 3 == 0:
                animal = loader.loadModel("box")
                animal.setScale(1)
                animal.setPos(randint(newPosX, newPosX + self.scaleBy),
                              randint(newPosY, newPosY + self.scaleBy), -0.75)
                animal.reparentTo(render)
                animalColl = self.initCollisionSphere(animal, 0.75, False)
                chicken = loader.loadModel("chicken")
                chicken.setScale(0.15)
                chicken.setPos(0.5, 0.5, 1.25)
                chicken.setHpr(0, 0, 0)
                chicken.reparentTo(animal)
                self.animalColls += [animalColl]
                animalGroundHandler = CollisionHandlerQueue()
                self.animals += [[animal, randint(0, 4), animalGroundHandler]]
                self.cTrav.addCollider(animalColl[0], animalGroundHandler)

    #load animal in front of main char
    def newAnimal(self):
        #load and initialize box for chicken to be rendered to
        x, y, z = self.cameraCurPos
        animal = loader.loadModel("box")
        animal.setScale(1)
        animal.setPos(x + 1, y + 15, -0.75)
        animal.reparentTo(render)
        animalColl = self.initCollisionSphere(animal, 0.75, False)
        #load chicken
        chicken = loader.loadModel("chicken")
        chicken.setScale(0.15)
        chicken.setPos(0.5, 0.5, 1.25)
        chicken.setHpr(0, 0, 0)
        chicken.reparentTo(animal)
        #store animal into
        self.animalColls += [animalColl]
        animalGroundHandler = CollisionHandlerQueue()
        self.animals += [[animal, 0, animalGroundHandler]]
        self.cTrav.addCollider(animalColl[0], animalGroundHandler)
        taskMgr.add(self.moveAnimal, "moveAnimalsTask")
        taskMgr.add(self.checkAnimalCollisions, "checkAnimalCollisionsTask")

    #move every animal in self.animals forward
    def moveAnimal(self, task):
        for animal in self.animals:
            x, y, z = animal[0].getPos()
            if animal[1] == 0:
                animal[0].setPos(x, y + 0.025, z)
                animal[0].setHpr(180, 0, 0)
            elif animal[1] == 2:
                animal[0].setPos(x + 0.025, y, z)
                animal[0].setHpr(90, 0, 0)
            elif animal[1] == 1:
                animal[0].setPos(x, y - 0.025, z)
                animal[0].setHpr(0, 0, 0)
            elif animal[1] == 3:
                animal[0].setPos(x - 0.025, y, z)
                animal[0].setHpr(270, 0, 0)
        return Task.cont

    #check if animal collided with surroundings
    def checkAnimalCollisions(self, task):
        #check collisions of each automatically moving animals
        for animal in self.animals:
            entries = list(animal[2].getEntries())
            entries.sort(key=lambda x: x.getSurfacePoint(render).getZ())
            if len(entries) > 0:
                x, y, z = animal[0].getPos()
                if animal[1] == 0:
                    animal[0].setPos(x, y - 0.03, z)
                elif animal[1] == 2:
                    animal[0].setPos(x - 0.03, y, z)
                elif animal[1] == 1:
                    animal[0].setPos(x, y + 0.03, z)
                elif animal[1] == 3:
                    animal[0].setPos(x + 0.03, y, z)
                animal[1] = (animal[1] + 1) % 4
        return Task.cont

    #check if main character collided with surroundings
    def checkCollisions(self, task):
        #check collisions for mainChar
        entries = list(self.mainCharGroundHandler.getEntries())
        entries.sort(key=lambda x: x.getSurfacePoint(render).getZ())
        #if bump into tree,go back to last position so char doesn't go in tree
        if (len(entries) > 0
                and ("axe" not in entries[0].getIntoNode().getName())
                and ("planter" not in entries[0].getIntoNode().getName())):
            camera.setPos(self.cameraCurPos)
            #show what was last hit item
            if self.haveAxe:
                #unhighlight last entry
                unhighlighted = True
                if unhighlighted:
                    for i in range(len(self.plantColls)):
                        if (self.lastHitEntry in \
                            self.plantColls[i][0].getName()):
                            self.plants[i].setColorScale(1, 1, 1, 1.0)
                            unhighlighted = False
                            break
                if unhighlighted:
                    for i in range(len(self.animalColls)):
                        if (self.lastHitEntry in \
                            self.animalColls[i][0].getName()):
                            self.animals[i][0].setColorScale(1, 1, 1, 1.0)
                            unhighlighted = False
                            break
                if unhighlighted:
                    for i in range(len(self.miniGameBoxes)):
                        if(self.lastHitEntry in \
                            self.miniGameBoxes[i][1][0].getName()):
                            self.miniGameBoxes[i][0].setColorScale(
                                1, 1, 1, 1.0)
                            unhighlighted = False
                            break
                #find last entry & highlight it
                if len(entries) > 0:
                    self.lastHitEntry = entries[0].getIntoNode().getName()
                    highlighted = True
                    if highlighted:
                        for i in range(len(self.plantColls)):
                            if (self.lastHitEntry in \
                                self.plantColls[i][0].getName()):
                                self.plants[i].setColorScale(
                                    0.6, 0.6, 1.0, 1.0)
                                highlighted = False
                                break
                    if highlighted:
                        for i in range(len(self.animalColls)):
                            if (self.lastHitEntry in \
                                self.animalColls[i][0].getName()):
                                self.animals[i][0].setColorScale(0.6,\
                                                                 0.6,1.0,1.0)
                                highlighted = False
                                break
                    if highlighted:
                        for i in range(len(self.miniGameBoxes)):
                            if(self.lastHitEntry in \
                                self.miniGameBoxes[i][1][0].getName()):
                                self.miniGameBoxes[i][0].setColorScale(0.6,\
                                                                    0.6,1.0,1.0)
                                highlighted = False
                                break
        #if bump into axe,activate axe & delete it
        elif len(entries) > 0 and ("axe"
                                   in entries[0].getIntoNode().getName()):
            self.haveAxe = True
            for obj in self.axes:
                obj.remove_node()

        #if bump into planter,activate planter & delete it
        elif (len(entries) > 0
              and ("planter" in entries[0].getIntoNode().getName())):
            self.havePlanter = True
            for obj in self.planters:
                obj.remove_node()
        #change onscreen text & add keyboard events if hit axe and/or planter
        if self.havePlanter:
            self.accept('w', self.eventPlanter)
            self.planterInstructions = OnscreenText(
                text="Press 'w' to plant." +
                "Press 'q' or 'e' to change plant",
                parent=base.a2dTopLeft,
                align=TextNode.ALeft,
                pos=(0.05, -0.28),
                fg=(1, 1, 1, 1),
                scale=.06,
                shadow=(0, 0, 0, 0.5))
            self.accept('e', self.changeSelectedPlanterOpt, ["e"])
            self.accept('q', self.changeSelectedPlanterOpt, ["q"])
        if self.haveAxe:
            self.accept('x', self.eventAxe)
            self.axeInstructions = OnscreenText(text="Press 'x' to cut plant.",
                                                parent=base.a2dTopLeft,
                                                align=TextNode.ALeft,
                                                pos=(0.05, -0.20),
                                                fg=(1, 1, 1, 1),
                                                scale=.06,
                                                shadow=(0, 0, 0, 0.5))
        return Task.cont

    #change selecter planter opt so that it stays w/in list
    def changeSelectedPlanterOpt(self, direction):
        #in forest,modify selectedPlantOpt if it goes out of range
        if self.setting == "forest":
            if direction == "e":
                self.selectedPlanterOpt += 1
                if self.selectedPlanterOpt >= len(self.planterOptionsForest):
                    self.selectedPlanterOpt -= len(self.planterOptionsForest)
            else:
                self.selectedPlanterOpt -= 1
                if self.selectedPlanterOpt <= -1 * len(
                        self.planterOptionsForest):
                    self.selectedPlanterOpt += len(self.planterOptionsForest)
        #in desert,modify selectedPlantOpt if it goes out of range
        else:
            if direction == "e":
                self.selectedPlanterOpt += 1
                if self.selectedPlanterOpt >= len(self.planterOptionsDesert):
                    self.selectedPlanterOpt -= len(self.planterOptionsDesert)
            else:
                self.selectedPlanterOpt -= 1
                if self.selectedPlanterOpt <= -1 * len(
                        self.planterOptionsDesert):
                    self.selectedPlanterOpt += len(self.planterOptionsDesert)

    #source: https://www.panda3d.org/manual/index.php/Event_Example
    #initialize collision sphere around object
    def initCollisionSphere(self, obj, circR, show=False):
        # Get the size of the object for the collision sphere.
        bounds = obj.getChild(0).getBounds()
        radius = bounds.getRadius() * circR

        center = bounds.getCenter()
        #make center of collision circle be on ground around tree trunks
        center[2] = 0
        if obj.getName() == "foliage01.egg.pz":
            pass
        elif obj.getName() == "foliage02.egg.pz":
            center[0] -= 4
        elif obj.getName() == "foliage03.egg.pz":
            center[0] -= 3.5
        elif obj.getName() == "foliage04.egg.pz":
            center[0] += 11
            center[1] -= 1
        elif obj.getName() == "foliage05.egg.pz":
            center[0] += 1.5
            center[1] -= 4
        elif obj.getName() == "foliage09.egg.pz":
            center[0] -= 2.5
            center[1] -= 2

        # Create a collision sphere and name it something understandable.
        collSphereStr = 'CollisionHull' + str(
            self.collCount) + "_" + obj.getName()
        self.collCount += 1
        cNode = CollisionNode(collSphereStr)
        cNode.addSolid(CollisionSphere(center, radius))

        cNodepath = obj.attachNewNode(cNode)
        if show:
            cNodepath.show()

        # Return a tuple with the collision node and its corrsponding string so
        # that the bitmask can be set.
        return (cNodepath, collSphereStr)

    #remove functionality from keyboard key
    def doNothing(self):
        pass

    #ask player if they want to continue to minigame screen
    def acceptMiniGame(self):
        self.question = OnscreenText(text="Do you want to play a minigame?",
                                     align=TextNode.ACenter,
                                     fg=(1, 1, 1, 1),
                                     pos=(0, 0.5),
                                     scale=.08,
                                     shadow=(0, 0, 0, 0.5))

        self.buttonNo = DirectButton(pos=(-0.2, 0, 0.24),
                                     text="No",
                                     scale=.1,
                                     pad=(.2, .2),
                                     rolloverSound=None,
                                     clickSound=None,
                                     command=self.miniSelected,
                                     extraArgs=["no"],
                                     relief=SUNKEN)

        self.buttonYes = DirectButton(pos=(0.2, 0, 0.24),
                                      text="Yes",
                                      scale=.1,
                                      pad=(.2, .2),
                                      rolloverSound=None,
                                      clickSound=None,
                                      command=self.miniSelected,
                                      extraArgs=["yes"],
                                      relief=RAISED)

        self.enterInstruction = OnscreenText(text="Press 'enter' to continue",
                                             align=TextNode.ACenter,
                                             fg=(1, 1, 1, 1),
                                             pos=(0, -0.5),
                                             scale=.08,
                                             shadow=(0, 0, 0, 0.5))

        self.accept("enter", self.executeMiniButtons)

    #change values of button when pressed
    def miniSelected(self, pressed):
        if pressed == "yes":
            self.miniGameRun = True
            self.buttonNo['relief'] = RAISED
            self.buttonYes['relief'] = SUNKEN
        elif pressed == "no":
            self.miniGameRun = False
            self.buttonNo['relief'] = SUNKEN
            self.buttonYes['relief'] = RAISED

    #control whether to run mini game or continue normal game
    def executeMiniButtons(self):
        self.question.destroy()
        self.buttonNo.destroy()
        self.buttonYes.destroy()
        self.enterInstruction.destroy()
        if self.miniGameRun:
            self.runMiniGame()

    #run minigame if magic box is collected
    def runMiniGame(self):
        #remove game functionality from keys while minigame is being played
        self.accept("a", self.doNothing)
        self.accept("f", self.doNothing)
        self.accept("w", self.doNothing)
        self.accept("e", self.doNothing)
        self.accept("q", self.doNothing)
        self.accept("enter", self.doNothing)

        #temporarily stop checking collisions on main game level
        taskMgr.remove('checkCollisionsTask')

        #temporarily add task
        taskMgr.add(self.miniGameCheckCollisions,
                    'miniGameCheckCollisionsTask')

        #temporary mini game controls
        self.accept("arrow_up", self.eventUpMini)
        self.accept("arrow_up-repeat", self.eventUpMini)
        self.accept("arrow_right", self.eventRightMini)
        self.accept("arrow_right-repeat", self.eventRightMini)
        self.accept("arrow_left", self.eventLeftMini)
        self.accept("arrow_left-repeat", self.eventLeftMini)
        self.accept("arrow_down", self.eventDownMini)
        self.accept("arrow_down-repeat", self.eventDownMini)
        self.accept("x", self.eventAxe)

        self.miniGameRun = False

        #shift camera down to minigame level
        self.x, self.y, self.z = camera.getPos()
        shiftPos = camera.posInterval(
            0.1, Point3(self.scaleBy // 2, self.scaleBy // 2, -148))
        miniGameView = Sequence(shiftPos)
        miniGameView.start()

        #game objects (object,x,y,scale)
        self.miniGameModles = [("plants/foliage01.egg.pz", 11, 12, 1),
                               ("plants/foliage02.egg.pz", -12, 14, 1),
                               ("plants/shrubbery.egg.pz", 1, 14, 1),
                               ("plants/cactus1.egg", 0, 0, 1),
                               ("plants/cactus2.egg", 2.5, 11, 1),
                               ("chicken.egg", 0, 0, 0.15)]

        #create minigame ground
        land = loader.loadModel("box")
        land.setPos(0, 0, -150)
        land.setSy(self.scaleBy)
        land.setSx(self.scaleBy)
        land.setSz(0.5)
        land.reparentTo(render)

        self.instructionsChicken = OnscreenText(text="Find chicken to return!",
                                                align=TextNode.ACenter,
                                                fg=(1, 1, 1, 1),
                                                pos=(0, 0.5),
                                                scale=.08,
                                                shadow=(0, 0, 0, 0.5))

        #load and initialize box for chicken to be rendered to
        x, y, z = self.cameraCurPos
        animal = loader.loadModel("box")
        animal.setScale(1)
        animal.setPos(randint(1, 118), randint(10, 106), -150.75)
        animal.reparentTo(render)
        animalColl = self.initCollisionSphere(animal, 0.75, False)
        #load chicken
        chicken = loader.loadModel("chicken")
        chicken.setScale(0.15)
        chicken.setPos(0.5, 0.5, 1.25)
        chicken.setHpr(0, 0, 0)
        chicken.reparentTo(animal)
        #store animal into
        self.animalColls += [animalColl]
        animalGroundHandler = CollisionHandlerQueue()
        self.animals += [[animal, 0, animalGroundHandler]]
        self.cTrav.addCollider(animalColl[0], animalGroundHandler)

    #when game is done,change setting back to original
    def miniGameDone(self):
        self.instructionsChicken.destroy()

        #delete new chicken
        self.animalColls[-1][0].remove_node()
        self.animals[-1][0].remove_node()
        self.animalColls = self.animalColls[:-1]
        self.animals = self.animals[:-1]

        #back to original game controls
        self.accept("arrow_up", self.eventArrowPressed, ["up"])
        self.accept("arrow_up-repeat", self.eventArrowPressed, ["up"])
        self.accept("arrow_right", self.eventArrowPressed, ["right"])
        self.accept("arrow_right-repeat", self.eventArrowPressed, ["right"])
        self.accept("arrow_left", self.eventArrowPressed, ["left"])
        self.accept("arrow_left-repeat", self.eventArrowPressed, ["left"])
        self.accept("arrow_down", self.eventArrowPressed, ["down"])
        self.accept("arrow_down-repeat", self.eventArrowPressed, ["down"])
        self.accept("f", self.eventAerielView)
        self.accept("w", self.eventPlanter)
        self.accept("e", self.changeSelectedPlanterOpt, ["e"])
        self.accept("q", self.changeSelectedPlanterOpt, ["e"])
        if not self.haveAxe:
            self.accept('x', self.doNothing)

        #redo taskMgr
        taskMgr.add(self.checkCollisions, 'checkCollisionsTask')
        taskMgr.remove('miniGameCheckCollisionsTask')

        #go back to normal view
        shiftPos = camera.posInterval(0.1, Point3(self.x, self.y, self.z))
        normalGameView = Sequence(shiftPos)
        normalGameView.start()

    #check if main character collided with chicken
    def miniGameCheckCollisions(self, task):
        #check collisions for mainChar
        entries = list(self.mainCharGroundHandler.getEntries())
        entries.sort(key=lambda x: x.getSurfacePoint(render).getZ())
        #if bump into chicken,go back to normal gam
        if (len(entries) > 0):
            self.miniGameDone()
        return Task.cont

    #set what happens when up arrow pressed
    def eventUpMini(self):
        self.curPosMini = self.mainChar.getPos()
        self.cameraCurPosMini = camera.getPos()
        x, y, z = base.camera.getPos()
        if y + self.moveMainCharX < 107:
            camera.setPos(x, y + self.moveMainCharY, z)

    #set what happens when down arrow pressed
    def eventDownMini(self):
        self.curPosMini = self.mainChar.getPos()
        self.cameraCurPosMini = camera.getPos()
        x, y, z = base.camera.getPos()
        if y - self.moveMainCharX > -9:
            camera.setPos(x, y - self.moveMainCharY, z)

    #set what happens when right arrow pressed
    def eventRightMini(self):
        self.curPosMini = self.mainChar.getPos()
        self.cameraCurPosMini = camera.getPos()
        x, y, z = base.camera.getPos()
        if x + self.moveMainCharX < 119:
            camera.setPos(x + self.moveMainCharX, y, z)

    #set what happens when left arrow pressed
    def eventLeftMini(self):
        self.curPosMini = self.mainChar.getPos()
        self.cameraCurPosMini = camera.getPos()
        x, y, z = base.camera.getPos()
        if x - self.moveMainCharX > 0:
            camera.setPos(x - self.moveMainCharY, y, z)

    #reload game
    def restartGame(self):
        self.loadStartScreen()
Beispiel #23
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()
Beispiel #24
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
Beispiel #25
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)
Beispiel #26
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()
Beispiel #27
0
class CatalogTabButton(NodePath):
    def __init__(self, catalogGui, nodeName, clickEvent):
        NodePath.__init__(self, catalogGui.attachNewNode(nodeName))

        self.active = False
        self.activePage = 0
        self.catalogGui = catalogGui
        self.catalogItemPages = []
        self.otherTabs = []
        self.clickEvent = clickEvent

        self.clickedNode = CatalogGlobals.CatalogNodePath.find('**/'+nodeName+'_DN').copyTo(self)
        self.hoverNode = CatalogGlobals.CatalogNodePath.find('**/'+nodeName+'_OVR').copyTo(self)

        self.tabButton = DirectButton(parent=self, relief=None, image=(self.clickedNode, self.clickedNode, self.hoverNode), command=self.tabClicked)

    def tabClicked(self):
        if self.active:
            return
        for tab in self.otherTabs:
            tab.disableTab()
        self.active = True
        self.catalogGui.setCurrentTab(self)
        self.showPages()
        self.updateArrows()
        self.clickEvent()

    def setOtherTabs(self, otherTabs):
        self.otherTabs = otherTabs

    def setCatalogItemPages(self, catalogItemPages):
        self.catalogItemPages = catalogItemPages

    def showPages(self):
        self.hidePages()
        if self.catalogItemPages:
            self.catalogItemPages[self.activePage].show()
            self.catalogGui.setActivePage(self.activePage)

    def hidePages(self):
        for page in self.catalogItemPages:
            page.hide()

    def disableTab(self):
        if not self.active:
            return
        self.active = False
        self.hidePages()
        self.activePage = 0

    def updateArrows(self):
        self.catalogGui.enableBothArrows()
        if self.activePage == 0:
            self.catalogGui.disableLeftArrow()
        if self.activePage == len(self.catalogItemPages) - 1:
            self.catalogGui.disableRightArrow()

    def moveLeft(self):
        self.activePage -= 1
        self.showPages()
        self.updateArrows()

    def moveRight(self):
        self.activePage += 1
        self.showPages()
        self.updateArrows()

    def lockItems(self):
        for page in self.catalogItemPages:
            page.lockItems()

    def updateItems(self, gifting):
        for page in self.catalogItemPages:
            page.updateItems(gifting)

    def cleanup(self):
        for page in self.catalogItemPages:
            page.cleanup()

        self.tabButton.destroy()

        NodePath.removeNode(self)
Beispiel #28
0
class MainMenu(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        self.accept("Exit",self.__exit)
        self.__rm = ResourcesManager()
        self.__destroySetting = False

    # 菜单界面
    def start(self):
        #全屏
        self.setFullScreen(0)

        #load background image
        self.__image = OnscreenImage(image='../../resources/images/menu/home1.png',scale=1)
        self.__image.setSx(self.getAspectRatio())
        self.__image.setTransparency(TransparencyAttrib.MAlpha)

        # 监听输入
        self.__keyInput = MenuPlayerInputHandler()
        self.accept("NewGame",self.__new_game)
        self.accept("LoadGame",self.__load_game)
        self.accept("Description",self.__description)
        self.accept("ChangeMenu",self.__change_menu)

        self.accept("a",self.setting_menu)
        self.accept("b",self.setting_destroy)

    # 设置全屏
    def setFullScreen(self,full):
        if full == 1 :
            self.__setFullscreen(2560,1600,0,0,1)
        else:
            self.__setFullscreen(800,600,150,50,0)

    # 清除界面,清除监听
    def destroy(self):
        self.__image.destroy()
        self.__keyInput.destroy()

    # 私有函数,选择全屏
    def __setFullscreen(self, width, height, posX, posY, full):
        winProps = WindowProperties()
        winProps.setOrigin(posX, posY)
        winProps.setSize(width, height)
        winProps.setFullscreen(full)
        self.win.requestProperties(winProps)

    # 私有函数,进入新建游戏界面
    def __new_game(self):
        print '进入new game'
        messenger.send("serious_new_game")
        print '发送了serious_new_game'

    # 私有函数,进入读取游戏界面
    def __load_game(self):
        print '进入load game'
        messenger.send("serious_load_game")
        print '发送了serious_load_game'

    # 私有函数,进入about界面
    def __description(self):
        print '进入description'
        messenger.send("serious_description")
        print '发送了serious_description'

    # 私有函数,用来自建的选择进入的游戏界面
    def __change_mode(self,image_path):
        self.__image.setImage(image_path)

    def __exit(self):
        print '进入exit'
        # self.__del__()
        exit()

    # 私有函数,更改游戏目录
    def __change_menu(self):
        switch_count = {0:'../../resources/images/menu/home1.png',
                        1:'../../resources/images/menu/home2.png',
                        2:'../../resources/images/menu/home3.png',
                        3:'../../resources/images/menu/home4.png',}
        self.__change_mode(switch_count[self.__keyInput.get_count()])

    #设置界面
    def setting_menu(self):
        if self.__destroySetting==False:
            # 设置界面背景图
            self.__background = OnscreenImage(image='../../resources/images/settings/setting_frame.png', pos=(0, 0, 0),
                                              scale=(1.0, 0, 0.7))
            self.__background.setTransparency(TransparencyAttrib.MAlpha)

            ##滑动条
            self.__slider = DirectSlider(pos=(0.16, 0, 0.26), scale=0.5, value=0.5, command=self.__setMusicSliderVolume,
                                         frameSize=(-1.0, 0.9, -0.06, 0.06),
                                         image='../../resources/images/settings/slide_bar.png',
                                         image_pos=(-0.05, 0, 0.0), image_scale=(1.0, 0, 0.05),
                                         thumb_image='../../resources/images/settings/slide_btn.png',
                                         thumb_image_pos=(-0.0, 0, 0.0), thumb_image_scale=0.1,
                                         thumb_frameSize=(0.0, 0.0, 0.0, 0.0))
            self.__slider.setTransparency(TransparencyAttrib.MAlpha)

            # self.__musicButton = DirectButton(pos=(0.9, 0, 0.75), text="Close", scale=0.1, pad=(0.2, 0.2), rolloverSound=None,
            #                                   clickSound=None, command=self.toggleMusicBox,extraArgs=[base])

            # 继续按钮
            self.__continueButton = DirectButton(pos=(-0.25, 0, 0.0), text="", scale=(0.2, 0, 0.1),
                                                 command=self.__continue_game,
                                                 image=("../../resources/images/settings/btn_continue_0.png",
                                                        "../../resources/images/settings/btn_continue_0.png"
                                                        , "../../resources/images/settings/btn_continue_1.png"),
                                                 frameColor=(0, 0, 0, 0))
            self.__continueButton.setTransparency(TransparencyAttrib.MAlpha)

            # 存档按钮
            self.__saveButton = DirectButton(pos=(0.33, 0, 0.0), text="", scale=(0.2, 0, 0.1), command=self.__save_game,
                                             image=("../../resources/images/settings/btn_save_0.png",
                                                    "../../resources/images/settings/btn_save_0.png"
                                                    , "../../resources/images/settings/btn_save_1.png"),
                                             frameColor=(0, 0, 0, 0))
            self.__saveButton.setTransparency(TransparencyAttrib.MAlpha)

            # 帮助按钮
            self.__helpButton = DirectButton(pos=(-0.25, 0, -0.25), text="", scale=(0.2, 0, 0.1), command=self.__help,
                                             image=("../../resources/images/settings/btn_help_0.png",
                                                    "../../resources/images/settings/btn_help_0.png"
                                                    , "../../resources/images/settings/btn_help_1.png"),
                                             frameColor=(0, 0, 0, 0))
            self.__helpButton.setTransparency(TransparencyAttrib.MAlpha)

            # 回到主界面按钮
            self.__homeButton = DirectButton(pos=(0.33, 0, -0.25), text="", scale=(0.2, 0, 0.1), command=self.__return_home,
                                             image=("../../resources/images/settings/btn_home_0.png",
                                                    "../../resources/images/settings/btn_home_0.png"
                                                    , "../../resources/images/settings/btn_home_1.png"),
                                             frameColor=(0, 0, 0, 0))
            self.__homeButton.setTransparency(TransparencyAttrib.MAlpha)

            # 设置滑动条value
            self.__slider['value'] = self.__rm.get_volume()

            self.__destroySetting = True

    #移除设置界面所有控件
    def setting_destroy(self):
        if self.__destroySetting==True:
            self.__background.destroy()
            self.__rm.set_volume(self.__slider['value'])
            self.__slider.destroy()
            # self.__musicButton.destroy()
            self.__continueButton.destroy()
            self.__saveButton.destroy()
            self.__helpButton.destroy()
            self.__homeButton.destroy()
            self.__destroySetting = False

    # 设置音乐声音大小
    def __setMusicSliderVolume(self):
        newVolume = self.__slider.guiItem.getValue()
        self.__rm.set_volume(newVolume)

    # 设置界面,私有函数,继续游戏
    def __continue_game(self):
        self.setting_destroy()

    # 设置界面,私有函数,存档
    def __save_game(self):
        self.setting_destroy()

    # 设置界面,私有函数,游戏帮助
    def __help(self):
        self.setting_destroy()

    # 设置界面,私有函数,回到主界面
    def __return_home(self):
        self.setting_destroy()
Beispiel #29
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()
Beispiel #30
0
class cApplication(DirectObject):
    def __init__(self):
        # create world
        self.world = cWorld()
        # setup controls
        self.setupControls()
        # display title information
        self.title = OnscreenText(text='BOIDS.PY - SEEK & ARRIVE',
                                  fg=(1.0, 1.0, 1.0, 1.0),
                                  pos=(-.98, .9),
                                  scale=0.06)
        # display copright information
        self.copyRight = OnscreenText(text='Copyright (C) 2016 David Lettier.',
                                      fg=(1.0, 1.0, 1.0, 1.0),
                                      pos=(.98, -.98),
                                      scale=0.05)
        # display panda version text
        self.pandaVersion = OnscreenText(text='Panda Version 1.9.2',
                                         fg=(1.0, 1.0, 1.0, 1.0),
                                         pos=(-1.18, -.98),
                                         scale=0.04)
        # display print debug button
        # this button calls the prntDebug function
        self.prntDebugButton = DirectButton(text="Print Debug",
                                            relief=DGG.RAISED,
                                            scale=.1,
                                            pad=(.5, .5),
                                            pos=Vec3(-1.0, 0.0, -.8),
                                            command=self.prntDebug)

    def setupControls(self):
        # accept the esc key to exit application
        self.accept('escape', sys.exit)

    def prntDebug(self):
        # destory debug button
        self.prntDebugButton.destroy()
        # create new clear debug button
        # this button calls the clearDebug function
        self.clearDebugButton = DirectButton(text="Clear Debug",
                                             relief=DGG.RAISED,
                                             scale=.1,
                                             pad=(.5, .5),
                                             pos=Vec3(-1.0, 0.0, -.8),
                                             command=self.clearDebug)
        # create green target position text
        self.greenPos = OnscreenText(
            text='Green Target Pos: ' + str(int(self.world.target.getX())) +
            ", " + str(int(self.world.target.getY())) + ", " +
            str(int(self.world.target.getZ())),
            fg=(1.0, 1.0, 1.0, 1.0),
            pos=(-.8, .8),
            scale=0.05,
            mayChange=True)
        # create blue boid position text
        self.bluePos = OnscreenText(
            text='Blue Boid (Arrive) Pos: ' +
            str(int(self.world.blueBoid.boidModel.getX())) + ", " +
            str(int(self.world.blueBoid.boidModel.getY())) + ", " +
            str(int(self.world.blueBoid.boidModel.getZ())),
            fg=(1.0, 1.0, 1.0, 1.0),
            pos=(-.8, .7),
            scale=0.05,
            mayChange=True)
        # create green boid position text
        self.redPos = OnscreenText(
            text='Red Boid (Seek) Pos: ' +
            str(int(self.world.redBoid.boidModel.getX())) + ", " +
            str(int(self.world.redBoid.boidModel.getY())) + ", " +
            str(int(self.world.redBoid.boidModel.getZ())),
            fg=(1.0, 1.0, 1.0, 1.0),
            pos=(-.8, .6),
            scale=0.05,
            mayChange=True)
        # add the update on screen text task
        taskMgr.add(self.updateOSTxt, 'updateOSTxt')

    def updateOSTxt(self, Task):
        # update green target position text
        self.greenPos.setText('Green Target Pos: ' +
                              str(int(self.world.target.getX())) + ", " +
                              str(int(self.world.target.getY())) + ", " +
                              str(int(self.world.target.getZ())))
        # update blue boid position text
        self.bluePos.setText('Blue Boid (Arrive) Pos: ' +
                             str(int(self.world.blueBoid.boidModel.getX())) +
                             ", " +
                             str(int(self.world.blueBoid.boidModel.getY())) +
                             ", " +
                             str(int(self.world.blueBoid.boidModel.getZ())))
        # update red boid position text
        self.redPos.setText('Red Boid (Seek) Pos: ' +
                            str(int(self.world.redBoid.boidModel.getX())) +
                            ", " +
                            str(int(self.world.redBoid.boidModel.getY())) +
                            ", " +
                            str(int(self.world.redBoid.boidModel.getZ())))
        # call task next frame
        return Task.cont

    def clearDebug(self):
        # destory button
        self.clearDebugButton.destroy()
        # destory all debug on screen text
        self.greenPos.destroy()
        self.bluePos.destroy()
        self.redPos.destroy()
        # remove task
        taskMgr.remove('updateOSTxt')
        # create again the print debug button to start the cycle all over again
        self.prntDebugButton = DirectButton(text="Print Debug",
                                            relief=DGG.RAISED,
                                            scale=.1,
                                            pad=(.5, .5),
                                            pos=Vec3(-1.0, 0.0, -.8),
                                            command=self.prntDebug)
Beispiel #31
0
class Character(DirectButton):
    def __init__(self, rootParent, pos, charFolder, charEvt):

        self.btn = DirectButton(
            image="characters/{}/idle_l1.png".format(charFolder),
            frameColor=(0, 0, 0, 0),
            frameSize=(-0.5, 0.5, -1, 1),
            scale=0.15,
            pos=pos,
            parent=rootParent,
            command=base.messenger.send,
            extraArgs=[charEvt],
            pressEffect=True)
        self.btn.setTransparency(1)
        self.animation = None
        self.charFolder = charFolder
        self.movement = None

    def stop(self):
        if self.animation is not None:
            self.animation.finish()
        if self.movement is not None:
            self.movement.finish()

    def destroy(self):
        self.stop()
        self.btn.destroy()

    def setStart(self, newPos):
        if self.movement is not None:
            self.movement.finish()

        self.btn.setPos(newPos)

    def animate(self, animation, direction, framecount, stopMovement=False):
        if stopMovement and self.movement is not None:
            self.movement.finish()

        if self.animation is not None:
            self.animation.finish()
        self.animation = self.getAnimation(animation, direction, framecount)
        self.animation.loop()

    def getAnimation(self, animationName, direction, framecount):
        delay = Wait(0.3)
        animation = Sequence()

        for i in range(1, framecount):
            path = "characters/{}/{}_{}{}.png".format(self.charFolder,
                                                      animationName, direction,
                                                      i)
            animation.append(Func(self.setFrame, path))
            animation.append(delay)

        return animation

    def setFrame(self, path):
        self.btn.setImage(path)
        tex = self.btn.component("image0").getTexture()
        tex.setMagfilter(SamplerState.FT_nearest)
        tex.setMinfilter(SamplerState.FT_nearest)

    def moveTo(self, newPos):
        self.animation.finish()
        direction = ""
        if newPos[0] > self.btn.getX():
            direction = "r"
        else:
            direction = "l"
        self.movement = Sequence(
            Func(self.animate, "run", direction, 4),
            self.btn.posInterval(3.0, newPos),
            Func(self.animate, "idle", direction, 3),
        )
        self.movement.start()
class QuestPoster(DirectFrame):
    notify = directNotify.newCategory('QuestPoster')

    # We need to declare and initialize these variables here
    # because some methods use them as default arguments.
    auxIcon = None

    # Requires one parameter, quest, this must be a Quest instance.
    # The next argument, parent, is where to reparent the DirectFrame to.
    # The next arguments are simply additional options when setting up the DirectFrame.
    def __init__(self, quest, parent=aspect2d, **kw):
        # The quest this poster is representing.
        self.quest = quest
        self.accessibleObjectives = quest.accessibleObjectives if quest else []
        self.viewObjective = quest.accessibleObjectives.seek(
        ) if quest else None

        isObjComplete = False if not quest else (
            self.accessibleObjectives.isComplete() or quest.isComplete())

        # Let's define our options for the DirectFrame.
        bookModel = loader.loadModel(
            'phase_3.5/models/gui/stickerbook_gui.bam')
        optiondefs = (('relief', None,
                       None), ('image', bookModel.find('**/questCard'),
                               None), ('image_scale', (0.8, 1.0, 0.58), None),
                      ('image_color', (1.0, 1.0, 1.0,
                                       1.0) if not isObjComplete else Vec4(
                                           *QuestGlobals.LIGHT_GREEN),
                       None), ('state', DGG.NORMAL, None))
        self.defineoptions(kw, optiondefs)

        # Finally, initialize the DirectFrame.
        DirectFrame.__init__(self, parent, relief=None)
        self.initialiseoptions(QuestPoster)

        # Let's declare and initialize our barebone GUI element variables.
        questTitle = '' if not self.quest else self.quest.name
        self.titleLabel = DirectLabel(parent=self,
                                      relief=None,
                                      text=questTitle,
                                      text_font=CIGlobals.getMinnieFont(),
                                      text_fg=QuestGlobals.TEXT_COLOR,
                                      text_scale=0.05,
                                      text_align=TextNode.ACenter,
                                      text_wordwrap=25.0,
                                      textMayChange=1,
                                      pos=(0, 0, 0.23))

        ##########################################################################
        #           THE FOLLOWING ELEMENTS BELOW ARE GROUPED TOGETHER            #
        ##########################################################################

        # The background frame where the objective image is displayed.
        # This is the colored background frame.

        circleGui = loader.loadModel(
            'phase_4/models/gui/CircleIconBackgroundGui.bam')
        self.auxFrame = DirectFrame(
            parent=self,
            relief=None,
            image=circleGui.find('**/circle_display_interior'),
            image_scale=0.18,
            text='',
            text_pos=(0, -0.11),
            text_fg=QuestGlobals.TEXT_COLOR,
            text_scale=QuestGlobals.QPtextScale,
            text_align=TextNode.ACenter,
            text_wordwrap=11.0,
            pos=QuestGlobals.DEFAULT_LEFT_PICTURE_POS)

        if self.quest and len(
                self.quest.accessibleObjectives) > 1 and not isObjComplete:
            # We can only use arrows when we have more than one objective available.
            arrowGui = loader.loadModel('phase_4/models/gui/QuestArrowGui.bam')
            self.prevObjArrow = DirectButton(
                parent=self.auxFrame,
                relief=None,
                geom=((arrowGui.find('**/quest_arrow_enabled'),
                       arrowGui.find('**/quest_arrow_click'),
                       arrowGui.find('**/quest_arrow_mouseover'),
                       arrowGui.find('**/quest_arrow_disabled'))),
                scale=0.08,
                command=self.switchObjective,
                extraArgs=[0],
                hpr=(180, 0, 0),
                pos=QuestGlobals.DEFAULT_LEFT_ARROW_POS)

            self.nextObjArrow = DirectButton(
                parent=self.auxFrame,
                relief=None,
                geom=((arrowGui.find('**/quest_arrow_enabled'),
                       arrowGui.find('**/quest_arrow_click'),
                       arrowGui.find('**/quest_arrow_mouseover'),
                       arrowGui.find('**/quest_arrow_disabled'))),
                scale=0.08,
                command=self.switchObjective,
                pos=QuestGlobals.DEFAULT_RIGHT_ARROW_POS)

        # The icon that goes on top of the aux frame.
        self.auxIcon = DirectFrame(parent=self.auxFrame,
                                   relief=None,
                                   text=' ',
                                   text_font=CIGlobals.getSuitFont(),
                                   text_pos=(0, -0.03),
                                   text_fg=QuestGlobals.TEXT_COLOR,
                                   text_scale=0.13,
                                   text_align=TextNode.ACenter,
                                   text_wordwrap=13.0,
                                   textMayChange=1)
        self.auxIcon.setColorOff(-1)

        self.auxOutline = DirectLabel(
            parent=self.auxFrame,
            relief=None,
            image=circleGui.find('**/circle_display_outline'),
            image_scale=0.18)

        # The aux text saying: DEFEAT, RECOVER, etc.
        self.auxText = DirectLabel(parent=self,
                                   relief=None,
                                   text=QuestGlobals.RECOVER,
                                   text_font=CIGlobals.getToonFont(),
                                   text_scale=QuestGlobals.QPauxText,
                                   text_fg=QuestGlobals.TEXT_COLOR,
                                   text_align=TextNode.ACenter,
                                   textMayChange=1,
                                   pos=QuestGlobals.DEFAULT_AUX_POS)
        self.auxText.hide()

        ##########################################################################

        # Information displayed about the objective.
        self.objectiveInfo = DirectLabel(
            parent=self,
            relief=None,
            text='',
            text_font=CIGlobals.getToonFont(),
            text_fg=QuestGlobals.TEXT_COLOR,
            text_scale=0.04,
            text_align=TextNode.ACenter,
            text_wordwrap=QuestGlobals.QPtextWordwrap,
            textMayChange=1,
            pos=(QuestGlobals.DEFAULT_INFO_POS))
        self.objectiveInfo.hide()

        # Information displayed showing the location.
        self.locationInfo = DirectLabel(
            parent=self,
            relief=None,
            text='N/A',
            text_font=CIGlobals.getToonFont(),
            text_fg=QuestGlobals.TEXT_COLOR,
            text_scale=QuestGlobals.QPtextScale,
            text_align=TextNode.ACenter,
            text_wordwrap=QuestGlobals.QPtextWordwrap,
            textMayChange=1,
            pos=(0, 0, -0.115))
        self.locationInfo.hide()

        # The progress bar showing the objective's progress
        self.progressBar = DirectWaitBar(parent=self,
                                         relief=DGG.SUNKEN,
                                         frameSize=(-0.95, 0.95, -0.1, 0.12),
                                         borderWidth=(0.025, 0.025),
                                         scale=0.2,
                                         frameColor=(0.945, 0.875, 0.706, 1.0),
                                         barColor=(0.5, 0.7, 0.5, 1),
                                         text='0/0',
                                         text_font=CIGlobals.getToonFont(),
                                         text_scale=0.19,
                                         text_fg=(0.05, 0.14, 0.4, 1),
                                         text_align=TextNode.ACenter,
                                         text_pos=(0, -0.05),
                                         pos=(0, 0, -0.2425))
        self.progressBar.hide()

        # The wood panel at the bottom where rewards are displayed.
        rewardFrameGeom = loader.loadModel(
            'phase_4/models/gui/gag_shop_purchase_gui.bam')
        self.rewardFrame = DirectFrame(
            parent=self,
            relief=None,
            geom=rewardFrameGeom.find('**/Goofys_Sign'),
            geom_scale=(0.62, 0, 0.4),
            pos=(-0.015, 0, -0.25))

        # Let's setup our reward frames.
        reward = None

        if self.quest and len(self.quest.rewards) > 0:
            reward = self.quest.rewards[0]
        self.lReward = QuestRewardFrame(self, reward)

        # The text displayed on the right side of the frame with additional information, if necessary.
        self.sideInfo = DirectLabel(parent=self,
                                    relief=None,
                                    text=QuestGlobals.JUST_FOR_FUN,
                                    text_fg=(0.0, 0.439, 1.0, 1.0),
                                    text_shadow=(0, 0, 0, 1),
                                    pos=(-0.2825, 0, 0.2),
                                    scale=0.03)
        self.sideInfo.setR(-30)

        # This side information is usually not needed, let's hide it.
        self.sideInfo.hide()

        # Remove the nodes of the loaded models we no longer need.
        circleGui.removeNode()
        bookModel.removeNode()
        rewardFrameGeom.removeNode()

        # We are only removing this node if we generated arrows.
        if hasattr(self, 'arrowGui'):
            arrowGui.removeNode()

        # Let's hide this until it is needed.
        self.hide()
        return

    def switchObjective(self, forward=1):
        if forward:
            self.accessibleObjectives.nextObjective()
        else:
            self.accessibleObjectives.lastObjective()
        self.viewObjective = self.accessibleObjectives.seek()
        self.setup()

    def setup(self):
        if self.quest:
            objective = self.viewObjective
            complete = self.accessibleObjectives.isComplete()

            # Let's reset our positioning of elements.
            self.auxFrame.setPos(QuestGlobals.DEFAULT_LEFT_PICTURE_POS)
            self.auxText.setPos(QuestGlobals.DEFAULT_AUX_POS)
            self.objectiveInfo.setPos(QuestGlobals.DEFAULT_INFO_POS)

            # Let's reset our icon.
            self.auxIcon.setScale(1, 1, 1)
            self.auxIcon.setPos(0, 0, 0)
            self.auxIcon.setHpr(0, 0, 0)

            self.objectiveInfo.show()
            self.auxFrame.show()

            # Let's setup the quest progress bar
            progress = objective.progress if hasattr(objective,
                                                     'progress') else None

            if objective.goal > 1:
                self.progressBar['range'] = objective.goal
                self.progressBar['value'] = progress & pow(2, 16) - 1

            if objective.HasProgress and objective.goal > 1 and not complete:
                self.progressBar.show()

            self.auxText.show()

            # Let's handle the objectives.
            if not complete:
                if objective.__class__ == CogObjective:
                    self.handleCogObjective()
                elif objective.__class__ == CogBuildingObjective:
                    self.handleCogBuildingObjective()
                elif objective.__class__ == MinigameObjective:
                    self.handleMinigameObjective()
                elif objective.__class__ == VisitNPCObjective:
                    self.handleNPCObjective()
            else:
                bgColor = QuestGlobals.RED

                if objective.type in DefeatObjectives:
                    bgColor = QuestGlobals.BLUE

                self.handleNPCObjective(auxText=QuestGlobals.RETURN + ' to',
                                        frameColor=bgColor)

            self.lReward.setup()

            newLineInObjInfo = '\n' in self.objectiveInfo['text']
            isShopLoc = QuestGlobals.isShopLocation(
                objective.area) if not complete else True

            if complete:
                locationText = QuestGlobals.getLocationText(None, objective)
            else:
                locationText = QuestGlobals.getLocationText(objective.area)

            self.locationInfo['text'] = locationText
            self.locationInfo['text_pos'] = (0.0, (0.025 if isShopLoc else (
                -0.025 if newLineInObjInfo else 0.0)))
            self.locationInfo.show()
        else:
            # We want to be able to show empty quest posters.
            self.titleLabel.hide()
            self.auxFrame.hide()
            self.auxIcon.hide()

        self.titleLabel.initialiseoptions(DirectLabel)
        self.auxIcon.initialiseoptions(DirectFrame)
        self.auxText.initialiseoptions(DirectLabel)
        self.objectiveInfo.initialiseoptions(DirectLabel)
        self.locationInfo.initialiseoptions(DirectLabel)
        self.rewardFrame.initialiseoptions(DirectFrame)
        self.sideInfo.initialiseoptions(DirectLabel)
        self.lReward.initialiseoptions(DirectFrame)

        # Handle arrow stuff if necessary.
        if hasattr(self, 'prevObjArrow'):
            index = self.accessibleObjectives.seeker
            self.prevObjArrow['state'] = DGG.NORMAL
            self.nextObjArrow['state'] = DGG.NORMAL
            self.prevObjArrow.setPos(QuestGlobals.DEFAULT_LEFT_ARROW_POS)
            self.nextObjArrow.setPos(QuestGlobals.DEFAULT_RIGHT_ARROW_POS)

            if index == 0:
                self.prevObjArrow['state'] = DGG.DISABLED
            elif index == len(self.accessibleObjectives) - 1:
                self.nextObjArrow['state'] = DGG.DISABLED

            self.prevObjArrow.initialiseoptions(DirectButton)
            self.nextObjArrow.initialiseoptions(DirectButton)

    # Changes geometry and scale of an icon.
    def handleSimpleIcon(self, geom, scale, icon):
        icon['geom'] = geom
        icon['geom_scale'] = scale

    def handleComplexIcon(self,
                          geom,
                          icon,
                          scale=QuestGlobals.IMAGE_SCALE_SMALL):
        geom.setDepthWrite(1)
        geom.setDepthTest(1)
        self.fitGeometry(geom, fFlip=1)
        self.handleSimpleIcon(geom, scale, icon)

        # We have to rotate the head and set the scale of the icon.
        if CIGlobals.Suit in geom.getName():
            cogName = geom.getPythonTag('Settings')
            data = QuestGlobals.Suit2PosterZNDScale.get(cogName)
            zOffset = data[0]
            headScale = data[1]
            icon.setScale(headScale)
            icon.setZ(icon.getZ() + zOffset)
            icon.setH(180)
        else:
            icon.setZ(icon.getZ() - 0.01)

    def handleCogObjective(self,
                           iconElement=auxIcon,
                           auxText=QuestGlobals.DEFEAT,
                           frameColor=QuestGlobals.BLUE):
        objective = self.viewObjective
        infoText = objective.getTaskInfo()

        if objective.__class__ == RecoverItemObjective:
            infoText = CIGlobals.makePlural(objective.cog)

        if not iconElement:
            iconElement = self.auxIcon

        # Let's make sure we have a current objective that is
        # an instance of the CogObjective class and this poster isn't destroyed.
        if not objective or not hasattr(self, 'titleLabel') or not isinstance(
                objective, CogObjective):
            return

        if objective.dept:
            icons = loader.loadModel('phase_3/models/gui/cog_icons.bam')
            deptIcon = None

            if objective.dept == Dept.BOSS:
                deptIcon = icons.find('**/CorpIcon')
            else:
                deptIcon = icons.find('**/%sIcon' %
                                      objective.dept.getTie().title())

            # Correct the medallion color.
            deptIcon.setColor(SuitGlobals.medallionColors[objective.dept])

            # Setup the icon and remove the icons node.
            self.handleSimpleIcon(deptIcon, 0.13, iconElement)
            icons.removeNode()
        elif objective.cog == QuestGlobals.Any:
            # We aren't fighting a Cog in particular.
            cogIcon = QuestGlobals.getCogIcon()
            self.handleSimpleIcon(cogIcon, 0.13, iconElement)

        # We're fighting a Cog in particular.
        if not objective.cog == QuestGlobals.Any:
            cogHeadInstance = SuitBank.getSuitByName(objective.cog).getHead()
            cogHead = cogHeadInstance.generate()
            cogHead.setName('%sHead' % CIGlobals.Suit)
            cogHead.setPythonTag('Settings', cogHeadInstance.head)
            cogHead.setScale(2)
            cogHead.setLightOff()
            self.handleComplexIcon(cogHead, iconElement)

            # HACK FIX: Corrects the buggy Flunky glasses.
            glasses = cogHead.find('**/glasses')
            if glasses and not glasses.isEmpty():
                glasses.setScale(1)
                glasses.reparentTo(cogHead)

        if not iconElement is self.auxIcon:
            if hasattr(self, 'goalInfo'):
                # We're working with the second frame, on the right.
                # Let's update the information pertaining to this side.
                self.goalInfo['text'] = infoText
                self.goalInfo.setPos(QuestGlobals.RECOVER_INFO2_POS)
                self.auxText.setPos(QuestGlobals.RECOVER_AUX_POS)
            else:
                raise AttributeError(
                    'Attempted to setup DoubleFrame information for poster using default style.'
                )
        else:
            self.objectiveInfo['text'] = infoText

        # Let's set the progress bar text
        pgBarText = '%d of %d %s' % (objective.progress, objective.goal,
                                     CIGlobals.makePastTense(auxText))
        self.progressBar['text'] = pgBarText

        self.auxText['text'] = auxText

        # Let's set the color of the poster.
        frame = self.auxFrame if iconElement is self.auxIcon else self.goalFrame
        frame['image_color'] = Vec4(*frameColor)

    def handleCogBuildingObjective(self,
                                   iconElement=auxIcon,
                                   auxText=QuestGlobals.DEFEAT,
                                   frameColor=QuestGlobals.BLUE):
        objective = self.viewObjective
        infoText = objective.getTaskInfo()

        if not iconElement:
            iconElement = self.auxIcon

        # Let's make sure we have a current objective that is
        # an instance of the CogBuildingObjective class and this poster isn't destroyed.
        if not objective or not hasattr(self, 'titleLabel') or not isinstance(
                objective, CogBuildingObjective):
            return

        # If we aren't looking for any specific department of building.
        if objective.dept == QuestGlobals.Any:
            # Let's just use the good ol' generic building icon.
            self.handleSimpleIcon(QuestGlobals.getCogBuildingIcon(),
                                  QuestGlobals.SIMPLE_IMAGE_SCALE, iconElement)
        else:
            # Ah geez, we're looking for a specific department.
            # Bossbot tie names are messed up, so we need this if statement.
            dept = objective.dept.getTie(
            ) if not objective.dept == Dept.BOSS else 'corp'
            bldgMdl = loader.loadModel(
                'phase_4/models/modules/suit_landmark_%s.bam' % dept)

            # Next, we need to load the building elevator.
            elevator = loader.loadModel('phase_4/models/modules/elevator.bam')
            elevator.reparentTo(bldgMdl.find('**/*_door_origin'))

            self.handleComplexIcon(bldgMdl, iconElement)

        # Let's set the progress bar text
        pgBarText = '%d of %d %s' % (objective.progress, objective.goal,
                                     CIGlobals.makePastTense(auxText))
        self.progressBar['text'] = pgBarText

        self.objectiveInfo['text'] = infoText
        self.auxText['text'] = auxText
        self.auxFrame['image_color'] = Vec4(*frameColor)

    def handleMinigameObjective(self,
                                iconElement=auxIcon,
                                auxText=QuestGlobals.PLAY,
                                frameColor=QuestGlobals.RED):
        objective = self.viewObjective
        infoText = objective.getTaskInfo()

        if not iconElement:
            iconElement = self.auxIcon

        # Let's make sure we have a current objective that is
        # an instance of the MinigameObjective class and this poster isn't destroyed.
        if not objective or not hasattr(self, 'titleLabel') or not isinstance(
                objective, MinigameObjective):
            return

        # Let's set the icon to the minigame icon.
        self.handleSimpleIcon(QuestGlobals.getTrolleyIcon(),
                              QuestGlobals.SIMPLE_IMAGE_SCALE, iconElement)

        # Let's set the progress bar text
        pgBarText = '%d of %d %s' % (objective.progress, objective.goal,
                                     CIGlobals.makePastTense(auxText))
        self.progressBar['text'] = pgBarText

        self.objectiveInfo['text'] = infoText
        self.auxText['text'] = auxText
        self.auxFrame['image_color'] = Vec4(*frameColor)

    def handleNPCObjective(self,
                           iconElement=auxIcon,
                           auxText=QuestGlobals.VISIT,
                           frameColor=QuestGlobals.BROWN):
        objective = self.viewObjective
        npcId = 0

        if self.accessibleObjectives.isComplete() and not hasattr(
                objective, 'npcId'):
            npcId = objective.assigner
        elif hasattr(objective, 'npcId'):
            npcId = objective.npcId

        if npcId == 0:
            infoText = 'A %s' % NPCGlobals.lHQOfficerF
        else:
            infoText = NPCGlobals.NPCToonNames[npcId]

        if not iconElement:
            iconElement = self.auxIcon

        # Let's generate the head.
        if not npcId == 0:
            dna = ToonDNA()
            dna.setDNAStrand(NPCGlobals.NPCToonDict.get(npcId)[2])
            head = ToonGlobals.generateGuiHead(dna)
            self.handleComplexIcon(head,
                                   iconElement,
                                   scale=QuestGlobals.IMAGE_SCALE_SMALL - 0.01)
        else:
            self.handleSimpleIcon(QuestGlobals.getHQIcon(),
                                  QuestGlobals.SIMPLE_IMAGE_SCALE, iconElement)

        self.auxText['text'] = auxText

        if not iconElement is self.auxIcon:
            if hasattr(self, 'goalInfo'):
                # We're working with the second frame, on the right.
                # Let's update the information pertaining to this side.
                self.goalInfo['text'] = infoText
                self.goalInfo.setPos(QuestGlobals.RECOVER_INFO2_POS)
                self.auxText.setPos(QuestGlobals.RECOVER_AUX_POS)
                self.goalFrame['image_color'] = frameColor
            else:
                raise AttributeError(
                    'Attempted to setup DoubleFrame information for poster using default style.'
                )
        else:
            self.objectiveInfo['text'] = infoText
            self.auxFrame['image_color'] = frameColor

    def fitGeometry(self, geom, fFlip=0, dimension=0.8):
        p1 = Point3()
        p2 = Point3()
        geom.calcTightBounds(p1, p2)
        if fFlip:
            t = p1[0]
            p1.setX(-p2[0])
            p2.setX(-t)
        d = p2 - p1
        biggest = max(d[0], d[2])
        s = dimension / biggest
        mid = (p1 + d / 2.0) * s
        geomXform = hidden.attachNewNode('geomXform')
        for child in geom.getChildren():
            child.reparentTo(geomXform)

        geomXform.setPosHprScale(-mid[0], -mid[1] + 1, -mid[2], 180, 0, 0, s,
                                 s, s)
        geomXform.reparentTo(geom)

    def destroy(self):
        if hasattr(self, 'titleLabel'):
            self.titleLabel.destroy()
            self.auxFrame.destroy()
            self.auxIcon.destroy()
            self.auxOutline.destroy()
            self.auxText.destroy()
            self.objectiveInfo.destroy()
            self.locationInfo.destroy()
            self.progressBar.destroy()
            self.rewardFrame.destroy()
            self.sideInfo.destroy()
            self.lReward.destroy()

            # We need to cleanup our arrows if they were created.
            if hasattr(self, 'prevObjArrow'):
                self.prevObjArrow.destroy()
                self.nextObjArrow.destroy()
                del self.prevObjArrow
                del self.nextObjArrow

            del self.titleLabel
            del self.auxFrame
            del self.auxIcon
            del self.auxOutline
            del self.auxText
            del self.objectiveInfo
            del self.locationInfo
            del self.progressBar
            del self.rewardFrame
            del self.sideInfo
            del self.lReward
            del self.accessibleObjectives
            del self.viewObjective
            DirectFrame.destroy(self)
            self.notify.debug('Destroyed all elements.')
Beispiel #33
0
class CatalogGUI(NodePath, DirectObject):
    def __init__(self, phone, doneEvent=None):
        NodePath.__init__(self, aspect2d.attachNewNode('CatalogGUI'))
        DirectObject.__init__(self)

        CatalogGlobals.CatalogNodePath.find('**/CATALOG_GUI_BKGD').copyTo(self)
        self.setScale(CatalogGlobals.CatalogBKGDScale)

        self.phone = phone
        self.doneEvent = doneEvent

        self.arrowButtons = {}
        self.createArrowButtons()

        self.currentTab = None
        self.tabButtons = {}
        self.createTabButtons()

        self.radioButtons = []
        # self.createRadioButtons()

        self.activePage = 0
        self.gifting = -1

        guiItems = loader.loadModel('phase_5.5/models/gui/catalog_gui')
        hangupGui = guiItems.find('**/hangup')
        hangupRolloverGui = guiItems.find('**/hangup_rollover')
        self.hangup = DirectButton(self, relief=None, pos=(2.28, 0, -1.3),
                                   image=[hangupGui, hangupRolloverGui, hangupRolloverGui, hangupGui],
                                   text=['', TTLocalizer.CatalogHangUp, TTLocalizer.CatalogHangUp],
                                   text_fg=Vec4(1), text_scale=0.07, text_pos=(0.0, 0.14),
                                   command=self.hangUp)
        guiItems.removeNode()

    def setCurrentTab(self, tab):
        self.currentTab = tab

    def getCurrentTab(self):
        return self.currentTab

    def setActivePage(self, activePage):
        self.activePage = activePage

    def getActivePage(self):
        return self.activePage

    def createTabButtons(self):
        # We need to create the tabs in reverse order...
        self.tabButtons['SPECIAL_TAB'] = CatalogTabButton(self, 'BTN7',
                                                          self.specialTabClicked)
        self.tabButtons['NAMETAG_TAB'] = CatalogTabButton(self, 'BTN6',
                                                          self.nametagTabClicked)
        self.tabButtons['CLOTHING_TAB'] = CatalogTabButton(self, 'BTN5',
                                                           self.clothingTabClicked)
        self.tabButtons['PHRASES_TAB'] = CatalogTabButton(self, 'BTN4',
                                                          self.phrasesTabClicked)
        self.tabButtons['EMOTE_TAB'] = CatalogTabButton(self, 'BTN3',
                                                        self.emoteTabClicked)
        self.tabButtons['FURNITURE_TAB'] = CatalogTabButton(self, 'BTN2',
                                                            self.furnitureTabClicked)
        self.tabButtons['POPULAR_TAB'] = CatalogTabButton(self, 'BTN1',
                                                          self.popularTabClicked)
        tabList = []
        for tab in self.tabButtons:
            tabList.append(self.tabButtons[tab])

        for tab in self.tabButtons:
            self.tabButtons[tab].setOtherTabs(tabList)

    def popularTabClicked(self):
        messenger.send('wakeup')

    def furnitureTabClicked(self):
        messenger.send('wakeup')

    def emoteTabClicked(self):
        messenger.send('wakeup')

    def phrasesTabClicked(self):
        messenger.send('wakeup')

    def clothingTabClicked(self):
        messenger.send('wakeup')

    def nametagTabClicked(self):
        messenger.send('wakeup')

    def specialTabClicked(self):
        messenger.send('wakeup')

    def createArrowButtons(self):
        self.arrowButtons['LEFT_ARROW'] = CatalogArrowButton(self, 'LT',
                                                             self.leftArrowClicked)
        self.arrowButtons['RIGHT_ARROW'] = CatalogArrowButton(self, 'RT',
                                                              self.rightArrowClicked)

    def leftArrowClicked(self):
        messenger.send('wakeup')
        if self.currentTab:
            self.currentTab.moveLeft()

    def rightArrowClicked(self):
        messenger.send('wakeup')
        if self.currentTab:
            self.currentTab.moveRight()

    def createRadioButtons(self):
        byNameRadioButton = CatalogRadioButton(self, 'ByName',
                                               self.byNameRadioButtonClicked)
        byCostRadioButton = CatalogRadioButton(self, 'ByCost',
                                               self.byCostRadioButtonClicked)

        self.radioButtons.append(byNameRadioButton)
        self.radioButtons.append(byCostRadioButton)

        for radioButton in self.radioButtons:
            radioButton.setOthers(self.radioButtons)

        byNameRadioButton.enable()

    def byNameRadioButtonClicked(self):
        pass

    def byCostRadioButtonClicked(self):
        pass

    def enableBothArrows(self):
        for arrow in self.arrowButtons:
            self.arrowButtons[arrow].show()

    def disableBothArrows(self):
        for arrow in self.arrowButtons:
            self.arrowButtons[arrow].hide()

    def disableLeftArrow(self):
        self.arrowButtons['LEFT_ARROW'].hide()

    def disableRightArrow(self):
        self.arrowButtons['RIGHT_ARROW'].hide()

    def show(self):
        self.accept('CatalogItemPurchaseRequest', self.__handlePurchaseRequest)
        base.setBackgroundColor(Vec4(0.570312, 0.449219, 0.164062, 1.0))
        NodePath.show(self)
        render.hide()

    def hide(self):
        self.ignore('CatalogItemPurchaseRequest')
        base.setBackgroundColor(ToontownGlobals.DefaultBackgroundColor)
        NodePath.hide(self)
        render.show()

    def unload(self):
        self.hide()

        for arrow in self.arrowButtons:
            self.arrowButtons[arrow].cleanup()

        for tab in self.tabButtons:
            self.tabButtons[tab].cleanup()

        for radio in self.radioButtons:
            radio.cleanup()

        self.hangup.destroy()

        self.destroy()

    def destroy(self):
        NodePath.removeNode(self)

    def hangUp(self):
        self.unload()
        print self.doneEvent
        messenger.send(self.doneEvent)

    def __handlePurchaseRequest(self, item):
        item.requestPurchase(self.phone, self.__handlePurchaseResponse)

    def __handlePurchaseResponse(self, retCode, item):
        self.lockItems()

    def lockItems(self):
        for tab in self.tabButtons:
            self.tabButtons[tab].lockItems()

    def updateItems(self):
        for tab in self.tabButtons:
            self.tabButtons[tab].updateItems(self.gifting)
class CatalogGUI(NodePath, DirectObject):
    def __init__(self, phone, doneEvent=None):
        NodePath.__init__(self, aspect2d.attachNewNode('CatalogGUI'))
        DirectObject.__init__(self)

        CatalogGlobals.CatalogNodePath.find('**/CATALOG_GUI_BKGD').copyTo(self)
        self.setScale(CatalogGlobals.CatalogBKGDScale)

        self.phone = phone
        self.doneEvent = doneEvent

        self.arrowButtons = {}
        self.createArrowButtons()

        self.currentTab = None
        self.tabButtons = {}
        self.createTabButtons()

        self.radioButtons = []
        # self.createRadioButtons()

        self.activePage = 0
        self.gifting = -1

        guiItems = loader.loadModel('phase_5.5/models/gui/catalog_gui')
        hangupGui = guiItems.find('**/hangup')
        hangupRolloverGui = guiItems.find('**/hangup_rollover')
        self.hangup = DirectButton(
            self,
            relief=None,
            pos=(2.28, 0, -1.3),
            image=[hangupGui, hangupRolloverGui, hangupRolloverGui, hangupGui],
            text=['', TTLocalizer.CatalogHangUp, TTLocalizer.CatalogHangUp],
            text_fg=Vec4(1),
            text_scale=0.07,
            text_pos=(0.0, 0.14),
            command=self.hangUp)
        guiItems.removeNode()

        jarGui = loader.loadModel('phase_3.5/models/gui/jar_gui')
        self.moneyDisplay = DirectLabel(
            parent=self,
            relief=None,
            pos=(2.28, 0, -0.9),
            scale=0.8,
            text=str(base.localAvatar.getMoney()),
            text_scale=0.18,
            text_fg=(0.95, 0.95, 0, 1),
            text_shadow=(0, 0, 0, 1),
            text_pos=(0, -0.1, 0),
            image=jarGui.find('**/Jar'),
            text_font=ToontownGlobals.getSignFont())

        jarGui.removeNode()
        return

    def setCurrentTab(self, tab):
        self.currentTab = tab

    def getCurrentTab(self):
        return self.currentTab

    def setActivePage(self, activePage):
        self.activePage = activePage

    def getActivePage(self):
        return self.activePage

    def createTabButtons(self):
        # We need to create the tabs in reverse order...
        self.tabButtons['SPECIAL_TAB'] = CatalogTabButton(
            self, 'BTN7', self.specialTabClicked)
        self.tabButtons['NAMETAG_TAB'] = CatalogTabButton(
            self, 'BTN6', self.nametagTabClicked)
        self.tabButtons['CLOTHING_TAB'] = CatalogTabButton(
            self, 'BTN5', self.clothingTabClicked)
        self.tabButtons['PHRASES_TAB'] = CatalogTabButton(
            self, 'BTN4', self.phrasesTabClicked)
        self.tabButtons['EMOTE_TAB'] = CatalogTabButton(
            self, 'BTN3', self.emoteTabClicked)
        self.tabButtons['FURNITURE_TAB'] = CatalogTabButton(
            self, 'BTN2', self.furnitureTabClicked)
        self.tabButtons['POPULAR_TAB'] = CatalogTabButton(
            self, 'BTN1', self.popularTabClicked)
        tabList = []
        for tab in self.tabButtons:
            tabList.append(self.tabButtons[tab])

        for tab in self.tabButtons:
            self.tabButtons[tab].setOtherTabs(tabList)

    def popularTabClicked(self):
        messenger.send('wakeup')

    def furnitureTabClicked(self):
        messenger.send('wakeup')

    def emoteTabClicked(self):
        messenger.send('wakeup')

    def phrasesTabClicked(self):
        messenger.send('wakeup')

    def clothingTabClicked(self):
        messenger.send('wakeup')

    def nametagTabClicked(self):
        messenger.send('wakeup')

    def specialTabClicked(self):
        messenger.send('wakeup')

    def createArrowButtons(self):
        self.arrowButtons['LEFT_ARROW'] = CatalogArrowButton(
            self, 'LT', self.leftArrowClicked)
        self.arrowButtons['RIGHT_ARROW'] = CatalogArrowButton(
            self, 'RT', self.rightArrowClicked)

    def leftArrowClicked(self):
        messenger.send('wakeup')
        if self.currentTab:
            self.currentTab.moveLeft()

    def rightArrowClicked(self):
        messenger.send('wakeup')
        if self.currentTab:
            self.currentTab.moveRight()

    def createRadioButtons(self):
        byNameRadioButton = CatalogRadioButton(self, 'ByName',
                                               self.byNameRadioButtonClicked)
        byCostRadioButton = CatalogRadioButton(self, 'ByCost',
                                               self.byCostRadioButtonClicked)

        self.radioButtons.append(byNameRadioButton)
        self.radioButtons.append(byCostRadioButton)

        for radioButton in self.radioButtons:
            radioButton.setOthers(self.radioButtons)

        byNameRadioButton.enable()

    def byNameRadioButtonClicked(self):
        pass

    def byCostRadioButtonClicked(self):
        pass

    def enableBothArrows(self):
        for arrow in self.arrowButtons:
            self.arrowButtons[arrow].show()

    def disableBothArrows(self):
        for arrow in self.arrowButtons:
            self.arrowButtons[arrow].hide()

    def disableLeftArrow(self):
        self.arrowButtons['LEFT_ARROW'].hide()

    def disableRightArrow(self):
        self.arrowButtons['RIGHT_ARROW'].hide()

    def show(self):
        self.accept('CatalogItemPurchaseRequest', self.__handlePurchaseRequest)
        self.accept(localAvatar.uniqueName('moneyChange'), self.__moneyChange)
        base.setBackgroundColor(Vec4(0.570312, 0.449219, 0.164062, 1.0))
        NodePath.show(self)
        render.hide()

    def hide(self):
        self.ignore('CatalogItemPurchaseRequest')
        self.ignore(localAvatar.uniqueName('moneyChange'))
        base.setBackgroundColor(ToontownGlobals.DefaultBackgroundColor)
        NodePath.hide(self)
        render.show()

    def unload(self):
        self.hide()

        for arrow in self.arrowButtons:
            self.arrowButtons[arrow].cleanup()

        for tab in self.tabButtons:
            self.tabButtons[tab].cleanup()

        for radio in self.radioButtons:
            radio.cleanup()

        self.hangup.destroy()

        self.destroy()

    def destroy(self):
        NodePath.removeNode(self)

    def hangUp(self):
        self.unload()
        print(self.doneEvent)
        messenger.send(self.doneEvent)

    def __handlePurchaseRequest(self, item):
        item.requestPurchase(self.phone, self.__handlePurchaseResponse)
        self.accept(localAvatar.uniqueName('moneyChange'), self.__moneyChange)

    def __handlePurchaseResponse(self, retCode, item):
        self.lockItems()
        self.accept(localAvatar.uniqueName('moneyChange'), self.__moneyChange)

    def lockItems(self):
        for tab in self.tabButtons:
            self.tabButtons[tab].lockItems()

    def updateItems(self):
        for tab in self.tabButtons:
            self.tabButtons[tab].updateItems(self.gifting)

    def __moneyChange(self, money):
        self.moneyDisplay['text'] = str(money)
Beispiel #35
0
class OptionsPage(DirectFrame):
    notify = directNotify.newCategory('OptionsPage')

    def __init__(self, **kw):
        fade = loader.loadModel('phase_13/models/gui/fade')
        dialog_box = loader.loadModel('phase_3/models/gui/dialog_box_gui')
        optiondefs = (('relief', None, None), ('image', fade, None),
                      ('image_scale', (5, 2, 2), None), ('image_color',
                                                         (0, 0, 0, 0.3), None),
                      ('text', 'Options', None), ('text_font', FONT, None),
                      ('text_scale', 0.08, None), ('text_pos', (0, 0.4), None),
                      ('state', DGG.NORMAL, None), ('geom', dialog_box, None),
                      ('sortOrder', 20, None))

        self.defineoptions(kw, optiondefs)
        DirectFrame.__init__(self, aspect2d)
        self.initialiseoptions(OptionsPage)
        self._optionButtons = []
        self.saveButton = None
        fade.removeNode()
        dialog_box.removeNode()

    def toggleMusic(self, enabled):
        options['want-music'] = bool(enabled)

    def toggleSFX(self, enabled):
        options['want-sfx'] = bool(enabled)

    def toggleRankView(self, enabled):
        options['show-player-ranks'] = bool(enabled)

    def togglePlayerNames(self, enabled):
        options['show-player-names'] = bool(enabled)

    def load(self):
        cmdMap = {
            'Toggle Music': [2.65, self.toggleMusic, options['want-music']],
            'Toggle Sound Effects':
            [1.27, self.toggleSFX, options['want-sfx']],
            'Toggle Rank Visibility':
            [1.27, self.toggleRankView, options['show-player-ranks']],
            'Toggle Player Names':
            [1.3, self.togglePlayerNames, options['show-player-names']]
        }
        startZ = 0.25
        for bText, bOptions in cmdMap.items():
            border, callback, configVal = bOptions
            checkbox = DirectCheckButton(parent=self,
                                         relief=None,
                                         text=bText,
                                         text_font=FONT,
                                         command=callback,
                                         text_scale=0.8,
                                         boxPlacement='right',
                                         boxBorder=border,
                                         scale=0.1,
                                         pos=(-0.1, 0, startZ),
                                         indicatorValue=configVal)
            startZ -= 0.17
            self._optionButtons.append(checkbox)

        buttonModels = loader.loadModel('phase_3.5/models/gui/inventory_gui')
        upButton = buttonModels.find('**//InventoryButtonUp')
        downButton = buttonModels.find('**/InventoryButtonDown')
        rolloverButton = buttonModels.find('**/InventoryButtonRollover')
        self.saveButton = DirectButton(parent=self,
                                       text_font=FONT,
                                       text='Save',
                                       text_pos=(0, -.17),
                                       scale=0.2,
                                       text_scale=0.68,
                                       command=self.unload,
                                       image=(upButton, downButton,
                                              rolloverButton),
                                       relief=None,
                                       text_fg=(0, 0, 0, 1),
                                       pos=(0, 0, -0.39),
                                       image_color=(1, 0.94, 0, 1),
                                       image_scale=(17, 1, 7),
                                       sortOrder=DGG.GEOM_SORT_INDEX)
        buttonModels.removeNode()

    def unload(self):
        if base.cr.mainMenu:
            base.cr.mainMenu.configReload()

        options.reload()
        for checkbox in self._optionButtons:
            checkbox.destroy()

        self._optionButtons = []

        if self.saveButton:
            self.saveButton.destroy()
            self.saveButton = None

        self.destroy()
Beispiel #36
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()
Beispiel #37
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())
Beispiel #38
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()
Beispiel #39
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()
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)
Beispiel #41
0
 def destroy(self):
     self.ignoreAll()
     DirectButton.destroy(self)