예제 #1
0
class DistributedFindFour(DistributedNode.DistributedNode):
    def __init__(self, cr):
        NodePath.__init__(self, 'DistributedFindFour')
        DistributedNode.DistributedNode.__init__(self, cr)
        self.cr = cr
        self.reparentTo(render)
        self.boardNode = loader.loadModel(
            'phase_6/models/golf/findfour_game.bam')
        self.boardNode.reparentTo(self)
        self.board = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0],
                      [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0],
                      [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]
        self.exitButton = None
        self.inGame = False
        self.waiting = True
        self.startButton = None
        self.playerNum = None
        self.turnText = None
        self.isMyTurn = False
        self.wantTimer = True
        self.leaveButton = None
        self.screenText = None
        self.turnText = None
        self.exitButton = None
        self.numRandomMoves = 0
        self.blinker = Sequence()
        self.playersTurnBlinker = Sequence()
        self.yourTurnBlinker = Sequence()
        self.winningSequence = Sequence()
        self.moveSequence = Sequence()
        self.moveList = []
        self.mySquares = []
        self.playerSeats = None
        self.moveCol = None
        self.move = None
        self.accept('mouse1', self.mouseClick)
        self.traverser = base.cTrav
        self.pickerNode = CollisionNode('mouseRay')
        self.pickerNP = camera.attachNewNode(self.pickerNode)
        self.pickerNode.setFromCollideMask(BitMask32(4096))
        self.pickerRay = CollisionRay()
        self.pickerNode.addSolid(self.pickerRay)
        self.myHandler = CollisionHandlerQueue()
        self.traverser.addCollider(self.pickerNP, self.myHandler)
        self.buttonModels = loader.loadModel(
            'phase_3.5/models/gui/inventory_gui')
        self.upButton = self.buttonModels.find('**//InventoryButtonUp')
        self.downButton = self.buttonModels.find('**/InventoryButtonDown')
        self.rolloverButton = self.buttonModels.find(
            '**/InventoryButtonRollover')
        self.clockNode = ToontownTimer()
        self.clockNode.setPos(1.16, 0, -0.83)
        self.clockNode.setScale(0.3)
        self.clockNode.hide()
        self.tintConstant = Vec4(0.25, 0.25, 0.25, 0)
        self.ghostConstant = Vec4(0, 0, 0, 0.5)
        self.knockSound = base.loadSfx('phase_5/audio/sfx/GUI_knock_1.ogg')
        self.clickSound = base.loadSfx(
            'phase_3/audio/sfx/GUI_balloon_popup.ogg')
        self.moveSound = base.loadSfx('phase_6/audio/sfx/CC_move.ogg')
        self.accept('stoppedAsleep', self.handleSleep)
        from direct.fsm import ClassicFSM, State
        self.fsm = ClassicFSM.ClassicFSM('ChineseCheckers', [
            State.State('waitingToBegin', self.enterWaitingToBegin,
                        self.exitWaitingToBegin, ['playing', 'gameOver']),
            State.State('playing', self.enterPlaying, self.exitPlaying,
                        ['gameOver']),
            State.State('gameOver', self.enterGameOver, self.exitGameOver,
                        ['waitingToBegin'])
        ], 'waitingToBegin', 'waitingToBegin')
        startLoc = self.boardNode.find('**/locators')
        self.locatorList = list(startLoc.getChildren())
        self.startingPositions = self.locatorList.pop(0)
        self.startingPositions = self.startingPositions.getChildren()
        instancePiece = self.boardNode.find('**/pieces')
        tempList = []
        for x in xrange(7):
            self.startingPositions[x].setTag('StartLocator', '%d' % x)
            collNode = CollisionNode('startpicker%d' % x)
            collNode.setIntoCollideMask(BitMask32(4096))
            tempList.append(self.startingPositions[x].attachNewNode(collNode))
            tempList[x].node().addSolid(
                CollisionTube(0, 0, 0.23, 0, 0, -.23, 0.2))

        for z in self.startingPositions:
            y = instancePiece.copyTo(z)
            for val in y.getChildren():
                val.hide()

        tempList = []
        for x in xrange(42):
            self.locatorList[x].setTag('GamePeiceLocator', '%d' % x)
            collNode = CollisionNode('startpicker%d' % x)
            collNode.setIntoCollideMask(BitMask32(4096))
            tempList.append(self.locatorList[x].attachNewNode(collNode))
            tempList[x].node().addSolid(CollisionSphere(0, 0, 0, 0.2))

        for z in self.locatorList:
            y = instancePiece.copyTo(z)
            for val in y.getChildren():
                val.hide()

        dummyHide = instancePiece.getParent().attachNewNode('DummyHider')
        instancePiece.reparentTo(dummyHide)
        dummyHide.hide()
        return

    def setName(self, name):
        self.name = name

    def announceGenerate(self):
        DistributedNode.DistributedNode.announceGenerate(self)
        if self.table.fsm.getCurrentState().getName() != 'observing':
            if base.localAvatar.doId in self.table.tableState:
                self.seatPos = self.table.tableState.index(
                    base.localAvatar.doId)
                if self.seatPos <= 2:
                    for x in self.startingPositions:
                        x.setH(0)

                    for x in self.locatorList:
                        x.setH(0)

                else:
                    for x in self.startingPositions:
                        x.setH(180)

                    for x in self.locatorList:
                        x.setH(180)

            self.moveCameraForGame()
        else:
            self.seatPos = self.table.seatBumpForObserve
            if self.seatPos > 2:
                for x in self.startingPositions:
                    x.setH(180)

                for x in self.locatorList:
                    x.setH(180)

            self.moveCameraForGame()

    def handleSleep(self, task=None):
        if self.fsm.getCurrentState().getName() == 'waitingToBegin':
            self.exitButtonPushed()
        if task != None:
            task.done
        return

    def setTableDoId(self, doId):
        self.tableDoId = doId
        self.table = self.cr.doId2do[doId]
        self.table.setTimerFunc(self.startButtonPushed)
        self.fsm.enterInitialState()
        self.table.setGameDoId(self.doId)

    def disable(self):
        DistributedNode.DistributedNode.disable(self)
        if self.leaveButton:
            self.leaveButton.destroy()
            self.leavebutton = None
        if self.screenText:
            self.screenText.destroy()
            self.screenText = None
        if self.turnText:
            self.turnText.destroy()
            self.turnText = None
        self.clockNode.stop()
        self.clockNode.hide()
        self.ignore('mouse1')
        self.ignore('stoppedAsleep')
        self.fsm = None
        taskMgr.remove('playerTurnTask')
        return

    def delete(self):
        DistributedNode.DistributedNode.delete(self)
        self.table.gameDoId = None
        self.table.game = None
        if self.exitButton:
            self.exitButton.destroy()
        if self.startButton:
            self.startButton.destroy()
        self.clockNode.stop()
        self.clockNode.hide()
        self.table.startButtonPushed = None
        self.ignore('mouse1')
        self.ignore('stoppedAsleep')
        self.fsm = None
        self.table = None
        self.winningSequence.finish()
        taskMgr.remove('playerTurnTask')
        return

    def getTimer(self):
        self.sendUpdate('requestTimer', [])

    def setTimer(self, timerEnd):
        if self.fsm.getCurrentState() != None and self.fsm.getCurrentState(
        ).getName() == 'waitingToBegin' and not self.table.fsm.getCurrentState(
        ).getName() == 'observing':
            self.clockNode.stop()
            time = globalClockDelta.networkToLocalTime(timerEnd)
            timeLeft = int(time - globalClock.getRealTime())
            if timeLeft > 0 and timerEnd != 0:
                if timeLeft > 60:
                    timeLeft = 60
                self.clockNode.setPos(1.16, 0, -0.83)
                self.clockNode.countdown(timeLeft, self.startButtonPushed)
                self.clockNode.show()
            else:
                self.clockNode.stop()
                self.clockNode.hide()
        return

    def setTurnTimer(self, turnEnd):
        if self.fsm.getCurrentState() != None and self.fsm.getCurrentState(
        ).getName() == 'playing':
            self.clockNode.stop()
            time = globalClockDelta.networkToLocalTime(turnEnd)
            timeLeft = int(time - globalClock.getRealTime())
            if timeLeft > 0:
                self.clockNode.setPos(0.64, 0, -0.27)
                self.clockNode.countdown(timeLeft, self.doRandomMove)
                self.clockNode.show()
        return

    def gameStart(self, playerNum):
        if playerNum != 255:
            self.playerNum = playerNum
            if self.playerNum == 1:
                self.playerColorString = 'Red'
            else:
                self.playerColorString = 'Yellow'
            self.moveCameraForGame()
        self.fsm.request('playing')

    def sendTurn(self, playersTurn):
        if self.fsm.getCurrentState().getName() == 'playing':
            if playersTurn == self.playerNum:
                self.isMyTurn = True
                taskMgr.add(self.turnTask, 'playerTurnTask')
            self.enableTurnScreenText(playersTurn)

    def illegalMove(self):
        self.exitButtonPushed()

    def moveCameraForGame(self):
        if self.table.cameraBoardTrack.isPlaying():
            self.table.cameraBoardTrack.pause()
        rotation = 0
        if self.seatPos <= 2:
            position = self.table.seats[1].getPos()
            position = position + Vec3(0, -8, 12.8)
            int = LerpPosHprInterval(camera, 2, position, Vec3(0, -38, 0),
                                     camera.getPos(), camera.getHpr())
        else:
            position = self.table.seats[4].getPos()
            position = position + Vec3(0, -8, 12.8)
            if camera.getH() < 0:
                int = LerpPosHprInterval(camera, 2, position,
                                         Vec3(-180, -20, 0), camera.getPos(),
                                         camera.getHpr())
            else:
                int = LerpPosHprInterval(camera, 2, position,
                                         Vec3(180, -20, 0), camera.getPos(),
                                         camera.getHpr())
        int.start()

    def enterWaitingToBegin(self):
        if self.table.fsm.getCurrentState().getName() != 'observing':
            self.enableExitButton()
            self.enableStartButton()

    def exitWaitingToBegin(self):
        if self.exitButton:
            self.exitButton.destroy()
            self.exitButton = None
        if self.startButton:
            self.startButton.destroy()
            self.exitButton = None
        self.clockNode.stop()
        self.clockNode.hide()
        return

    def enterPlaying(self):
        self.inGame = True
        self.enableScreenText()
        if self.table.fsm.getCurrentState().getName() != 'observing':
            self.enableLeaveButton()

    def exitPlaying(self):
        self.inGame = False
        if self.leaveButton:
            self.leaveButton.destroy()
            self.leavebutton = None
        self.playerNum = None
        if self.screenText:
            self.screenText.destroy()
            self.screenText = None
        if self.turnText:
            self.turnText.destroy()
            self.turnText = None
        self.clockNode.stop()
        self.clockNode.hide()
        return

    def enterGameOver(self):
        pass

    def exitGameOver(self):
        pass

    def exitWaitCountdown(self):
        self.__disableCollisions()
        self.ignore('trolleyExitButton')
        self.clockNode.reset()

    def enableExitButton(self):
        self.exitButton = DirectButton(
            relief=None,
            text=TTLocalizer.ChineseCheckersGetUpButton,
            text_fg=(1, 1, 0.65, 1),
            text_pos=(0, -.23),
            text_scale=0.8,
            image=(self.upButton, self.downButton, self.rolloverButton),
            image_color=(1, 0, 0, 1),
            image_scale=(20, 1, 11),
            pos=(0.92, 0, 0.8),
            scale=0.15,
            command=lambda self=self: self.exitButtonPushed())
        return

    def enableScreenText(self):
        defaultPos = (-.7, -0.29)
        if self.playerNum == 1:
            message = 'You are Red'
            color = Vec4(1, 0, 0, 1)
        elif self.playerNum == 2:
            message = 'You are Yellow'
            color = Vec4(1, 1, 0, 1)
        else:
            message = TTLocalizer.CheckersObserver
            color = Vec4(0, 0, 0, 1)
        self.screenText = OnscreenText(text=message,
                                       pos=defaultPos,
                                       scale=0.1,
                                       fg=color,
                                       align=TextNode.ACenter,
                                       mayChange=1)

    def enableStartButton(self):
        self.startButton = DirectButton(
            relief=None,
            text=TTLocalizer.ChineseCheckersStartButton,
            text_fg=(1, 1, 0.65, 1),
            text_pos=(0, -.23),
            text_scale=0.6,
            image=(self.upButton, self.downButton, self.rolloverButton),
            image_color=(1, 0, 0, 1),
            image_scale=(20, 1, 11),
            pos=(0.92, 0, 0.57),
            scale=0.15,
            command=lambda self=self: self.startButtonPushed())
        return

    def enableLeaveButton(self):
        self.leaveButton = DirectButton(
            relief=None,
            text=TTLocalizer.ChineseCheckersQuitButton,
            text_fg=(1, 1, 0.65, 1),
            text_pos=(0, -.13),
            text_scale=0.5,
            image=(self.upButton, self.downButton, self.rolloverButton),
            image_color=(1, 0, 0, 1),
            image_scale=(20, 1, 11),
            pos=(0.92, 0, 0.8),
            scale=0.15,
            command=lambda self=self: self.exitButtonPushed())
        return

    def enableTurnScreenText(self, player):
        playerOrder = [1, 4, 2, 5, 3, 6]
        message1 = TTLocalizer.CheckersIts
        if self.turnText != None:
            self.turnText.destroy()
        if player == self.playerNum:
            message2 = TTLocalizer.ChineseCheckersYourTurn
            color = (0, 0, 0, 1)
        elif player == 1:
            message2 = "Red's Turn"
            color = (1, 0, 0, 1)
        elif player == 2:
            message2 = "Yellow's Turn"
            color = (1, 1, 0, 1)
        self.turnText = OnscreenText(text=message1 + message2,
                                     pos=(-0.7, -0.39),
                                     scale=0.092,
                                     fg=color,
                                     align=TextNode.ACenter,
                                     mayChange=1)
        return

    def startButtonPushed(self):
        self.sendUpdate('requestBegin')
        self.startButton.hide()
        self.clockNode.stop()
        self.clockNode.hide()

    def exitButtonPushed(self):
        self.fsm.request('gameOver')
        self.table.fsm.request('off')
        self.clockNode.stop()
        self.clockNode.hide()
        self.table.sendUpdate('requestExit')

    def mouseClick(self):
        messenger.send('wakeup')
        if self.isMyTurn == True and self.inGame == True and not self.moveSequence.isPlaying(
        ):
            if self.moveCol != None:
                self.d_requestMove(self.moveCol)
                self.moveCol = None
                self.isMyTurn = False
                taskMgr.remove('playerTurnTask')
        return

    def handleClicked(self, index):
        pass

    def turnTask(self, task):
        if base.mouseWatcherNode.hasMouse() == False:
            return task.cont
        if self.isMyTurn == False:
            return task.cont
        if self.moveSequence.isPlaying():
            return task.cont
        mpos = base.mouseWatcherNode.getMouse()
        self.pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())
        self.traverser.traverse(render)
        if self.myHandler.getNumEntries() > 0:
            self.myHandler.sortEntries()
            pickedObj = self.myHandler.getEntry(0).getIntoNodePath()
            pickedObj = pickedObj.getNetTag('StartLocator')
            if pickedObj:
                colVal = int(pickedObj)
                if colVal == self.moveCol:
                    return task.cont
                if self.board[0][colVal] == 0:
                    if self.moveCol != None:
                        for x in self.startingPositions[self.moveCol].getChild(
                                1).getChildren():
                            x.hide()

                    self.moveCol = colVal
                    if self.playerNum == 1:
                        self.startingPositions[self.moveCol].getChild(
                            1).getChild(2).show()
                    elif self.playerNum == 2:
                        self.startingPositions[self.moveCol].getChild(
                            1).getChild(3).show()
        return task.cont

    def d_requestMove(self, moveCol):
        self.sendUpdate('requestMove', [moveCol])

    def setGameState(self, tableState, moveCol, movePos, turn):
        messenger.send('wakeup')
        if self.table.fsm.getCurrentState().getName() == 'observing':
            isBlank = True
            for x in xrange(7):
                if self.board[5][x] != 0:
                    isBlank = False
                    break

            gameBlank = True
            for x in xrange(7):
                if tableState[5][x] != 0:
                    gameBlank = False
                    break

            if isBlank == True and gameBlank == False:
                for x in xrange(6):
                    for y in xrange(7):
                        self.board[x][y] = tableState[x][y]

                self.updateGameState()
                return
        if moveCol == 0 and movePos == 0 and turn == 0:
            for x in xrange(6):
                for y in xrange(7):
                    self.board[x][y] = tableState[x][y]

            self.updateGameState()
        else:
            self.animatePeice(tableState, moveCol, movePos, turn)
        didIWin = self.checkForWin()
        if didIWin != None:
            self.sendUpdate('requestWin', [didIWin])
        return

    def updateGameState(self):
        for x in xrange(6):
            for y in xrange(7):
                for z in self.locatorList[x * 7 + y].getChild(1).getChildren():
                    z.hide()

        for x in xrange(6):
            for y in xrange(7):
                state = self.board[x][y]
                if state == 1:
                    self.locatorList[x * 7 + y].getChild(1).getChild(0).show()
                elif state == 2:
                    self.locatorList[x * 7 + y].getChild(1).getChild(1).show()

    def checkForWin(self):
        for x in xrange(6):
            for y in xrange(7):
                if self.board[x][y] == self.playerNum:
                    if self.checkHorizontal(x, y, self.playerNum) == True:
                        return [x, y]
                    elif self.checkVertical(x, y, self.playerNum) == True:
                        return [x, y]
                    elif self.checkDiagonal(x, y, self.playerNum) == True:
                        return [x, y]

        return None

    def announceWinnerPosition(self, x, y, winDirection, playerNum):
        self.isMyturn = False
        if self.turnText:
            self.turnText.hide()
        self.clockNode.stop()
        self.clockNode.hide()
        if winDirection == 0:
            blinkList = self.findHorizontal(x, y, playerNum)
        elif winDirection == 1:
            blinkList = self.findVertical(x, y, playerNum)
        elif winDirection == 2:
            blinkList = self.findDiagonal(x, y, playerNum)
        if blinkList != []:
            print blinkList
            val0 = x * 7 + y
            x = blinkList[0][0]
            y = blinkList[0][1]
            val1 = x * 7 + y
            x = blinkList[1][0]
            y = blinkList[1][1]
            val2 = x * 7 + y
            x = blinkList[2][0]
            y = blinkList[2][1]
            val3 = x * 7 + y
            self.winningSequence = Sequence()
            downBlinkerParallel = Parallel(
                LerpColorInterval(self.locatorList[val0], 0.3,
                                  Vec4(0.5, 0.5, 0.5, 0.5), Vec4(1, 1, 1, 1)),
                LerpColorInterval(self.locatorList[val1], 0.3,
                                  Vec4(0.5, 0.5, 0.5, 0.5), Vec4(1, 1, 1, 1)),
                LerpColorInterval(self.locatorList[val2], 0.3,
                                  Vec4(0.5, 0.5, 0.5, 0.5), Vec4(1, 1, 1, 1)),
                LerpColorInterval(self.locatorList[val3], 0.3,
                                  Vec4(0.5, 0.5, 0.5, 0.5), Vec4(1, 1, 1, 1)))
            upBlinkerParallel = Parallel(
                LerpColorInterval(self.locatorList[val0], 0.3,
                                  Vec4(1, 1, 1, 1), Vec4(0.5, 0.5, 0.5, 0.5)),
                LerpColorInterval(self.locatorList[val1], 0.3,
                                  Vec4(1, 1, 1, 1), Vec4(0.5, 0.5, 0.5, 0.5)),
                LerpColorInterval(self.locatorList[val2], 0.3,
                                  Vec4(1, 1, 1, 1), Vec4(0.5, 0.5, 0.5, 0.5)),
                LerpColorInterval(self.locatorList[val3], 0.3,
                                  Vec4(1, 1, 1, 1), Vec4(0.5, 0.5, 0.5, 0.5)))
            self.winningSequence.append(downBlinkerParallel)
            self.winningSequence.append(upBlinkerParallel)
            self.winningSequence.loop()

    def tie(self):
        self.tieSequence = Sequence(autoFinish=1)
        self.clockNode.stop()
        self.clockNode.hide()
        self.isMyTurn = False
        self.moveSequence.finish()
        if self.turnText:
            self.turnText.hide()
        for x in xrange(41):
            self.tieSequence.append(
                Parallel(
                    LerpColorInterval(self.locatorList[x], 0.15,
                                      Vec4(0.5, 0.5, 0.5, 0.5),
                                      Vec4(1, 1, 1, 1)),
                    LerpColorInterval(self.locatorList[x], 0.15,
                                      Vec4(1, 1, 1, 1),
                                      Vec4(0.5, 0.5, 0.5, 0.5))))

        whisper = WhisperPopup('This Find Four game has resulted in a Tie!',
                               OTPGlobals.getInterfaceFont(),
                               WhisperPopup.WTNormal)
        whisper.manage(base.marginManager)
        self.tieSequence.start()

    def hideChildren(self, nodeList):
        pass

    def animatePeice(self, tableState, moveCol, movePos, turn):
        messenger.send('wakeup')
        for x in xrange(6):
            for y in xrange(7):
                self.board[x][y] = tableState[x][y]

        pos = self.startingPositions[moveCol].getPos()
        if turn == 0:
            peice = self.startingPositions[moveCol].getChild(
                1).getChildren()[2]
            peice.show()
        elif turn == 1:
            peice = self.startingPositions[moveCol].getChild(
                1).getChildren()[3]
            peice.show()
        self.moveSequence = Sequence()
        startPos = self.startingPositions[moveCol].getPos()
        arrayLoc = movePos * 7 + moveCol
        self.moveSequence.append(
            LerpPosInterval(self.startingPositions[moveCol], 1.5,
                            self.locatorList[arrayLoc].getPos(self), startPos))
        self.moveSequence.append(Func(peice.hide))
        self.moveSequence.append(
            Func(self.startingPositions[moveCol].setPos, startPos))
        self.moveSequence.append(Func(self.updateGameState))
        self.moveSequence.start()

    def announceWin(self, avId):
        self.fsm.request('gameOver')

    def doRandomMove(self):
        if self.isMyTurn:
            if self.moveCol != None:
                self.d_requestMove(self.moveCol)
                self.moveCol = None
                self.isMyTurn = False
                taskMgr.remove('playerTurnTask')
            else:
                hasfound = False
                while hasfound == False:
                    x = random.randint(0, 6)
                    if self.board[0][x] == 0:
                        self.d_requestMove(x)
                        self.moveCol = None
                        self.isMyTurn = False
                        taskMgr.remove('playerTurnTask')
                        hasfound = True

        return

    def doNothing(self):
        pass

    def checkHorizontal(self, rVal, cVal, playerNum):
        if cVal == 3:
            for x in xrange(1, 4):
                if self.board[rVal][cVal - x] != playerNum:
                    break
                if self.board[rVal][cVal - x] == playerNum and x == 3:
                    return True

            for x in xrange(1, 4):
                if self.board[rVal][cVal + x] != playerNum:
                    break
                if self.board[rVal][cVal + x] == playerNum and x == 3:
                    return True

            return False
        elif cVal == 2:
            for x in xrange(1, 4):
                if self.board[rVal][cVal + x] != playerNum:
                    break
                if self.board[rVal][cVal + x] == playerNum and x == 3:
                    return True

            return False
        elif cVal == 4:
            for x in xrange(1, 4):
                if self.board[rVal][cVal - x] != playerNum:
                    break
                if self.board[rVal][cVal - x] == playerNum and x == 3:
                    return True

            return False
        else:
            return False

    def checkVertical(self, rVal, cVal, playerNum):
        if rVal == 2:
            for x in xrange(1, 4):
                if self.board[rVal + x][cVal] != playerNum:
                    break
                if self.board[rVal + x][cVal] == playerNum and x == 3:
                    return True

            return False
        elif rVal == 3:
            for x in xrange(1, 4):
                if self.board[rVal - x][cVal] != playerNum:
                    break
                if self.board[rVal - x][cVal] == playerNum and x == 3:
                    return True

            return False
        else:
            return False

    def checkDiagonal(self, rVal, cVal, playerNum):
        if cVal <= 2:
            if rVal == 2:
                for x in xrange(1, 4):
                    if self.board[rVal + x][cVal + x] != playerNum:
                        break
                    if self.board[rVal + x][cVal + x] == playerNum and x == 3:
                        return True

                return False
            elif rVal == 3:
                for x in xrange(1, 4):
                    if self.board[rVal - x][cVal + x] != playerNum:
                        break
                    if self.board[rVal - x][cVal + x] == playerNum and x == 3:
                        return True

                return False
        elif cVal >= 4:
            if rVal == 2:
                for x in xrange(1, 4):
                    if self.board[rVal + x][cVal - x] != playerNum:
                        break
                    if self.board[rVal + x][cVal - x] == playerNum and x == 3:
                        return True

                return False
            elif rVal == 3:
                for x in xrange(1, 4):
                    if self.board[rVal - x][cVal - x] != playerNum:
                        break
                    if self.board[rVal - x][cVal - x] == playerNum and x == 3:
                        return True

                return False
        elif rVal == 3 or rVal == 4 or rVal == 5:
            for x in xrange(1, 4):
                if self.board[rVal - x][cVal - x] != playerNum:
                    break
                if self.board[rVal - x][cVal - x] == playerNum and x == 3:
                    return True

            for x in xrange(1, 4):
                if self.board[rVal - x][cVal - x] != playerNum:
                    break
                if self.board[rVal - x][cVal - x] == playerNum and x == 3:
                    return True

            return False
        elif rVal == 0 or rVal == 1 or rVal == 2:
            for x in xrange(1, 4):
                if self.board[rVal + x][cVal - x] != playerNum:
                    break
                if self.board[rVal + x][cVal - x] == playerNum and x == 3:
                    return True

            for x in xrange(1, 4):
                if self.board[rVal + x][cVal + x] != playerNum:
                    break
                if self.board[rVal + x][cVal + x] == playerNum and x == 3:
                    return True

            return False
        return False

    def findHorizontal(self, rVal, cVal, playerNum):
        if cVal == 3:
            retList = []
            for x in xrange(1, 4):
                retList.append([rVal, cVal - x])
                if self.board[rVal][cVal - x] != playerNum:
                    retList = []
                    break
                if self.board[rVal][cVal - x] == playerNum and x == 3:
                    return retList

            for x in xrange(1, 4):
                retList.append([rVal, cVal + x])
                if self.board[rVal][cVal + x] != playerNum:
                    retList = []
                    break
                if self.board[rVal][cVal + x] == playerNum and x == 3:
                    return retList

            return []
        elif cVal == 2:
            retList = []
            for x in xrange(1, 4):
                retList.append([rVal, cVal + x])
                if self.board[rVal][cVal + x] != playerNum:
                    retList = []
                    break
                if self.board[rVal][cVal + x] == playerNum and x == 3:
                    return retList

            return []
        elif cVal == 4:
            retList = []
            for x in xrange(1, 4):
                retList.append([rVal, cVal - x])
                if self.board[rVal][cVal - x] != playerNum:
                    retList = []
                    break
                if self.board[rVal][cVal - x] == playerNum and x == 3:
                    return retList

            return []
        else:
            return []

    def findVertical(self, rVal, cVal, playerNum):
        if rVal == 2:
            retList = []
            for x in xrange(1, 4):
                retList.append([rVal + x, cVal])
                if self.board[rVal + x][cVal] != playerNum:
                    retList = []
                    break
                if self.board[rVal + x][cVal] == playerNum and x == 3:
                    return retList

            return []
        elif rVal == 3:
            retList = []
            for x in xrange(1, 4):
                retList.append([rVal - x, cVal])
                if self.board[rVal - x][cVal] != playerNum:
                    retList = []
                    break
                if self.board[rVal - x][cVal] == playerNum and x == 3:
                    return retList

            return []
        else:
            return []

    def findDiagonal(self, rVal, cVal, playerNum):
        retList = []
        if cVal <= 2:
            if rVal == 2:
                for x in xrange(1, 4):
                    retList.append([rVal + x, cVal + x])
                    if self.board[rVal + x][cVal + x] != playerNum:
                        retList = []
                        break
                    if self.board[rVal + x][cVal + x] == playerNum and x == 3:
                        return retList

                return []
            elif rVal == 3:
                for x in xrange(1, 4):
                    retList.append([rVal - x, cVal + x])
                    if self.board[rVal - x][cVal + x] != playerNum:
                        retList = []
                        break
                    if self.board[rVal - x][cVal + x] == playerNum and x == 3:
                        return retList

                return []
        elif cVal >= 4:
            if rVal == 2:
                for x in xrange(1, 4):
                    retList.append([rVal + x, cVal - x])
                    if self.board[rVal + x][cVal - x] != playerNum:
                        retList = []
                        break
                    if self.board[rVal + x][cVal - x] == playerNum and x == 3:
                        return retList

                return []
            elif rVal == 3:
                for x in xrange(1, 4):
                    retList.append([rVal - x, cVal - x])
                    if self.board[rVal - x][cVal - x] != playerNum:
                        retList = []
                        break
                    if self.board[rVal - x][cVal - x] == playerNum and x == 3:
                        return retList

                return []
        elif rVal == 3 or rVal == 4 or rVal == 5:
            for x in xrange(1, 4):
                retList.append([rVal - x, cVal - x])
                if self.board[rVal - x][cVal - x] != playerNum:
                    retList = []
                    break
                if self.board[rVal - x][cVal - x] == playerNum and x == 3:
                    return retList

            for x in xrange(1, 4):
                retList.append([rVal + x, cVal - x])
                if self.board[rVal + x][cVal - x] != playerNum:
                    retList = []
                    break
                if self.board[rVal + x][cVal - x] == playerNum and x == 3:
                    return retList

            return []
        elif rVal == 0 or rVal == 1 or rVal == 2:
            for x in xrange(1, 4):
                retList.append([rVal + x, cVal - x])
                if self.board[rVal + x][cVal - x] != playerNum:
                    retList = []
                    break
                if self.board[rVal + x][cVal - x] == playerNum and x == 3:
                    return retList

            for x in xrange(1, 4):
                retList.append([rVal + x, cVal + x])
                if self.board[rVal + x][cVal + x] != playerNum:
                    retList = []
                    break
                if self.board[rVal + x][cVal + x] == playerNum and x == 3:
                    return retList

            return []
        return []
class DistributedCheckers(DistributedNode.DistributedNode):

    def __init__(self, cr):
        NodePath.__init__(self, 'DistributedCheckers')
        DistributedNode.DistributedNode.__init__(self, cr)
        self.cr = cr
        self.reparentTo(render)
        self.boardNode = loader.loadModel('phase_6/models/golf/regular_checker_game.bam')
        self.boardNode.reparentTo(self)
        self.board = CheckersBoard()
        self.exitButton = None
        self.inGame = False
        self.waiting = True
        self.startButton = None
        self.playerNum = None
        self.turnText = None
        self.isMyTurn = False
        self.wantTimer = True
        self.leaveButton = None
        self.screenText = None
        self.turnText = None
        self.exitButton = None
        self.numRandomMoves = 0
        self.blinker = Sequence()
        self.moveList = []
        self.mySquares = []
        self.myKings = []
        self.isRotated = False
        self.accept('mouse1', self.mouseClick)
        self.traverser = base.cTrav
        self.pickerNode = CollisionNode('mouseRay')
        self.pickerNP = camera.attachNewNode(self.pickerNode)
        self.pickerNode.setFromCollideMask(ToontownGlobals.WallBitmask)
        self.pickerRay = CollisionRay()
        self.pickerNode.addSolid(self.pickerRay)
        self.myHandler = CollisionHandlerQueue()
        self.traverser.addCollider(self.pickerNP, self.myHandler)
        self.buttonModels = loader.loadModel('phase_3.5/models/gui/inventory_gui')
        self.upButton = self.buttonModels.find('**//InventoryButtonUp')
        self.downButton = self.buttonModels.find('**/InventoryButtonDown')
        self.rolloverButton = self.buttonModels.find('**/InventoryButtonRollover')
        self.clockNode = ToontownTimer()
        self.clockNode.setPos(1.16, 0, -0.83)
        self.clockNode.setScale(0.3)
        self.clockNode.hide()
        self.playerColors = [Vec4(0, 0, 1, 1), Vec4(0, 1, 0, 1)]
        self.tintConstant = Vec4(0.25, 0.25, 0.25, 0.5)
        self.ghostConstant = Vec4(0, 0, 0, 0.8)
        self.startingPositions = [[0,
          1,
          2,
          3,
          4,
          5,
          6,
          7,
          8,
          9,
          10,
          11], [20,
          21,
          22,
          23,
          24,
          25,
          26,
          27,
          28,
          29,
          30,
          31]]
        self.knockSound = base.loadSfx('phase_5/audio/sfx/GUI_knock_1.ogg')
        self.clickSound = base.loadSfx('phase_3/audio/sfx/GUI_balloon_popup.ogg')
        self.moveSound = base.loadSfx('phase_6/audio/sfx/CC_move.ogg')
        self.accept('stoppedAsleep', self.handleSleep)
        self.fsm = ClassicFSM.ClassicFSM('ChineseCheckers', [State.State('waitingToBegin', self.enterWaitingToBegin, self.exitWaitingToBegin, ['playing', 'gameOver']), State.State('playing', self.enterPlaying, self.exitPlaying, ['gameOver']), State.State('gameOver', self.enterGameOver, self.exitGameOver, ['waitingToBegin'])], 'waitingToBegin', 'waitingToBegin')
        x = self.boardNode.find('**/locator*')
        self.locatorList = x.getChildren()
        tempList = []
        for x in xrange(0, 32):
            self.locatorList[x].setTag('GamePeiceLocator', '%d' % x)
            tempList.append(self.locatorList[x].attachNewNode(CollisionNode('picker%d' % x)))
            tempList[x].node().addSolid(CollisionSphere(0, 0, 0, 0.39))

        for z in self.locatorList:
            y = loader.loadModel('phase_6/models/golf/regular_checker_piecewhite.bam')
            y.find('**/checker_k*').hide()
            zz = loader.loadModel('phase_6/models/golf/regular_checker_pieceblack.bam')
            zz.find('**/checker_k*').hide()
            y.reparentTo(z)
            y.hide()
            zz.reparentTo(z)
            zz.hide()

        return

    def setName(self, name):
        self.name = name

    def announceGenerate(self):
        DistributedNode.DistributedNode.announceGenerate(self)
        if self.table.fsm.getCurrentState().getName() != 'observing':
            if base.localAvatar.doId in self.table.tableState:
                self.seatPos = self.table.tableState.index(base.localAvatar.doId)

    def handleSleep(self, task = None):
        if self.fsm.getCurrentState().getName() == 'waitingToBegin':
            self.exitButtonPushed()
        if task != None:
            task.done
        return

    def setTableDoId(self, doId):
        self.tableDoId = doId
        self.table = self.cr.doId2do[doId]
        self.table.setTimerFunc(self.startButtonPushed)
        self.fsm.enterInitialState()
        self.table.setGameDoId(self.doId)

    def disable(self):
        DistributedNode.DistributedNode.disable(self)
        if self.leaveButton:
            self.leaveButton.destroy()
            self.leavebutton = None
        if self.screenText:
            self.screenText.destroy()
            self.screenText = None
        if self.turnText:
            self.turnText.destroy()
            self.turnText = None
        self.clockNode.stop()
        self.clockNode.hide()
        self.ignore('mouse1')
        self.ignore('stoppedAsleep')
        self.fsm = None
        return

    def delete(self):
        DistributedNode.DistributedNode.delete(self)
        self.table.gameDoId = None
        self.table.game = None
        if self.exitButton:
            self.exitButton.destroy()
        if self.startButton:
            self.startButton.destroy()
        self.clockNode.stop()
        self.clockNode.hide()
        self.table.startButtonPushed = None
        self.ignore('mouse1')
        self.ignore('stoppedAsleep')
        self.fsm = None
        self.table = None
        return

    def getTimer(self):
        self.sendUpdate('requestTimer', [])

    def setTimer(self, timerEnd):
        if self.fsm.getCurrentState() != None and self.fsm.getCurrentState().getName() == 'waitingToBegin' and not self.table.fsm.getCurrentState().getName() == 'observing':
            self.clockNode.stop()
            time = globalClockDelta.networkToLocalTime(timerEnd)
            timeLeft = int(time - globalClock.getRealTime())
            if timeLeft > 0 and timerEnd != 0:
                if timeLeft > 60:
                    timeLeft = 60
                self.clockNode.setPos(1.16, 0, -0.83)
                self.clockNode.countdown(timeLeft, self.startButtonPushed)
                self.clockNode.show()
            else:
                self.clockNode.stop()
                self.clockNode.hide()
        return

    def setTurnTimer(self, turnEnd):
        if self.fsm.getCurrentState() != None and self.fsm.getCurrentState().getName() == 'playing':
            self.clockNode.stop()
            time = globalClockDelta.networkToLocalTime(turnEnd)
            timeLeft = int(time - globalClock.getRealTime())
            if timeLeft > 0:
                self.clockNode.setPos(-.74, 0, -0.2)
                if self.isMyTurn:
                    self.clockNode.countdown(timeLeft, self.doNothing)
                else:
                    self.clockNode.countdown(timeLeft, self.doNothing)
                self.clockNode.show()
        return

    def gameStart(self, playerNum):
        if playerNum != 255:
            self.playerNum = playerNum
            if self.playerNum == 1:
                self.playerColorString = 'white'
            else:
                self.playerColorString = 'black'
            self.playerColor = self.playerColors[playerNum - 1]
            self.moveCameraForGame()
        self.fsm.request('playing')

    def sendTurn(self, playersTurn):
        if self.fsm.getCurrentState().getName() == 'playing':
            if playersTurn == self.playerNum:
                self.isMyTurn = True
            self.enableTurnScreenText(playersTurn)

    def illegalMove(self):
        self.exitButtonPushed()

    def moveCameraForGame(self):
        if self.table.cameraBoardTrack.isPlaying():
            self.table.cameraBoardTrack.finish()
        rotation = 0
        if self.seatPos > 2:
            if self.playerNum == 1:
                rotation = 180
            elif self.playerNum == 2:
                rotation = 0
            for x in self.locatorList:
                x.setH(180)

            self.isRotated = True
        elif self.playerNum == 1:
            rotation = 0
        elif self.playerNum == 2:
            rotation = 180
            for x in self.locatorList:
                x.setH(180)

            self.isRotated = True
        int = LerpHprInterval(self.boardNode, 4.2, Vec3(rotation, self.boardNode.getP(), self.boardNode.getR()), self.boardNode.getHpr())
        int.start()

    def enterWaitingToBegin(self):
        if self.table.fsm.getCurrentState().getName() != 'observing':
            self.enableExitButton()
            self.enableStartButton()

    def exitWaitingToBegin(self):
        if self.exitButton:
            self.exitButton.destroy()
            self.exitButton = None
        if self.startButton:
            self.startButton.destroy()
            self.exitButton = None
        self.clockNode.stop()
        self.clockNode.hide()
        return

    def enterPlaying(self):
        self.inGame = True
        self.enableScreenText()
        if self.table.fsm.getCurrentState().getName() != 'observing':
            self.enableLeaveButton()

    def exitPlaying(self):
        self.inGame = False
        if self.leaveButton:
            self.leaveButton.destroy()
            self.leavebutton = None
        self.playerNum = None
        if self.screenText:
            self.screenText.destroy()
            self.screenText = None
        if self.turnText:
            self.turnText.destroy()
            self.turnText = None
        self.clockNode.stop()
        self.clockNode.hide()
        return

    def enterGameOver(self):
        pass

    def exitGameOver(self):
        pass

    def exitWaitCountdown(self):
        self.__disableCollisions()
        self.ignore('trolleyExitButton')
        self.clockNode.reset()

    def enableExitButton(self):
        self.exitButton = DirectButton(relief=None, text=TTLocalizer.ChineseCheckersGetUpButton, text_fg=(1, 1, 0.65, 1), text_pos=(0, -.23), text_scale=0.8, image=(self.upButton, self.downButton, self.rolloverButton), image_color=(1, 0, 0, 1), image_scale=(20, 1, 11), pos=(0.92, 0, 0.4), scale=0.15, command=lambda self = self: self.exitButtonPushed())
        return

    def enableScreenText(self):
        defaultPos = (-.8, -0.4)
        if self.playerNum == 1:
            message = TTLocalizer.CheckersColorWhite
            color = Vec4(1, 1, 1, 1)
        elif self.playerNum == 2:
            message = TTLocalizer.CheckersColorBlack
            color = Vec4(0, 0, 0, 1)
        else:
            message = TTLocalizer.CheckersObserver
            color = Vec4(0, 0, 0, 1)
            defaultPos = (-.8, -0.4)
        self.screenText = OnscreenText(text=message, pos=defaultPos, scale=0.1, fg=color, align=TextNode.ACenter, mayChange=1)

    def enableStartButton(self):
        self.startButton = DirectButton(relief=None, text=TTLocalizer.ChineseCheckersStartButton, text_fg=(1, 1, 0.65, 1), text_pos=(0, -.23), text_scale=0.6, image=(self.upButton, self.downButton, self.rolloverButton), image_color=(1, 0, 0, 1), image_scale=(20, 1, 11), pos=(0.92, 0, 0.1), scale=0.15, command=lambda self = self: self.startButtonPushed())
        return

    def enableLeaveButton(self):
        self.leaveButton = DirectButton(relief=None, text=TTLocalizer.ChineseCheckersQuitButton, text_fg=(1, 1, 0.65, 1), text_pos=(0, -.13), text_scale=0.5, image=(self.upButton, self.downButton, self.rolloverButton), image_color=(1, 0, 0, 1), image_scale=(20, 1, 11), pos=(0.92, 0, 0.4), scale=0.15, command=lambda self = self: self.exitButtonPushed())
        return

    def enableTurnScreenText(self, player):
        playerOrder = [1,
         4,
         2,
         5,
         3,
         6]
        message1 = TTLocalizer.CheckersIts
        if self.turnText != None:
            self.turnText.destroy()
        if player == self.playerNum:
            message2 = TTLocalizer.ChineseCheckersYourTurn
            color = (0, 0, 0, 1)
        elif player == 1:
            message2 = TTLocalizer.CheckersWhiteTurn
            color = (1, 1, 1, 1)
        elif player == 2:
            message2 = TTLocalizer.CheckersBlackTurn
            color = (0, 0, 0, 1)
        self.turnText = OnscreenText(text=message1 + message2, pos=(-0.8, -0.5), scale=0.092, fg=color, align=TextNode.ACenter, mayChange=1)
        return

    def startButtonPushed(self):
        self.sendUpdate('requestBegin')
        self.startButton.hide()
        self.clockNode.stop()
        self.clockNode.hide()

    def exitButtonPushed(self):
        self.fsm.request('gameOver')
        self.table.fsm.request('off')
        self.clockNode.stop()
        self.clockNode.hide()
        self.table.sendUpdate('requestExit')

    def mouseClick(self):
        messenger.send('wakeup')
        if self.isMyTurn == True and self.inGame == True:
            mpos = base.mouseWatcherNode.getMouse()
            self.pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())
            self.traverser.traverse(render)
            if self.myHandler.getNumEntries() > 0:
                self.myHandler.sortEntries()
                pickedObj = self.myHandler.getEntry(0).getIntoNodePath()
                pickedObj = pickedObj.getNetTag('GamePeiceLocator')
                if pickedObj:
                    self.handleClicked(int(pickedObj))

    def handleClicked(self, index):
        self.sound = Sequence(SoundInterval(self.clickSound))
        if self.moveList == []:
            if index not in self.mySquares and index not in self.myKings:
                return
            self.moveList.append(index)
            type = self.board.squareList[index].getState()
            if type == 3 or type == 4:
                self.moverType = 'king'
            else:
                self.moverType = 'normal'
            self.blinker = Sequence()
            col = self.locatorList[index].getColor()
            self.blinker.append(LerpColorInterval(self.locatorList[index], 0.7, self.tintConstant, col))
            self.blinker.append(LerpColorInterval(self.locatorList[index], 0.7, col, self.tintConstant))
            self.blinker.loop()
            self.sound.start()
        elif index in self.mySquares or index in self.myKings:
            for x in self.moveList:
                self.locatorList[x].setColor(1, 1, 1, 1)
                self.locatorList[x].hide()

            self.blinker.finish()
            self.blinker = Sequence()
            col = self.locatorList[index].getColor()
            self.blinker.append(LerpColorInterval(self.locatorList[index], 0.7, self.tintConstant, col))
            self.blinker.append(LerpColorInterval(self.locatorList[index], 0.7, col, self.tintConstant))
            self.blinker.loop()
            self.sound.start()
            self.locatorList[self.moveList[0]].show()
            self.moveList = []
            self.moveList.append(index)
            type = self.board.squareList[index].getState()
            if type == 3 or type == 4:
                self.moverType = 'king'
            else:
                self.moverType = 'normal'
        else:
            self.currentMove = index
            lastItem = self.board.squareList[self.moveList[len(self.moveList) - 1]]
            thisItem = self.board.squareList[index]
            if self.mustJump == True:
                if lastItem.getNum() == index:
                    self.blinker.finish()
                    self.d_requestMove(self.moveList)
                    self.isMyTurn = False
                    self.moveList = []
                    return
                if self.checkLegalJump(lastItem, thisItem, self.moverType) == True:
                    col = self.locatorList[index].getColor()
                    self.locatorList[index].show()
                    self.sound.start()
                    if self.existsLegalJumpsFrom(index, self.moverType) == False:
                        self.moveList.append(index)
                        self.blinker.finish()
                        self.d_requestMove(self.moveList)
                        self.moveList = []
                        self.isMyTurn = False
                    else:
                        self.moveList.append(index)
                        if self.playerColorString == 'white':
                            x = self.locatorList[index].getChildren()[1]
                            x.show()
                        else:
                            x = self.locatorList[index].getChildren()[2]
                            x.show()
                        if self.moverType == 'king':
                            x.find('**/checker_k*').show()
                        self.locatorList[index].setColor(Vec4(0.5, 0.5, 0.5, 0.5))
            elif self.checkLegalMove(lastItem, thisItem, self.moverType) == True:
                self.moveList.append(index)
                col = self.locatorList[index].getColor()
                self.locatorList[index].show()
                self.sound.start()
                self.blinker.finish()
                self.d_requestMove(self.moveList)
                self.moveList = []
                self.isMyTurn = False

    def existsLegalJumpsFrom(self, index, peice):
        if peice == 'king':
            for x in xrange(4):
                if self.board.squareList[index].getAdjacent()[x] != None and \
                        self.board.squareList[index].getJumps()[x] != None:
                    adj = self.board.squareList[self.board.squareList[index].getAdjacent()[x]]
                    jump = self.board.squareList[self.board.squareList[index].getJumps()[x]]
                    if adj.getState() == 0:
                        pass
                    elif adj.getState() == self.playerNum or adj.getState() == self.playerNum + 2:
                        pass
                    elif jump.getState() == 0:
                        if index not in self.moveList and jump.getNum() not in self.moveList:
                            return True
            return False
        elif peice == 'normal':
            if self.playerNum == 1:
                moveForward = [1, 2]
            elif self.playerNum == 2:
                moveForward = [0, 3]
            for x in moveForward:
                if self.board.squareList[index].getAdjacent()[x] != None and \
                        self.board.squareList[index].getJumps()[x] != None:
                    adj = self.board.squareList[self.board.squareList[index].getAdjacent()[x]]
                    jump = self.board.squareList[self.board.squareList[index].getJumps()[x]]
                    if adj.getState() == 0:
                        pass
                    elif adj.getState() == self.playerNum or adj.getState() == self.playerNum + 2:
                        pass
                    elif jump.getState() == 0:
                        if index not in self.moveList:
                            return True
            return False

    def existsLegalMovesFrom(self, index, peice):
        if peice == 'king':
            for x in self.board.squareList[index].getAdjacent():
                if x != None:
                    if self.board.squareList[x].getState() == 0:
                        return True

            return False
        elif peice == 'normal':
            if self.playerNum == 1:
                moveForward = [1, 2]
            elif self.playerNum == 2:
                moveForward = [0, 3]
            for x in moveForward:
                if self.board.squareList[index].getAdjacent()[x] != None:
                    adj = self.board.squareList[self.board.squareList[index].getAdjacent()[x]]
                    if adj.getState() == 0:
                        return True

            return False
        return

    def checkLegalMove(self, firstSquare, secondSquare, peice):
        if firstSquare.getNum() not in self.mySquares and firstSquare.getNum() not in self.myKings:
            return False
        if self.playerNum == 1:
            moveForward = [1, 2]
        else:
            moveForward = [0, 3]
        if peice == 'king':
            for x in xrange(4):
                if firstSquare.getAdjacent()[x] != None:
                    if self.board.squareList[firstSquare.getAdjacent()[x]].getState() == 0 and secondSquare.getNum() in firstSquare.getAdjacent():
                        return True

            return False
        elif peice == 'normal':
            for x in moveForward:
                if firstSquare.getAdjacent()[x] != None and secondSquare.getNum() in firstSquare.getAdjacent():
                    if self.board.squareList[firstSquare.getAdjacent()[x]].getState() == 0 and firstSquare.getAdjacent().index(secondSquare.getNum()) == x:
                        return True

            return False
        return

    def checkLegalJump(self, firstSquare, secondSquare, peice):
        if firstSquare.getNum() not in self.mySquares and firstSquare.getNum() not in self.myKings and len(self.moveList) == 1:
            return False
        if self.playerNum == 1:
            moveForward = [1, 2]
            opposingPeices = [2, 4]
        else:
            moveForward = [0, 3]
            opposingPeices = [1, 3]
        if peice == 'king':
            if secondSquare.getNum() in firstSquare.getJumps():
                index = firstSquare.getJumps().index(secondSquare.getNum())
                if self.board.squareList[firstSquare.getAdjacent()[index]].getState() in opposingPeices:
                    return True
                else:
                    return False
        elif peice == 'normal':
            if secondSquare.getNum() in firstSquare.getJumps():
                index = firstSquare.getJumps().index(secondSquare.getNum())
                if index in moveForward:
                    if self.board.squareList[firstSquare.getAdjacent()[index]].getState() in opposingPeices:
                        return True
                    else:
                        return False
                else:
                    return False
            else:
                return False

    def d_requestMove(self, moveList):
        self.sendUpdate('requestMove', [moveList])

    def setGameState(self, tableState, moveList):
        if moveList != []:
            if self.board.squareList[moveList[0]].getState() == 1 or self.board.squareList[moveList[0]].getState() == 3:
                playerColor = 'white'
            else:
                playerColor = 'black'
            if self.board.squareList[moveList[0]].getState() <= 2:
                self.animatePeice(tableState, moveList, 'normal', playerColor)
            else:
                self.animatePeice(tableState, moveList, 'king', playerColor)
        else:
            self.updateGameState(tableState)

    def updateGameState(self, squares):
        self.board.setStates(squares)
        self.mySquares = []
        self.myKings = []
        messenger.send('wakeup')
        isObserve = False
        if self.playerNum == None:
            self.playerNum = 1
            self.playerColorString = 'white'
            isObserve = True
        for xx in xrange(32):
            for blah in self.locatorList[xx].getChildren():
                blah.hide()
                if self.locatorList[xx].getChildren().index(blah) != 0:
                    blah1 = blah.find('**/checker_k*')

            owner = self.board.squareList[xx].getState()
            if owner == self.playerNum:
                if self.playerColorString == 'white':
                    x = self.locatorList[xx].getChildren()[1]
                    x.show()
                    x.find('**/checker_k*').hide()
                else:
                    x = self.locatorList[xx].getChildren()[2]
                    x.show()
                    x.find('**/checker_k*').hide()
                self.mySquares.append(xx)
            elif owner == 0:
                self.hideChildren(self.locatorList[xx].getChildren())
            elif owner == self.playerNum + 2:
                if self.playerColorString == 'white':
                    x = self.locatorList[xx].getChildren()[1]
                    x.show()
                    x.find('**/checker_k*').show()
                else:
                    x = self.locatorList[xx].getChildren()[2]
                    x.show()
                    x.find('**/checker_k*').show()
                self.myKings.append(xx)
            elif owner <= 2:
                if self.playerColorString == 'white':
                    x = self.locatorList[xx].getChildren()[2]
                    x.show()
                    x.find('**/checker_k*').hide()
                else:
                    x = self.locatorList[xx].getChildren()[1]
                    x.show()
                    x.find('**/checker_k*').hide()
            elif self.playerColorString == 'white':
                x = self.locatorList[xx].getChildren()[2]
                x.show()
                x.find('**/checker_k*').show()
            else:
                x = self.locatorList[xx].getChildren()[1]
                x.show()
                x.find('**/checker_k*').show()

        if isObserve == True:
            self.playerNum = None
            self.playerColorString = None
            return
        self.mustJump = False
        self.hasNormalMoves = False
        for x in self.myKings:
            if self.existsLegalJumpsFrom(x, 'king') == True:
                self.mustJump = True
                break
            else:
                self.mustJump = False

        if self.mustJump == False:
            for x in self.mySquares:
                if self.existsLegalJumpsFrom(x, 'normal') == True:
                    self.mustJump = True
                    break
                else:
                    self.mustJump = False

        if self.mustJump != True:
            for x in self.mySquares:
                if self.existsLegalMovesFrom(x, 'normal') == True:
                    self.hasNormalMoves = True
                    break
                else:
                    self.hasNormalMoves = False
                if self.hasNormalMoves == False:
                    for x in self.myKings:
                        if self.existsLegalMovesFrom(x, 'king') == True:
                            self.hasNormalMoves = True
                            break
                        else:
                            self.hasNormalMoves = False

        if self.mustJump == False and self.hasNormalMoves == False:
            pass
        return

    def hideChildren(self, nodeList):
        for x in xrange(1, 2):
            nodeList[x].hide()

    def animatePeice(self, tableState, moveList, type, playerColor):
        messenger.send('wakeup')
        if playerColor == 'white':
            gamePeiceForAnimation = loader.loadModel('phase_6/models/golf/regular_checker_piecewhite.bam')
        else:
            gamePeiceForAnimation = loader.loadModel('phase_6/models/golf/regular_checker_pieceblack.bam')
        if type == 'king':
            gamePeiceForAnimation.find('**/checker_k*').show()
        else:
            gamePeiceForAnimation.find('**/checker_k*').hide()
        gamePeiceForAnimation.reparentTo(self.boardNode)
        gamePeiceForAnimation.setPos(self.locatorList[moveList[0]].getPos())
        if self.isRotated == True:
            gamePeiceForAnimation.setH(180)
        for x in self.locatorList[moveList[0]].getChildren():
            x.hide()

        checkersPeiceTrack = Sequence()
        length = len(moveList)
        for x in xrange(length - 1):
            checkersPeiceTrack.append(Parallel(SoundInterval(self.moveSound), ProjectileInterval(gamePeiceForAnimation, endPos=self.locatorList[moveList[x + 1]].getPos(), duration=0.5)))

        checkersPeiceTrack.append(Func(gamePeiceForAnimation.removeNode))
        checkersPeiceTrack.append(Func(self.updateGameState, tableState))
        checkersPeiceTrack.append(Func(self.unAlpha, moveList))
        checkersPeiceTrack.start()

    def announceWin(self, avId):
        self.fsm.request('gameOver')

    def unAlpha(self, moveList):
        for x in moveList:
            self.locatorList[x].setColorOff()

    def doRandomMove(self):
        import random
        move = []
        foundLegal = False
        self.blinker.pause()
        self.numRandomMoves += 1
        while not foundLegal:
            x = random.randint(0, 9)
            for y in self.board.getAdjacent(self.mySquares[x]):
                if y != None and self.board.getState(y) == 0:
                    move.append(self.mySquares[x])
                    move.append(y)
                    foundLegal = True
                    break

        if move == []:
            pass
        playSound = Sequence(SoundInterval(self.knockSound))
        playSound.start()
        self.d_requestMove(move)
        self.moveList = []
        self.isMyTurn = False
        if self.numRandomMoves >= 5:
            self.exitButtonPushed()
        return

    def doNothing(self):
        pass
class DistributedFindFour(DistributedNode.DistributedNode):

    def __init__(self, cr):
        NodePath.__init__(self, 'DistributedFindFour')
        DistributedNode.DistributedNode.__init__(self, cr)
        self.cr = cr
        self.reparentTo(render)
        self.boardNode = loader.loadModel('phase_6/models/golf/findfour_game.bam')
        self.boardNode.reparentTo(self)
        self.board = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0],
                      [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]
        self.exitButton = None
        self.inGame = False
        self.waiting = True
        self.startButton = None
        self.playerNum = None
        self.turnText = None
        self.isMyTurn = False
        self.wantTimer = True
        self.leaveButton = None
        self.screenText = None
        self.turnText = None
        self.exitButton = None
        self.numRandomMoves = 0
        self.blinker = Sequence()
        self.playersTurnBlinker = Sequence()
        self.yourTurnBlinker = Sequence()
        self.winningSequence = Sequence()
        self.moveSequence = Sequence()
        self.moveList = []
        self.mySquares = []
        self.playerSeats = None
        self.moveCol = None
        self.move = None
        self.accept('mouse1', self.mouseClick)
        self.traverser = base.cTrav
        self.pickerNode = CollisionNode('mouseRay')
        self.pickerNP = camera.attachNewNode(self.pickerNode)
        self.pickerNode.setFromCollideMask(BitMask32(4096))
        self.pickerRay = CollisionRay()
        self.pickerNode.addSolid(self.pickerRay)
        self.myHandler = CollisionHandlerQueue()
        self.traverser.addCollider(self.pickerNP, self.myHandler)
        self.buttonModels = loader.loadModel('phase_3.5/models/gui/inventory_gui')
        self.upButton = self.buttonModels.find('**//InventoryButtonUp')
        self.downButton = self.buttonModels.find('**/InventoryButtonDown')
        self.rolloverButton = self.buttonModels.find('**/InventoryButtonRollover')
        self.clockNode = ToontownTimer()
        self.clockNode.setPos(1.16, 0, -0.83)
        self.clockNode.setScale(0.3)
        self.clockNode.hide()
        self.tintConstant = Vec4(0.25, 0.25, 0.25, 0)
        self.ghostConstant = Vec4(0, 0, 0, 0.5)
        self.knockSound = base.loadSfx('phase_5/audio/sfx/GUI_knock_1.ogg')
        self.clickSound = base.loadSfx('phase_3/audio/sfx/GUI_balloon_popup.ogg')
        self.moveSound = base.loadSfx('phase_6/audio/sfx/CC_move.ogg')
        self.accept('stoppedAsleep', self.handleSleep)
        from direct.fsm import ClassicFSM, State
        self.fsm = ClassicFSM.ClassicFSM('ChineseCheckers', [State.State('waitingToBegin', self.enterWaitingToBegin, self.exitWaitingToBegin, ['playing', 'gameOver']), State.State('playing', self.enterPlaying, self.exitPlaying, ['gameOver']), State.State('gameOver', self.enterGameOver, self.exitGameOver, ['waitingToBegin'])], 'waitingToBegin', 'waitingToBegin')
        startLoc = self.boardNode.find('**/locators')
        self.locatorList = list(startLoc.getChildren())
        self.startingPositions = self.locatorList.pop(0)
        self.startingPositions = self.startingPositions.getChildren()
        instancePiece = self.boardNode.find('**/pieces')
        tempList = []
        for x in xrange(7):
            self.startingPositions[x].setTag('StartLocator', '%d' % x)
            collNode = CollisionNode('startpicker%d' % x)
            collNode.setIntoCollideMask(BitMask32(4096))
            tempList.append(self.startingPositions[x].attachNewNode(collNode))
            tempList[x].node().addSolid(CollisionTube(0, 0, 0.23, 0, 0, -.23, 0.2))

        for z in self.startingPositions:
            y = instancePiece.copyTo(z)
            for val in y.getChildren():
                val.hide()

        tempList = []
        for x in xrange(42):
            self.locatorList[x].setTag('GamePeiceLocator', '%d' % x)
            collNode = CollisionNode('startpicker%d' % x)
            collNode.setIntoCollideMask(BitMask32(4096))
            tempList.append(self.locatorList[x].attachNewNode(collNode))
            tempList[x].node().addSolid(CollisionSphere(0, 0, 0, 0.2))

        for z in self.locatorList:
            y = instancePiece.copyTo(z)
            for val in y.getChildren():
                val.hide()

        dummyHide = instancePiece.getParent().attachNewNode('DummyHider')
        instancePiece.reparentTo(dummyHide)
        dummyHide.hide()
        return

    def setName(self, name):
        self.name = name

    def announceGenerate(self):
        DistributedNode.DistributedNode.announceGenerate(self)
        if self.table.fsm.getCurrentState().getName() != 'observing':
            if base.localAvatar.doId in self.table.tableState:
                self.seatPos = self.table.tableState.index(base.localAvatar.doId)
                if self.seatPos <= 2:
                    for x in self.startingPositions:
                        x.setH(0)

                    for x in self.locatorList:
                        x.setH(0)

                else:
                    for x in self.startingPositions:
                        x.setH(180)

                    for x in self.locatorList:
                        x.setH(180)

            self.moveCameraForGame()
        else:
            self.seatPos = self.table.seatBumpForObserve
            if self.seatPos > 2:
                for x in self.startingPositions:
                    x.setH(180)

                for x in self.locatorList:
                    x.setH(180)

            self.moveCameraForGame()

    def handleSleep(self, task = None):
        if self.fsm.getCurrentState().getName() == 'waitingToBegin':
            self.exitButtonPushed()
        if task != None:
            task.done
        return

    def setTableDoId(self, doId):
        self.tableDoId = doId
        self.table = self.cr.doId2do[doId]
        self.table.setTimerFunc(self.startButtonPushed)
        self.fsm.enterInitialState()
        self.table.setGameDoId(self.doId)

    def disable(self):
        DistributedNode.DistributedNode.disable(self)
        if self.leaveButton:
            self.leaveButton.destroy()
            self.leavebutton = None
        if self.screenText:
            self.screenText.destroy()
            self.screenText = None
        if self.turnText:
            self.turnText.destroy()
            self.turnText = None
        self.clockNode.stop()
        self.clockNode.hide()
        self.ignore('mouse1')
        self.ignore('stoppedAsleep')
        self.fsm = None
        taskMgr.remove('playerTurnTask')
        return

    def delete(self):
        DistributedNode.DistributedNode.delete(self)
        self.table.gameDoId = None
        self.table.game = None
        if self.exitButton:
            self.exitButton.destroy()
        if self.startButton:
            self.startButton.destroy()
        self.clockNode.stop()
        self.clockNode.hide()
        self.table.startButtonPushed = None
        self.ignore('mouse1')
        self.ignore('stoppedAsleep')
        self.fsm = None
        self.table = None
        self.winningSequence.finish()
        taskMgr.remove('playerTurnTask')
        return

    def getTimer(self):
        self.sendUpdate('requestTimer', [])

    def setTimer(self, timerEnd):
        if self.fsm.getCurrentState() != None and self.fsm.getCurrentState().getName() == 'waitingToBegin' and not self.table.fsm.getCurrentState().getName() == 'observing':
            self.clockNode.stop()
            time = globalClockDelta.networkToLocalTime(timerEnd)
            timeLeft = int(time - globalClock.getRealTime())
            if timeLeft > 0 and timerEnd != 0:
                if timeLeft > 60:
                    timeLeft = 60
                self.clockNode.setPos(1.16, 0, -0.83)
                self.clockNode.countdown(timeLeft, self.startButtonPushed)
                self.clockNode.show()
            else:
                self.clockNode.stop()
                self.clockNode.hide()
        return

    def setTurnTimer(self, turnEnd):
        if self.fsm.getCurrentState() != None and self.fsm.getCurrentState().getName() == 'playing':
            self.clockNode.stop()
            time = globalClockDelta.networkToLocalTime(turnEnd)
            timeLeft = int(time - globalClock.getRealTime())
            if timeLeft > 0:
                self.clockNode.setPos(0.64, 0, -0.27)
                self.clockNode.countdown(timeLeft, self.doRandomMove)
                self.clockNode.show()
        return

    def gameStart(self, playerNum):
        if playerNum != 255:
            self.playerNum = playerNum
            if self.playerNum == 1:
                self.playerColorString = 'Red'
            else:
                self.playerColorString = 'Yellow'
            self.moveCameraForGame()
        self.fsm.request('playing')

    def sendTurn(self, playersTurn):
        if self.fsm.getCurrentState().getName() == 'playing':
            if playersTurn == self.playerNum:
                self.isMyTurn = True
                taskMgr.add(self.turnTask, 'playerTurnTask')
            self.enableTurnScreenText(playersTurn)

    def illegalMove(self):
        self.exitButtonPushed()

    def moveCameraForGame(self):
        if self.table.cameraBoardTrack.isPlaying():
            self.table.cameraBoardTrack.pause()
        rotation = 0
        if self.seatPos <= 2:
            position = self.table.seats[1].getPos()
            position = position + Vec3(0, -8, 12.8)
            int = LerpPosHprInterval(camera, 2, position, Vec3(0, -38, 0), camera.getPos(), camera.getHpr())
        else:
            position = self.table.seats[4].getPos()
            position = position + Vec3(0, -8, 12.8)
            if camera.getH() < 0:
                int = LerpPosHprInterval(camera, 2, position, Vec3(-180, -20, 0), camera.getPos(), camera.getHpr())
            else:
                int = LerpPosHprInterval(camera, 2, position, Vec3(180, -20, 0), camera.getPos(), camera.getHpr())
        int.start()

    def enterWaitingToBegin(self):
        if self.table.fsm.getCurrentState().getName() != 'observing':
            self.enableExitButton()
            self.enableStartButton()

    def exitWaitingToBegin(self):
        if self.exitButton:
            self.exitButton.destroy()
            self.exitButton = None
        if self.startButton:
            self.startButton.destroy()
            self.exitButton = None
        self.clockNode.stop()
        self.clockNode.hide()
        return

    def enterPlaying(self):
        self.inGame = True
        self.enableScreenText()
        if self.table.fsm.getCurrentState().getName() != 'observing':
            self.enableLeaveButton()

    def exitPlaying(self):
        self.inGame = False
        if self.leaveButton:
            self.leaveButton.destroy()
            self.leavebutton = None
        self.playerNum = None
        if self.screenText:
            self.screenText.destroy()
            self.screenText = None
        if self.turnText:
            self.turnText.destroy()
            self.turnText = None
        self.clockNode.stop()
        self.clockNode.hide()
        return

    def enterGameOver(self):
        pass

    def exitGameOver(self):
        pass

    def exitWaitCountdown(self):
        self.__disableCollisions()
        self.ignore('trolleyExitButton')
        self.clockNode.reset()

    def enableExitButton(self):
        self.exitButton = DirectButton(relief=None, text=TTLocalizer.ChineseCheckersGetUpButton, text_fg=(1, 1, 0.65, 1), text_pos=(0, -.23), text_scale=0.8, image=(self.upButton, self.downButton, self.rolloverButton), image_color=(1, 0, 0, 1), image_scale=(20, 1, 11), pos=(0.92, 0, 0.8), scale=0.15, command=lambda self = self: self.exitButtonPushed())
        return

    def enableScreenText(self):
        defaultPos = (-.7, -0.29)
        if self.playerNum == 1:
            message = 'You are Red'
            color = Vec4(1, 0, 0, 1)
        elif self.playerNum == 2:
            message = 'You are Yellow'
            color = Vec4(1, 1, 0, 1)
        else:
            message = TTLocalizer.CheckersObserver
            color = Vec4(0, 0, 0, 1)
        self.screenText = OnscreenText(text=message, pos=defaultPos, scale=0.1, fg=color, align=TextNode.ACenter, mayChange=1)

    def enableStartButton(self):
        self.startButton = DirectButton(relief=None, text=TTLocalizer.ChineseCheckersStartButton, text_fg=(1, 1, 0.65, 1), text_pos=(0, -.23), text_scale=0.6, image=(self.upButton, self.downButton, self.rolloverButton), image_color=(1, 0, 0, 1), image_scale=(20, 1, 11), pos=(0.92, 0, 0.57), scale=0.15, command=lambda self = self: self.startButtonPushed())
        return

    def enableLeaveButton(self):
        self.leaveButton = DirectButton(relief=None, text=TTLocalizer.ChineseCheckersQuitButton, text_fg=(1, 1, 0.65, 1), text_pos=(0, -.13), text_scale=0.5, image=(self.upButton, self.downButton, self.rolloverButton), image_color=(1, 0, 0, 1), image_scale=(20, 1, 11), pos=(0.92, 0, 0.8), scale=0.15, command=lambda self = self: self.exitButtonPushed())
        return

    def enableTurnScreenText(self, player):
        playerOrder = [1,
         4,
         2,
         5,
         3,
         6]
        message1 = TTLocalizer.CheckersIts
        if self.turnText != None:
            self.turnText.destroy()
        if player == self.playerNum:
            message2 = TTLocalizer.ChineseCheckersYourTurn
            color = (0, 0, 0, 1)
        elif player == 1:
            message2 = "Red's Turn"
            color = (1, 0, 0, 1)
        elif player == 2:
            message2 = "Yellow's Turn"
            color = (1, 1, 0, 1)
        self.turnText = OnscreenText(text=message1 + message2, pos=(-0.7, -0.39), scale=0.092, fg=color, align=TextNode.ACenter, mayChange=1)
        return

    def startButtonPushed(self):
        self.sendUpdate('requestBegin')
        self.startButton.hide()
        self.clockNode.stop()
        self.clockNode.hide()

    def exitButtonPushed(self):
        self.fsm.request('gameOver')
        self.table.fsm.request('off')
        self.clockNode.stop()
        self.clockNode.hide()
        self.table.sendUpdate('requestExit')

    def mouseClick(self):
        messenger.send('wakeup')
        if self.isMyTurn == True and self.inGame == True and not self.moveSequence.isPlaying():
            if self.moveCol != None:
                self.d_requestMove(self.moveCol)
                self.moveCol = None
                self.isMyTurn = False
                taskMgr.remove('playerTurnTask')
        return

    def handleClicked(self, index):
        pass

    def turnTask(self, task):
        if base.mouseWatcherNode.hasMouse() == False:
            return task.cont
        if self.isMyTurn == False:
            return task.cont
        if self.moveSequence.isPlaying():
            return task.cont
        mpos = base.mouseWatcherNode.getMouse()
        self.pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())
        self.traverser.traverse(render)
        if self.myHandler.getNumEntries() > 0:
            self.myHandler.sortEntries()
            pickedObj = self.myHandler.getEntry(0).getIntoNodePath()
            pickedObj = pickedObj.getNetTag('StartLocator')
            if pickedObj:
                colVal = int(pickedObj)
                if colVal == self.moveCol:
                    return task.cont
                if self.board[0][colVal] == 0:
                    if self.moveCol != None:
                        for x in self.startingPositions[self.moveCol].getChild(1).getChildren():
                            x.hide()

                    self.moveCol = colVal
                    if self.playerNum == 1:
                        self.startingPositions[self.moveCol].getChild(1).getChild(2).show()
                    elif self.playerNum == 2:
                        self.startingPositions[self.moveCol].getChild(1).getChild(3).show()
        return task.cont

    def d_requestMove(self, moveCol):
        self.sendUpdate('requestMove', [moveCol])

    def setGameState(self, tableState, moveCol, movePos, turn):
        messenger.send('wakeup')
        if self.table.fsm.getCurrentState().getName() == 'observing':
            isBlank = True
            for x in xrange(7):
                if self.board[5][x] != 0:
                    isBlank = False
                    break

            gameBlank = True
            for x in xrange(7):
                if tableState[5][x] != 0:
                    gameBlank = False
                    break

            if isBlank == True and gameBlank == False:
                for x in xrange(6):
                    for y in xrange(7):
                        self.board[x][y] = tableState[x][y]

                self.updateGameState()
                return
        if moveCol == 0 and movePos == 0 and turn == 0:
            for x in xrange(6):
                for y in xrange(7):
                    self.board[x][y] = tableState[x][y]

            self.updateGameState()
        else:
            self.animatePeice(tableState, moveCol, movePos, turn)
        didIWin = self.checkForWin()
        if didIWin != None:
            self.sendUpdate('requestWin', [didIWin])
        return

    def updateGameState(self):
        for x in xrange(6):
            for y in xrange(7):
                for z in self.locatorList[x * 7 + y].getChild(1).getChildren():
                    z.hide()

        for x in xrange(6):
            for y in xrange(7):
                state = self.board[x][y]
                if state == 1:
                    self.locatorList[x * 7 + y].getChild(1).getChild(0).show()
                elif state == 2:
                    self.locatorList[x * 7 + y].getChild(1).getChild(1).show()

    def checkForWin(self):
        for x in xrange(6):
            for y in xrange(7):
                if self.board[x][y] == self.playerNum:
                    if self.checkHorizontal(x, y, self.playerNum) == True:
                        return [x, y]
                    elif self.checkVertical(x, y, self.playerNum) == True:
                        return [x, y]
                    elif self.checkDiagonal(x, y, self.playerNum) == True:
                        return [x, y]

        return None

    def announceWinnerPosition(self, x, y, winDirection, playerNum):
        self.isMyturn = False
        if self.turnText:
            self.turnText.hide()
        self.clockNode.stop()
        self.clockNode.hide()
        if winDirection == 0:
            blinkList = self.findHorizontal(x, y, playerNum)
        elif winDirection == 1:
            blinkList = self.findVertical(x, y, playerNum)
        elif winDirection == 2:
            blinkList = self.findDiagonal(x, y, playerNum)
        if blinkList != []:
            print blinkList
            val0 = x * 7 + y
            x = blinkList[0][0]
            y = blinkList[0][1]
            val1 = x * 7 + y
            x = blinkList[1][0]
            y = blinkList[1][1]
            val2 = x * 7 + y
            x = blinkList[2][0]
            y = blinkList[2][1]
            val3 = x * 7 + y
            self.winningSequence = Sequence()
            downBlinkerParallel = Parallel(LerpColorInterval(self.locatorList[val0], 0.3, Vec4(0.5, 0.5, 0.5, 0.5), Vec4(1, 1, 1, 1)), LerpColorInterval(self.locatorList[val1], 0.3, Vec4(0.5, 0.5, 0.5, 0.5), Vec4(1, 1, 1, 1)), LerpColorInterval(self.locatorList[val2], 0.3, Vec4(0.5, 0.5, 0.5, 0.5), Vec4(1, 1, 1, 1)), LerpColorInterval(self.locatorList[val3], 0.3, Vec4(0.5, 0.5, 0.5, 0.5), Vec4(1, 1, 1, 1)))
            upBlinkerParallel = Parallel(LerpColorInterval(self.locatorList[val0], 0.3, Vec4(1, 1, 1, 1), Vec4(0.5, 0.5, 0.5, 0.5)), LerpColorInterval(self.locatorList[val1], 0.3, Vec4(1, 1, 1, 1), Vec4(0.5, 0.5, 0.5, 0.5)), LerpColorInterval(self.locatorList[val2], 0.3, Vec4(1, 1, 1, 1), Vec4(0.5, 0.5, 0.5, 0.5)), LerpColorInterval(self.locatorList[val3], 0.3, Vec4(1, 1, 1, 1), Vec4(0.5, 0.5, 0.5, 0.5)))
            self.winningSequence.append(downBlinkerParallel)
            self.winningSequence.append(upBlinkerParallel)
            self.winningSequence.loop()

    def tie(self):
        self.tieSequence = Sequence(autoFinish=1)
        self.clockNode.stop()
        self.clockNode.hide()
        self.isMyTurn = False
        self.moveSequence.finish()
        if self.turnText:
            self.turnText.hide()
        for x in xrange(41):
            self.tieSequence.append(Parallel(LerpColorInterval(self.locatorList[x], 0.15, Vec4(0.5, 0.5, 0.5, 0.5), Vec4(1, 1, 1, 1)), LerpColorInterval(self.locatorList[x], 0.15, Vec4(1, 1, 1, 1), Vec4(0.5, 0.5, 0.5, 0.5))))

        whisper = WhisperPopup('This Find Four game has resulted in a Tie!', OTPGlobals.getInterfaceFont(), WhisperPopup.WTNormal)
        whisper.manage(base.marginManager)
        self.tieSequence.start()

    def hideChildren(self, nodeList):
        pass

    def animatePeice(self, tableState, moveCol, movePos, turn):
        messenger.send('wakeup')
        for x in xrange(6):
            for y in xrange(7):
                self.board[x][y] = tableState[x][y]

        pos = self.startingPositions[moveCol].getPos()
        if turn == 0:
            peice = self.startingPositions[moveCol].getChild(1).getChildren()[2]
            peice.show()
        elif turn == 1:
            peice = self.startingPositions[moveCol].getChild(1).getChildren()[3]
            peice.show()
        self.moveSequence = Sequence()
        startPos = self.startingPositions[moveCol].getPos()
        arrayLoc = movePos * 7 + moveCol
        self.moveSequence.append(LerpPosInterval(self.startingPositions[moveCol], 1.5, self.locatorList[arrayLoc].getPos(self), startPos))
        self.moveSequence.append(Func(peice.hide))
        self.moveSequence.append(Func(self.startingPositions[moveCol].setPos, startPos))
        self.moveSequence.append(Func(self.updateGameState))
        self.moveSequence.start()

    def announceWin(self, avId):
        self.fsm.request('gameOver')

    def doRandomMove(self):
        if self.isMyTurn:
            if self.moveCol != None:
                self.d_requestMove(self.moveCol)
                self.moveCol = None
                self.isMyTurn = False
                taskMgr.remove('playerTurnTask')
            else:
                hasfound = False
                while hasfound == False:
                    x = random.randint(0, 6)
                    if self.board[0][x] == 0:
                        self.d_requestMove(x)
                        self.moveCol = None
                        self.isMyTurn = False
                        taskMgr.remove('playerTurnTask')
                        hasfound = True

        return

    def doNothing(self):
        pass

    def checkHorizontal(self, rVal, cVal, playerNum):
        if cVal == 3:
            for x in xrange(1, 4):
                if self.board[rVal][cVal - x] != playerNum:
                    break
                if self.board[rVal][cVal - x] == playerNum and x == 3:
                    return True

            for x in xrange(1, 4):
                if self.board[rVal][cVal + x] != playerNum:
                    break
                if self.board[rVal][cVal + x] == playerNum and x == 3:
                    return True

            return False
        elif cVal == 2:
            for x in xrange(1, 4):
                if self.board[rVal][cVal + x] != playerNum:
                    break
                if self.board[rVal][cVal + x] == playerNum and x == 3:
                    return True

            return False
        elif cVal == 4:
            for x in xrange(1, 4):
                if self.board[rVal][cVal - x] != playerNum:
                    break
                if self.board[rVal][cVal - x] == playerNum and x == 3:
                    return True

            return False
        else:
            return False

    def checkVertical(self, rVal, cVal, playerNum):
        if rVal == 2:
            for x in xrange(1, 4):
                if self.board[rVal + x][cVal] != playerNum:
                    break
                if self.board[rVal + x][cVal] == playerNum and x == 3:
                    return True

            return False
        elif rVal == 3:
            for x in xrange(1, 4):
                if self.board[rVal - x][cVal] != playerNum:
                    break
                if self.board[rVal - x][cVal] == playerNum and x == 3:
                    return True

            return False
        else:
            return False

    def checkDiagonal(self, rVal, cVal, playerNum):
        if cVal <= 2:
            if rVal == 2:
                for x in xrange(1, 4):
                    if self.board[rVal + x][cVal + x] != playerNum:
                        break
                    if self.board[rVal + x][cVal + x] == playerNum and x == 3:
                        return True

                return False
            elif rVal == 3:
                for x in xrange(1, 4):
                    if self.board[rVal - x][cVal + x] != playerNum:
                        break
                    if self.board[rVal - x][cVal + x] == playerNum and x == 3:
                        return True

                return False
        elif cVal >= 4:
            if rVal == 2:
                for x in xrange(1, 4):
                    if self.board[rVal + x][cVal - x] != playerNum:
                        break
                    if self.board[rVal + x][cVal - x] == playerNum and x == 3:
                        return True

                return False
            elif rVal == 3:
                for x in xrange(1, 4):
                    if self.board[rVal - x][cVal - x] != playerNum:
                        break
                    if self.board[rVal - x][cVal - x] == playerNum and x == 3:
                        return True

                return False
        elif rVal == 3 or rVal == 4 or rVal == 5:
            for x in xrange(1, 4):
                if self.board[rVal - x][cVal - x] != playerNum:
                    break
                if self.board[rVal - x][cVal - x] == playerNum and x == 3:
                    return True

            for x in xrange(1, 4):
                if self.board[rVal - x][cVal - x] != playerNum:
                    break
                if self.board[rVal - x][cVal - x] == playerNum and x == 3:
                    return True

            return False
        elif rVal == 0 or rVal == 1 or rVal == 2:
            for x in xrange(1, 4):
                if self.board[rVal + x][cVal - x] != playerNum:
                    break
                if self.board[rVal + x][cVal - x] == playerNum and x == 3:
                    return True

            for x in xrange(1, 4):
                if self.board[rVal + x][cVal + x] != playerNum:
                    break
                if self.board[rVal + x][cVal + x] == playerNum and x == 3:
                    return True

            return False
        return False

    def findHorizontal(self, rVal, cVal, playerNum):
        if cVal == 3:
            retList = []
            for x in xrange(1, 4):
                retList.append([rVal, cVal - x])
                if self.board[rVal][cVal - x] != playerNum:
                    retList = []
                    break
                if self.board[rVal][cVal - x] == playerNum and x == 3:
                    return retList

            for x in xrange(1, 4):
                retList.append([rVal, cVal + x])
                if self.board[rVal][cVal + x] != playerNum:
                    retList = []
                    break
                if self.board[rVal][cVal + x] == playerNum and x == 3:
                    return retList

            return []
        elif cVal == 2:
            retList = []
            for x in xrange(1, 4):
                retList.append([rVal, cVal + x])
                if self.board[rVal][cVal + x] != playerNum:
                    retList = []
                    break
                if self.board[rVal][cVal + x] == playerNum and x == 3:
                    return retList

            return []
        elif cVal == 4:
            retList = []
            for x in xrange(1, 4):
                retList.append([rVal, cVal - x])
                if self.board[rVal][cVal - x] != playerNum:
                    retList = []
                    break
                if self.board[rVal][cVal - x] == playerNum and x == 3:
                    return retList

            return []
        else:
            return []

    def findVertical(self, rVal, cVal, playerNum):
        if rVal == 2:
            retList = []
            for x in xrange(1, 4):
                retList.append([rVal + x, cVal])
                if self.board[rVal + x][cVal] != playerNum:
                    retList = []
                    break
                if self.board[rVal + x][cVal] == playerNum and x == 3:
                    return retList

            return []
        elif rVal == 3:
            retList = []
            for x in xrange(1, 4):
                retList.append([rVal - x, cVal])
                if self.board[rVal - x][cVal] != playerNum:
                    retList = []
                    break
                if self.board[rVal - x][cVal] == playerNum and x == 3:
                    return retList

            return []
        else:
            return []

    def findDiagonal(self, rVal, cVal, playerNum):
        retList = []
        if cVal <= 2:
            if rVal == 2:
                for x in xrange(1, 4):
                    retList.append([rVal + x, cVal + x])
                    if self.board[rVal + x][cVal + x] != playerNum:
                        retList = []
                        break
                    if self.board[rVal + x][cVal + x] == playerNum and x == 3:
                        return retList

                return []
            elif rVal == 3:
                for x in xrange(1, 4):
                    retList.append([rVal - x, cVal + x])
                    if self.board[rVal - x][cVal + x] != playerNum:
                        retList = []
                        break
                    if self.board[rVal - x][cVal + x] == playerNum and x == 3:
                        return retList

                return []
        elif cVal >= 4:
            if rVal == 2:
                for x in xrange(1, 4):
                    retList.append([rVal + x, cVal - x])
                    if self.board[rVal + x][cVal - x] != playerNum:
                        retList = []
                        break
                    if self.board[rVal + x][cVal - x] == playerNum and x == 3:
                        return retList

                return []
            elif rVal == 3:
                for x in xrange(1, 4):
                    retList.append([rVal - x, cVal - x])
                    if self.board[rVal - x][cVal - x] != playerNum:
                        retList = []
                        break
                    if self.board[rVal - x][cVal - x] == playerNum and x == 3:
                        return retList

                return []
        elif rVal == 3 or rVal == 4 or rVal == 5:
            for x in xrange(1, 4):
                retList.append([rVal - x, cVal - x])
                if self.board[rVal - x][cVal - x] != playerNum:
                    retList = []
                    break
                if self.board[rVal - x][cVal - x] == playerNum and x == 3:
                    return retList

            for x in xrange(1, 4):
                retList.append([rVal + x, cVal - x])
                if self.board[rVal + x][cVal - x] != playerNum:
                    retList = []
                    break
                if self.board[rVal + x][cVal - x] == playerNum and x == 3:
                    return retList

            return []
        elif rVal == 0 or rVal == 1 or rVal == 2:
            for x in xrange(1, 4):
                retList.append([rVal + x, cVal - x])
                if self.board[rVal + x][cVal - x] != playerNum:
                    retList = []
                    break
                if self.board[rVal + x][cVal - x] == playerNum and x == 3:
                    return retList

            for x in xrange(1, 4):
                retList.append([rVal + x, cVal + x])
                if self.board[rVal + x][cVal + x] != playerNum:
                    retList = []
                    break
                if self.board[rVal + x][cVal + x] == playerNum and x == 3:
                    return retList

            return []
        return []
예제 #4
0
class DistributedCheckers(DistributedNode.DistributedNode):
    def __init__(self, cr):
        NodePath.__init__(self, 'DistributedCheckers')
        DistributedNode.DistributedNode.__init__(self, cr)
        self.cr = cr
        self.reparentTo(render)
        self.boardNode = loader.loadModel(
            'phase_6/models/golf/regular_checker_game.bam')
        self.boardNode.reparentTo(self)
        self.board = CheckersBoard()
        self.exitButton = None
        self.inGame = False
        self.waiting = True
        self.startButton = None
        self.playerNum = None
        self.turnText = None
        self.isMyTurn = False
        self.wantTimer = True
        self.leaveButton = None
        self.screenText = None
        self.turnText = None
        self.exitButton = None
        self.numRandomMoves = 0
        self.blinker = Sequence()
        self.moveList = []
        self.mySquares = []
        self.myKings = []
        self.isRotated = False
        self.accept('mouse1', self.mouseClick)
        self.traverser = base.cTrav
        self.pickerNode = CollisionNode('mouseRay')
        self.pickerNP = camera.attachNewNode(self.pickerNode)
        self.pickerNode.setFromCollideMask(ToontownGlobals.WallBitmask)
        self.pickerRay = CollisionRay()
        self.pickerNode.addSolid(self.pickerRay)
        self.myHandler = CollisionHandlerQueue()
        self.traverser.addCollider(self.pickerNP, self.myHandler)
        self.buttonModels = loader.loadModel(
            'phase_3.5/models/gui/inventory_gui')
        self.upButton = self.buttonModels.find('**//InventoryButtonUp')
        self.downButton = self.buttonModels.find('**/InventoryButtonDown')
        self.rolloverButton = self.buttonModels.find(
            '**/InventoryButtonRollover')
        self.clockNode = ToontownTimer()
        self.clockNode.setPos(1.16, 0, -0.83)
        self.clockNode.setScale(0.3)
        self.clockNode.hide()
        self.playerColors = [Vec4(0, 0, 1, 1), Vec4(0, 1, 0, 1)]
        self.tintConstant = Vec4(0.25, 0.25, 0.25, 0.5)
        self.ghostConstant = Vec4(0, 0, 0, 0.8)
        self.startingPositions = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
                                  [
                                      20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
                                      30, 31
                                  ]]
        self.knockSound = base.loadSfx('phase_5/audio/sfx/GUI_knock_1.ogg')
        self.clickSound = base.loadSfx(
            'phase_3/audio/sfx/GUI_balloon_popup.ogg')
        self.moveSound = base.loadSfx('phase_6/audio/sfx/CC_move.ogg')
        self.accept('stoppedAsleep', self.handleSleep)
        self.fsm = ClassicFSM.ClassicFSM('ChineseCheckers', [
            State.State('waitingToBegin', self.enterWaitingToBegin,
                        self.exitWaitingToBegin, ['playing', 'gameOver']),
            State.State('playing', self.enterPlaying, self.exitPlaying,
                        ['gameOver']),
            State.State('gameOver', self.enterGameOver, self.exitGameOver,
                        ['waitingToBegin'])
        ], 'waitingToBegin', 'waitingToBegin')
        x = self.boardNode.find('**/locator*')
        self.locatorList = x.getChildren()
        tempList = []
        for x in xrange(0, 32):
            self.locatorList[x].setTag('GamePeiceLocator', '%d' % x)
            tempList.append(self.locatorList[x].attachNewNode(
                CollisionNode('picker%d' % x)))
            tempList[x].node().addSolid(CollisionSphere(0, 0, 0, 0.39))

        for z in self.locatorList:
            y = loader.loadModel(
                'phase_6/models/golf/regular_checker_piecewhite.bam')
            y.find('**/checker_k*').hide()
            zz = loader.loadModel(
                'phase_6/models/golf/regular_checker_pieceblack.bam')
            zz.find('**/checker_k*').hide()
            y.reparentTo(z)
            y.hide()
            zz.reparentTo(z)
            zz.hide()

        return

    def setName(self, name):
        self.name = name

    def announceGenerate(self):
        DistributedNode.DistributedNode.announceGenerate(self)
        if self.table.fsm.getCurrentState().getName() != 'observing':
            if base.localAvatar.doId in self.table.tableState:
                self.seatPos = self.table.tableState.index(
                    base.localAvatar.doId)

    def handleSleep(self, task=None):
        if self.fsm.getCurrentState().getName() == 'waitingToBegin':
            self.exitButtonPushed()
        if task != None:
            task.done
        return

    def setTableDoId(self, doId):
        self.tableDoId = doId
        self.table = self.cr.doId2do[doId]
        self.table.setTimerFunc(self.startButtonPushed)
        self.fsm.enterInitialState()
        self.table.setGameDoId(self.doId)

    def disable(self):
        DistributedNode.DistributedNode.disable(self)
        if self.leaveButton:
            self.leaveButton.destroy()
            self.leavebutton = None
        if self.screenText:
            self.screenText.destroy()
            self.screenText = None
        if self.turnText:
            self.turnText.destroy()
            self.turnText = None
        self.clockNode.stop()
        self.clockNode.hide()
        self.ignore('mouse1')
        self.ignore('stoppedAsleep')
        self.fsm = None
        return

    def delete(self):
        DistributedNode.DistributedNode.delete(self)
        self.table.gameDoId = None
        self.table.game = None
        if self.exitButton:
            self.exitButton.destroy()
        if self.startButton:
            self.startButton.destroy()
        self.clockNode.stop()
        self.clockNode.hide()
        self.table.startButtonPushed = None
        self.ignore('mouse1')
        self.ignore('stoppedAsleep')
        self.fsm = None
        self.table = None
        return

    def getTimer(self):
        self.sendUpdate('requestTimer', [])

    def setTimer(self, timerEnd):
        if self.fsm.getCurrentState() != None and self.fsm.getCurrentState(
        ).getName() == 'waitingToBegin' and not self.table.fsm.getCurrentState(
        ).getName() == 'observing':
            self.clockNode.stop()
            time = globalClockDelta.networkToLocalTime(timerEnd)
            timeLeft = int(time - globalClock.getRealTime())
            if timeLeft > 0 and timerEnd != 0:
                if timeLeft > 60:
                    timeLeft = 60
                self.clockNode.setPos(1.16, 0, -0.83)
                self.clockNode.countdown(timeLeft, self.startButtonPushed)
                self.clockNode.show()
            else:
                self.clockNode.stop()
                self.clockNode.hide()
        return

    def setTurnTimer(self, turnEnd):
        if self.fsm.getCurrentState() != None and self.fsm.getCurrentState(
        ).getName() == 'playing':
            self.clockNode.stop()
            time = globalClockDelta.networkToLocalTime(turnEnd)
            timeLeft = int(time - globalClock.getRealTime())
            if timeLeft > 0:
                self.clockNode.setPos(-.74, 0, -0.2)
                if self.isMyTurn:
                    self.clockNode.countdown(timeLeft, self.doNothing)
                else:
                    self.clockNode.countdown(timeLeft, self.doNothing)
                self.clockNode.show()
        return

    def gameStart(self, playerNum):
        if playerNum != 255:
            self.playerNum = playerNum
            if self.playerNum == 1:
                self.playerColorString = 'white'
            else:
                self.playerColorString = 'black'
            self.playerColor = self.playerColors[playerNum - 1]
            self.moveCameraForGame()
        self.fsm.request('playing')

    def sendTurn(self, playersTurn):
        if self.fsm.getCurrentState().getName() == 'playing':
            if playersTurn == self.playerNum:
                self.isMyTurn = True
            self.enableTurnScreenText(playersTurn)

    def illegalMove(self):
        self.exitButtonPushed()

    def moveCameraForGame(self):
        if self.table.cameraBoardTrack.isPlaying():
            self.table.cameraBoardTrack.finish()
        rotation = 0
        if self.seatPos > 2:
            if self.playerNum == 1:
                rotation = 180
            elif self.playerNum == 2:
                rotation = 0
            for x in self.locatorList:
                x.setH(180)

            self.isRotated = True
        elif self.playerNum == 1:
            rotation = 0
        elif self.playerNum == 2:
            rotation = 180
            for x in self.locatorList:
                x.setH(180)

            self.isRotated = True
        int = LerpHprInterval(
            self.boardNode, 4.2,
            Vec3(rotation, self.boardNode.getP(), self.boardNode.getR()),
            self.boardNode.getHpr())
        int.start()

    def enterWaitingToBegin(self):
        if self.table.fsm.getCurrentState().getName() != 'observing':
            self.enableExitButton()
            self.enableStartButton()

    def exitWaitingToBegin(self):
        if self.exitButton:
            self.exitButton.destroy()
            self.exitButton = None
        if self.startButton:
            self.startButton.destroy()
            self.exitButton = None
        self.clockNode.stop()
        self.clockNode.hide()
        return

    def enterPlaying(self):
        self.inGame = True
        self.enableScreenText()
        if self.table.fsm.getCurrentState().getName() != 'observing':
            self.enableLeaveButton()

    def exitPlaying(self):
        self.inGame = False
        if self.leaveButton:
            self.leaveButton.destroy()
            self.leavebutton = None
        self.playerNum = None
        if self.screenText:
            self.screenText.destroy()
            self.screenText = None
        if self.turnText:
            self.turnText.destroy()
            self.turnText = None
        self.clockNode.stop()
        self.clockNode.hide()
        return

    def enterGameOver(self):
        pass

    def exitGameOver(self):
        pass

    def exitWaitCountdown(self):
        self.__disableCollisions()
        self.ignore('trolleyExitButton')
        self.clockNode.reset()

    def enableExitButton(self):
        self.exitButton = DirectButton(
            relief=None,
            text=TTLocalizer.ChineseCheckersGetUpButton,
            text_fg=(1, 1, 0.65, 1),
            text_pos=(0, -.23),
            text_scale=0.8,
            image=(self.upButton, self.downButton, self.rolloverButton),
            image_color=(1, 0, 0, 1),
            image_scale=(20, 1, 11),
            pos=(0.92, 0, 0.4),
            scale=0.15,
            command=lambda self=self: self.exitButtonPushed())
        return

    def enableScreenText(self):
        defaultPos = (-.8, -0.4)
        if self.playerNum == 1:
            message = TTLocalizer.CheckersColorWhite
            color = Vec4(1, 1, 1, 1)
        elif self.playerNum == 2:
            message = TTLocalizer.CheckersColorBlack
            color = Vec4(0, 0, 0, 1)
        else:
            message = TTLocalizer.CheckersObserver
            color = Vec4(0, 0, 0, 1)
            defaultPos = (-.8, -0.4)
        self.screenText = OnscreenText(text=message,
                                       pos=defaultPos,
                                       scale=0.1,
                                       fg=color,
                                       align=TextNode.ACenter,
                                       mayChange=1)

    def enableStartButton(self):
        self.startButton = DirectButton(
            relief=None,
            text=TTLocalizer.ChineseCheckersStartButton,
            text_fg=(1, 1, 0.65, 1),
            text_pos=(0, -.23),
            text_scale=0.6,
            image=(self.upButton, self.downButton, self.rolloverButton),
            image_color=(1, 0, 0, 1),
            image_scale=(20, 1, 11),
            pos=(0.92, 0, 0.1),
            scale=0.15,
            command=lambda self=self: self.startButtonPushed())
        return

    def enableLeaveButton(self):
        self.leaveButton = DirectButton(
            relief=None,
            text=TTLocalizer.ChineseCheckersQuitButton,
            text_fg=(1, 1, 0.65, 1),
            text_pos=(0, -.13),
            text_scale=0.5,
            image=(self.upButton, self.downButton, self.rolloverButton),
            image_color=(1, 0, 0, 1),
            image_scale=(20, 1, 11),
            pos=(0.92, 0, 0.4),
            scale=0.15,
            command=lambda self=self: self.exitButtonPushed())
        return

    def enableTurnScreenText(self, player):
        playerOrder = [1, 4, 2, 5, 3, 6]
        message1 = TTLocalizer.CheckersIts
        if self.turnText != None:
            self.turnText.destroy()
        if player == self.playerNum:
            message2 = TTLocalizer.ChineseCheckersYourTurn
            color = (0, 0, 0, 1)
        elif player == 1:
            message2 = TTLocalizer.CheckersWhiteTurn
            color = (1, 1, 1, 1)
        elif player == 2:
            message2 = TTLocalizer.CheckersBlackTurn
            color = (0, 0, 0, 1)
        self.turnText = OnscreenText(text=message1 + message2,
                                     pos=(-0.8, -0.5),
                                     scale=0.092,
                                     fg=color,
                                     align=TextNode.ACenter,
                                     mayChange=1)
        return

    def startButtonPushed(self):
        self.sendUpdate('requestBegin')
        self.startButton.hide()
        self.clockNode.stop()
        self.clockNode.hide()

    def exitButtonPushed(self):
        self.fsm.request('gameOver')
        self.table.fsm.request('off')
        self.clockNode.stop()
        self.clockNode.hide()
        self.table.sendUpdate('requestExit')

    def mouseClick(self):
        messenger.send('wakeup')
        if self.isMyTurn == True and self.inGame == True:
            mpos = base.mouseWatcherNode.getMouse()
            self.pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())
            self.traverser.traverse(render)
            if self.myHandler.getNumEntries() > 0:
                self.myHandler.sortEntries()
                pickedObj = self.myHandler.getEntry(0).getIntoNodePath()
                pickedObj = pickedObj.getNetTag('GamePeiceLocator')
                if pickedObj:
                    self.handleClicked(int(pickedObj))

    def handleClicked(self, index):
        self.sound = Sequence(SoundInterval(self.clickSound))
        if self.moveList == []:
            if index not in self.mySquares and index not in self.myKings:
                return
            self.moveList.append(index)
            type = self.board.squareList[index].getState()
            if type == 3 or type == 4:
                self.moverType = 'king'
            else:
                self.moverType = 'normal'
            self.blinker = Sequence()
            col = self.locatorList[index].getColor()
            self.blinker.append(
                LerpColorInterval(self.locatorList[index], 0.7,
                                  self.tintConstant, col))
            self.blinker.append(
                LerpColorInterval(self.locatorList[index], 0.7, col,
                                  self.tintConstant))
            self.blinker.loop()
            self.sound.start()
        elif index in self.mySquares or index in self.myKings:
            for x in self.moveList:
                self.locatorList[x].setColor(1, 1, 1, 1)
                self.locatorList[x].hide()

            self.blinker.finish()
            self.blinker = Sequence()
            col = self.locatorList[index].getColor()
            self.blinker.append(
                LerpColorInterval(self.locatorList[index], 0.7,
                                  self.tintConstant, col))
            self.blinker.append(
                LerpColorInterval(self.locatorList[index], 0.7, col,
                                  self.tintConstant))
            self.blinker.loop()
            self.sound.start()
            self.locatorList[self.moveList[0]].show()
            self.moveList = []
            self.moveList.append(index)
            type = self.board.squareList[index].getState()
            if type == 3 or type == 4:
                self.moverType = 'king'
            else:
                self.moverType = 'normal'
        else:
            self.currentMove = index
            lastItem = self.board.squareList[self.moveList[len(self.moveList) -
                                                           1]]
            thisItem = self.board.squareList[index]
            if self.mustJump == True:
                if lastItem.getNum() == index:
                    self.blinker.finish()
                    self.d_requestMove(self.moveList)
                    self.isMyTurn = False
                    self.moveList = []
                    return
                if self.checkLegalJump(lastItem, thisItem,
                                       self.moverType) == True:
                    col = self.locatorList[index].getColor()
                    self.locatorList[index].show()
                    self.sound.start()
                    if self.existsLegalJumpsFrom(index,
                                                 self.moverType) == False:
                        self.moveList.append(index)
                        self.blinker.finish()
                        self.d_requestMove(self.moveList)
                        self.moveList = []
                        self.isMyTurn = False
                    else:
                        self.moveList.append(index)
                        if self.playerColorString == 'white':
                            x = self.locatorList[index].getChildren()[1]
                            x.show()
                        else:
                            x = self.locatorList[index].getChildren()[2]
                            x.show()
                        if self.moverType == 'king':
                            x.find('**/checker_k*').show()
                        self.locatorList[index].setColor(
                            Vec4(0.5, 0.5, 0.5, 0.5))
            elif self.checkLegalMove(lastItem, thisItem,
                                     self.moverType) == True:
                self.moveList.append(index)
                col = self.locatorList[index].getColor()
                self.locatorList[index].show()
                self.sound.start()
                self.blinker.finish()
                self.d_requestMove(self.moveList)
                self.moveList = []
                self.isMyTurn = False

    def existsLegalJumpsFrom(self, index, peice):
        if peice == 'king':
            for x in xrange(4):
                if self.board.squareList[index].getAdjacent()[x] != None and \
                        self.board.squareList[index].getJumps()[x] != None:
                    adj = self.board.squareList[
                        self.board.squareList[index].getAdjacent()[x]]
                    jump = self.board.squareList[
                        self.board.squareList[index].getJumps()[x]]
                    if adj.getState() == 0:
                        pass
                    elif adj.getState() == self.playerNum or adj.getState(
                    ) == self.playerNum + 2:
                        pass
                    elif jump.getState() == 0:
                        if index not in self.moveList and jump.getNum(
                        ) not in self.moveList:
                            return True
            return False
        elif peice == 'normal':
            if self.playerNum == 1:
                moveForward = [1, 2]
            elif self.playerNum == 2:
                moveForward = [0, 3]
            for x in moveForward:
                if self.board.squareList[index].getAdjacent()[x] != None and \
                        self.board.squareList[index].getJumps()[x] != None:
                    adj = self.board.squareList[
                        self.board.squareList[index].getAdjacent()[x]]
                    jump = self.board.squareList[
                        self.board.squareList[index].getJumps()[x]]
                    if adj.getState() == 0:
                        pass
                    elif adj.getState() == self.playerNum or adj.getState(
                    ) == self.playerNum + 2:
                        pass
                    elif jump.getState() == 0:
                        if index not in self.moveList:
                            return True
            return False

    def existsLegalMovesFrom(self, index, peice):
        if peice == 'king':
            for x in self.board.squareList[index].getAdjacent():
                if x != None:
                    if self.board.squareList[x].getState() == 0:
                        return True

            return False
        elif peice == 'normal':
            if self.playerNum == 1:
                moveForward = [1, 2]
            elif self.playerNum == 2:
                moveForward = [0, 3]
            for x in moveForward:
                if self.board.squareList[index].getAdjacent()[x] != None:
                    adj = self.board.squareList[
                        self.board.squareList[index].getAdjacent()[x]]
                    if adj.getState() == 0:
                        return True

            return False
        return

    def checkLegalMove(self, firstSquare, secondSquare, peice):
        if firstSquare.getNum() not in self.mySquares and firstSquare.getNum(
        ) not in self.myKings:
            return False
        if self.playerNum == 1:
            moveForward = [1, 2]
        else:
            moveForward = [0, 3]
        if peice == 'king':
            for x in xrange(4):
                if firstSquare.getAdjacent()[x] != None:
                    if self.board.squareList[firstSquare.getAdjacent(
                    )[x]].getState() == 0 and secondSquare.getNum(
                    ) in firstSquare.getAdjacent():
                        return True

            return False
        elif peice == 'normal':
            for x in moveForward:
                if firstSquare.getAdjacent(
                )[x] != None and secondSquare.getNum(
                ) in firstSquare.getAdjacent():
                    if self.board.squareList[firstSquare.getAdjacent(
                    )[x]].getState() == 0 and firstSquare.getAdjacent().index(
                            secondSquare.getNum()) == x:
                        return True

            return False
        return

    def checkLegalJump(self, firstSquare, secondSquare, peice):
        if firstSquare.getNum() not in self.mySquares and firstSquare.getNum(
        ) not in self.myKings and len(self.moveList) == 1:
            return False
        if self.playerNum == 1:
            moveForward = [1, 2]
            opposingPeices = [2, 4]
        else:
            moveForward = [0, 3]
            opposingPeices = [1, 3]
        if peice == 'king':
            if secondSquare.getNum() in firstSquare.getJumps():
                index = firstSquare.getJumps().index(secondSquare.getNum())
                if self.board.squareList[firstSquare.getAdjacent()
                                         [index]].getState() in opposingPeices:
                    return True
                else:
                    return False
        elif peice == 'normal':
            if secondSquare.getNum() in firstSquare.getJumps():
                index = firstSquare.getJumps().index(secondSquare.getNum())
                if index in moveForward:
                    if self.board.squareList[firstSquare.getAdjacent(
                    )[index]].getState() in opposingPeices:
                        return True
                    else:
                        return False
                else:
                    return False
            else:
                return False

    def d_requestMove(self, moveList):
        self.sendUpdate('requestMove', [moveList])

    def setGameState(self, tableState, moveList):
        if moveList != []:
            if self.board.squareList[moveList[0]].getState(
            ) == 1 or self.board.squareList[moveList[0]].getState() == 3:
                playerColor = 'white'
            else:
                playerColor = 'black'
            if self.board.squareList[moveList[0]].getState() <= 2:
                self.animatePeice(tableState, moveList, 'normal', playerColor)
            else:
                self.animatePeice(tableState, moveList, 'king', playerColor)
        else:
            self.updateGameState(tableState)

    def updateGameState(self, squares):
        self.board.setStates(squares)
        self.mySquares = []
        self.myKings = []
        messenger.send('wakeup')
        isObserve = False
        if self.playerNum == None:
            self.playerNum = 1
            self.playerColorString = 'white'
            isObserve = True
        for xx in xrange(32):
            for blah in self.locatorList[xx].getChildren():
                blah.hide()
                if self.locatorList[xx].getChildren().index(blah) != 0:
                    blah1 = blah.find('**/checker_k*')

            owner = self.board.squareList[xx].getState()
            if owner == self.playerNum:
                if self.playerColorString == 'white':
                    x = self.locatorList[xx].getChildren()[1]
                    x.show()
                    x.find('**/checker_k*').hide()
                else:
                    x = self.locatorList[xx].getChildren()[2]
                    x.show()
                    x.find('**/checker_k*').hide()
                self.mySquares.append(xx)
            elif owner == 0:
                self.hideChildren(self.locatorList[xx].getChildren())
            elif owner == self.playerNum + 2:
                if self.playerColorString == 'white':
                    x = self.locatorList[xx].getChildren()[1]
                    x.show()
                    x.find('**/checker_k*').show()
                else:
                    x = self.locatorList[xx].getChildren()[2]
                    x.show()
                    x.find('**/checker_k*').show()
                self.myKings.append(xx)
            elif owner <= 2:
                if self.playerColorString == 'white':
                    x = self.locatorList[xx].getChildren()[2]
                    x.show()
                    x.find('**/checker_k*').hide()
                else:
                    x = self.locatorList[xx].getChildren()[1]
                    x.show()
                    x.find('**/checker_k*').hide()
            elif self.playerColorString == 'white':
                x = self.locatorList[xx].getChildren()[2]
                x.show()
                x.find('**/checker_k*').show()
            else:
                x = self.locatorList[xx].getChildren()[1]
                x.show()
                x.find('**/checker_k*').show()

        if isObserve == True:
            self.playerNum = None
            self.playerColorString = None
            return
        self.mustJump = False
        self.hasNormalMoves = False
        for x in self.myKings:
            if self.existsLegalJumpsFrom(x, 'king') == True:
                self.mustJump = True
                break
            else:
                self.mustJump = False

        if self.mustJump == False:
            for x in self.mySquares:
                if self.existsLegalJumpsFrom(x, 'normal') == True:
                    self.mustJump = True
                    break
                else:
                    self.mustJump = False

        if self.mustJump != True:
            for x in self.mySquares:
                if self.existsLegalMovesFrom(x, 'normal') == True:
                    self.hasNormalMoves = True
                    break
                else:
                    self.hasNormalMoves = False
                if self.hasNormalMoves == False:
                    for x in self.myKings:
                        if self.existsLegalMovesFrom(x, 'king') == True:
                            self.hasNormalMoves = True
                            break
                        else:
                            self.hasNormalMoves = False

        if self.mustJump == False and self.hasNormalMoves == False:
            pass
        return

    def hideChildren(self, nodeList):
        for x in xrange(1, 2):
            nodeList[x].hide()

    def animatePeice(self, tableState, moveList, type, playerColor):
        messenger.send('wakeup')
        if playerColor == 'white':
            gamePeiceForAnimation = loader.loadModel(
                'phase_6/models/golf/regular_checker_piecewhite.bam')
        else:
            gamePeiceForAnimation = loader.loadModel(
                'phase_6/models/golf/regular_checker_pieceblack.bam')
        if type == 'king':
            gamePeiceForAnimation.find('**/checker_k*').show()
        else:
            gamePeiceForAnimation.find('**/checker_k*').hide()
        gamePeiceForAnimation.reparentTo(self.boardNode)
        gamePeiceForAnimation.setPos(self.locatorList[moveList[0]].getPos())
        if self.isRotated == True:
            gamePeiceForAnimation.setH(180)
        for x in self.locatorList[moveList[0]].getChildren():
            x.hide()

        checkersPeiceTrack = Sequence()
        length = len(moveList)
        for x in xrange(length - 1):
            checkersPeiceTrack.append(
                Parallel(
                    SoundInterval(self.moveSound),
                    ProjectileInterval(
                        gamePeiceForAnimation,
                        endPos=self.locatorList[moveList[x + 1]].getPos(),
                        duration=0.5)))

        checkersPeiceTrack.append(Func(gamePeiceForAnimation.removeNode))
        checkersPeiceTrack.append(Func(self.updateGameState, tableState))
        checkersPeiceTrack.append(Func(self.unAlpha, moveList))
        checkersPeiceTrack.start()

    def announceWin(self, avId):
        self.fsm.request('gameOver')

    def unAlpha(self, moveList):
        for x in moveList:
            self.locatorList[x].setColorOff()

    def doRandomMove(self):
        import random
        move = []
        foundLegal = False
        self.blinker.pause()
        self.numRandomMoves += 1
        while not foundLegal:
            x = random.randint(0, 9)
            for y in self.board.getAdjacent(self.mySquares[x]):
                if y != None and self.board.getState(y) == 0:
                    move.append(self.mySquares[x])
                    move.append(y)
                    foundLegal = True
                    break

        if move == []:
            pass
        playSound = Sequence(SoundInterval(self.knockSound))
        playSound.start()
        self.d_requestMove(move)
        self.moveList = []
        self.isMyTurn = False
        if self.numRandomMoves >= 5:
            self.exitButtonPushed()
        return

    def doNothing(self):
        pass
class DistributedPicnicTable(DistributedNode.DistributedNode):

    def __init__(self, cr):
        self.cr = cr
        NodePath.__init__(self, 'DistributedPicnicTable')
        DistributedNode.DistributedNode.__init__(self, cr)
        self.reparentTo(render)
        self.picnicTable = loader.loadModel('phase_6/models/golf/game_table.bam')
        self.picnicTable.reparentTo(self)
        self.picnicTableSphereNodes = []
        self.numSeats = 6
        self.seats = []
        self.jumpOffsets = []
        self.inGame = False
        self.requestSeat = None
        self.gameState = None
        self.cameraBoardTrack = Func(self.doNothing)
        self.seatBumpForObserve = 0
        self.winTrack = Sequence()
        self.outTrack = Sequence()
        self.joinButton = None
        self.observeButton = None
        self.tutorialButton = None
        self.exitButton = None
        self.isPlaying = False
        self.gameMenu = None
        self.game = None
        self.gameZone = None
        self.tutorial = None
        self.timerFunc = None
        self.gameDoId = None
        self.gameWantTimer = False
        self.tableState = [None,
         None,
         None,
         None,
         None,
         None]
        self.haveAnimated = []
        self.winSound = base.loadSfx('phase_6/audio/sfx/KART_Applause_1.ogg')
        self.happyDance = base.loadSfx('phase_5/audio/sfx/AA_heal_happydance.ogg')
        self.accept('stoppedAsleep', self.handleSleep)
        base.localAvatar.startSleepWatch(self.handleSleep)
        self.__toonTracks = {}
        self.fsm = ClassicFSM.ClassicFSM('PicnicTable', [State.State('off', self.enterOff, self.exitOff, ['chooseMode', 'observing']),
         State.State('chooseMode', self.enterChooseMode, self.exitChooseMode, ['sitting', 'off', 'observing']),
         State.State('sitting', self.enterSitting, self.exitSitting, ['off']),
         State.State('observing', self.enterObserving, self.exitObserving, ['off'])], 'off', 'off')
        self.fsm.enterInitialState()
        for i in xrange(self.numSeats):
            self.seats.append(self.picnicTable.find('**/*seat%d' % (i + 1)))
            self.jumpOffsets.append(self.picnicTable.find('**/*jumpOut%d' % (i + 1)))

        self.tableCloth = self.picnicTable.find('**/basket_locator')
        self.tableclothSphereNode = self.tableCloth.attachNewNode(CollisionNode('tablecloth_sphere'))
        self.tableclothSphereNode.node().addSolid(CollisionSphere(0, 0, -2, 5.5))
        self.clockNode = ToontownTimer()
        self.clockNode.setPos(1.16, 0, -0.83)
        self.clockNode.setScale(0.3)
        self.clockNode.hide()
        return

    def announceGenerate(self):
        DistributedNode.DistributedNode.announceGenerate(self)
        for i in xrange(self.numSeats):
            self.picnicTableSphereNodes.append(self.seats[i].attachNewNode(CollisionNode('picnicTable_sphere_%d_%d' % (self.getDoId(), i))))
            self.picnicTableSphereNodes[i].node().addSolid(CollisionSphere(0, 0, 0, 2))

        self.tableState = [None,
         None,
         None,
         None,
         None,
         None]
        self.requestTableState()
        self.buttonModels = loader.loadModel('phase_3.5/models/gui/inventory_gui')
        self.upButton = self.buttonModels.find('**//InventoryButtonUp')
        self.downButton = self.buttonModels.find('**/InventoryButtonDown')
        self.rolloverButton = self.buttonModels.find('**/InventoryButtonRollover')
        angle = self.getH()
        angle -= 90
        radAngle = deg2Rad(angle)
        unitVec = Vec3(math.cos(radAngle), math.sin(radAngle), 0)
        unitVec *= 30.0
        self.endPos = self.getPos() + unitVec
        dist = Vec3(self.endPos - self.getPos()).length()
        wheelAngle = dist / (0.5 * 1.4 * math.pi) * 360
        self.__enableCollisions()
        return

    def handleSleep(self, task = None):
        if self.fsm.getCurrentState().getName() == 'chooseMode':
            self.cancelButtonPushed()
        elif self.fsm.getCurrentState().getName() == 'sitting':
            self.sendUpdate('requestExit', [])
        if self.gameMenu != None:
            self.gameMenu.removeButtons()
            self.gameMenu.picnicFunction = None
            self.gameMenu = None
        if task != None:
            task.done
        return

    def disable(self):
        DistributedNode.DistributedNode.disable(self)
        self.ignore('stoppedAsleep')
        self.clearToonTracks()
        self.__disableCollisions()
        self.disableChoiceButtons()
        self.picnicTable.removeNode()
        self.cameraBoardTrack = None
        return

    def delete(self):
        self.__disableCollisions()
        self.ignore('stoppedAsleep')
        DistributedNode.DistributedNode.delete(self)
        self.disableChoiceButtons()
        self.cameraBoardTrack = None
        del self.winTrack
        del self.outTrack
        self.fsm = None
        self.gameZone = None
        self.clearToonTracks()
        self.cameraBoardTrack = None
        return

    def setName(self, name):
        self.name = name

    def setGameDoId(self, doId):
        self.gameDoId = doId
        self.game = self.cr.doId2do[doId]
        self.game.setHpr(self.getHpr())
        self.gameWantTimer = self.game.wantTimer
        if self.gameState == 1:
            self.game.fsm.request('playing')

    def setTimerFunc(self, function):
        self.timerFunc = function

    def setTimer(self, timerEnd):
        self.clockNode.stop()
        time = globalClockDelta.networkToLocalTime(timerEnd)
        self.timeLeft = int(time - globalClock.getRealTime())
        if self.gameWantTimer and self.game != None:
            self.showTimer()
        return

    def showTimer(self):
        self.clockNode.stop()
        self.clockNode.countdown(self.timeLeft, self.timerFunc)
        self.clockNode.show()

    def requestTableState(self):
        self.sendUpdate('requestTableState', [])

    def setTableState(self, tableStateList, isplaying):
        y = 0
        print 'SET TABLE STATE'
        if isplaying == 0:
            self.isPlaying = False
        else:
            self.isPlaying = True
        for x in tableStateList:
            if x != 0:
                if x not in self.tableState and x in self.cr.doId2do and x not in self.haveAnimated:
                    seatIndex = tableStateList.index(x)
                    toon = self.cr.doId2do[x]
                    toon.stopSmooth()
                    toon.setAnimState('Sit', 1.0)
                    dest = self.seats[seatIndex].getPos(self.tableCloth)
                    hpr = self.seats[seatIndex].getHpr(render)
                    toon.setHpr(hpr)
                    if seatIndex > 2:
                        toon.setH(self.getH() + 180)
                    toon.wrtReparentTo(self)
                    toon.setPos(dest)
                    toon.setZ(toon.getZ() + 1.35)
                    if seatIndex > 2:
                        toon.setY(toon.getY() - 1.0)
                    else:
                        toon.setY(toon.getY() + 1.0)
            if x != 0:
                self.tableState[y] = x
            else:
                self.tableState[y] = None
            y = y + 1

        numPlayers = 0
        for x in self.tableState:
            if x != None:
                numPlayers += 1

        print ' GETTING 2', self.gameMenu, numPlayers
        if self.gameMenu:
            if numPlayers > 2:
                print ' GETTING HERE!!'
                self.gameMenu.FindFour.setColor(0.7, 0.7, 0.7, 0.7)
                self.gameMenu.FindFour['command'] = self.doNothing
                self.gameMenu.findFourText['fg'] = (0.7, 0.7, 0.7, 0.7)
                self.gameMenu.Checkers.setColor(0.7, 0.7, 0.7, 0.7)
                self.gameMenu.Checkers['command'] = self.doNothing
                self.gameMenu.checkersText['fg'] = (0.7, 0.7, 0.7, 0.7)
        return

    def setIsPlaying(self, isPlaying):
        if isPlaying == 0:
            self.isPlaying = False
        elif isPlaying == 1:
            self.isPlaying = True

    def announceWinner(self, winString, avId):
        if avId == base.localAvatar.getDoId():
            sound = Sequence(Wait(2.0), Parallel(SoundInterval(self.winSound), SoundInterval(self.happyDance)))
            sound.start()
            base.cr.playGame.getPlace().setState('walk')
            if winString == 'Chinese Checkers':
                whisper = WhisperPopup(TTLocalizer.ChineseCheckersYouWon, OTPGlobals.getInterfaceFont(), WhisperPopup.WTNormal)
            elif winString == 'Checkers':
                whisper = WhisperPopup(TTLocalizer.RegularCheckersYouWon, OTPGlobals.getInterfaceFont(), WhisperPopup.WTNormal)
            elif winString == 'Find Four':
                whisper = WhisperPopup('You won a game of Find Four!', OTPGlobals.getInterfaceFont(), WhisperPopup.WTNormal)
        elif avId in self.cr.doId2do:
            stateString = self.fsm.getCurrentState().getName()
            if stateString == 'sitting' or stateString == 'observing':
                base.cr.playGame.getPlace().setState('walk')
            av = self.cr.doId2do[avId]
            if winString == 'Chinese Checkers':
                whisper = WhisperPopup(av.getName() + TTLocalizer.ChineseCheckersGameOf + TTLocalizer.ChineseCheckers, OTPGlobals.getInterfaceFont(), WhisperPopup.WTNormal)
            elif winString == 'Checkers':
                whisper = WhisperPopup(av.getName() + TTLocalizer.RegularCheckersGameOf + TTLocalizer.RegularCheckers, OTPGlobals.getInterfaceFont(), WhisperPopup.WTNormal)
            elif winString == 'Find Four':
                whisper = WhisperPopup(av.getName() + ' has won a game of' + ' Find Four!', OTPGlobals.getInterfaceFont(), WhisperPopup.WTNormal)
        if avId in self.cr.doId2do:
            toon = self.cr.doId2do[avId]
            self.winTrack = Sequence(autoFinish=1)
            if self.outTrack.isPlaying():
                self.winTrack.append(Wait(2.0))
            if avId == base.localAvatar.getDoId():
                self.winTrack.append(Func(self.stopToWalk))
            self.winTrack.append(ActorInterval(toon, 'happy-dance'))
            if avId == base.localAvatar.getDoId():
                self.winTrack.append(Func(self.allowToWalk))
            self.winTrack.start()
        whisper.manage(base.marginManager)

    def handleEnterPicnicTableSphere(self, i, collEntry):
        self.notify.debug('Entering Picnic Table Sphere.... %s' % self.getDoId())
        self.requestSeat = i
        self.seatBumpForObserve = i
        self.fsm.request('chooseMode')

    def enableChoiceButtons(self):
        if self.tableState[self.seatBumpForObserve] == None and self.isPlaying == False:
            self.joinButton = DirectButton(
                relief=None,
                text=TTLocalizer.PicnicTableJoinButton,
                text_fg=(1, 1, 0.65, 1),
                text_pos=(0, -.23),
                text_scale=0.8,
                image=(self.upButton, self.downButton, self.rolloverButton),
                image_color=(1, 0, 0, 1),
                image_scale=(20, 1, 11),
                pos=(0, 0, 0.8),
                scale=0.15,
                command=lambda self = self: self.joinButtonPushed())
        if self.isPlaying == True:
            self.observeButton = DirectButton(
                relief=None,
                text=TTLocalizer.PicnicTableObserveButton,
                text_fg=(1, 1, 0.65, 1),
                text_pos=(0, -.23),
                text_scale=0.8,
                image=(self.upButton, self.downButton, self.rolloverButton),
                image_color=(1, 0, 0, 1),
                image_scale=(20, 1, 11),
                pos=(0, 0, 0.6),
                scale=0.15,
                command=lambda self = self: self.observeButtonPushed())
        self.exitButton = DirectButton(
            relief=None,
            text=TTLocalizer.PicnicTableCancelButton,
            text_fg=(1, 1, 0.65, 1),
            text_pos=(0, -.23),
            text_scale=0.8,
            image=(self.upButton, self.downButton, self.rolloverButton),
            image_color=(1, 0, 0, 1),
            image_scale=(20, 1, 11),
            pos=(1, 0, 0.6),
            scale=0.15,
            command=lambda self = self: self.cancelButtonPushed())
        self.tutorialButton = DirectButton(
            relief=None,
            text=TTLocalizer.PicnicTableTutorial,
            text_fg=(1, 1, 0.65, 1),
            text_pos=(-.05, -.13),
            text_scale=0.55,
            image=(self.upButton, self.downButton, self.rolloverButton),
            image_color=(1, 0, 0, 1),
            image_scale=(20, 1, 11),
            pos=(-1, 0, 0.6),
            scale=0.15,
            command=lambda self = self: self.tutorialButtonPushed())
        base.cr.playGame.getPlace().setState('stopped')
        return

    def tutorialButtonPushed(self):
        self.disableChoiceButtons()
        self.gameMenu = GameMenu(self.tutorialFunction, 1)
        self.tutorialButton.destroy()
        self.tutorialButton = None
        return

    def tutorialFunction(self, tutVal):
        if tutVal == 1:
            self.tutorial = ChineseTutorial(self.tutorialDone)
        elif tutVal == 2:
            self.tutorial = CheckersTutorial(self.tutorialDone)
        self.gameMenu.picnicFunction = None
        self.gameMenu = None
        return

    def tutorialDone(self):
        self.requestSeat = None
        self.fsm.request('off')
        self.tutorial = None
        return

    def joinButtonPushed(self):
        toon = base.localAvatar
        self.sendUpdate('requestJoin', [self.requestSeat,
         toon.getX(),
         toon.getY(),
         toon.getZ(),
         toon.getH(),
         toon.getP(),
         toon.getR()])
        self.requestSeat = None
        self.fsm.request('sitting')
        return

    def rejectJoin(self):
        self.fsm.request('off')
        self.allowToWalk()

    def cancelButtonPushed(self):
        base.cr.playGame.getPlace().setState('walk')
        self.requestSeat = None
        self.fsm.request('off')
        return

    def disableChoiceButtons(self):
        if self.joinButton:
            self.joinButton.destroy()
        if self.observeButton:
            self.observeButton.destroy()
        if self.exitButton:
            self.exitButton.destroy()
        if self.tutorialButton:
            self.tutorialButton.destroy()

    def pickFunction(self, gameNum):
        if gameNum == 1:
            self.sendUpdate('requestPickedGame', [gameNum])
        elif gameNum == 2:
            self.sendUpdate('requestPickedGame', [gameNum])
        elif gameNum == 3:
            self.sendUpdate('requestPickedGame', [gameNum])

    def allowPick(self):
        self.gameMenu = GameMenu(self.pickFunction, 2)

    def setZone(self, zoneId):
        if self.fsm.getCurrentState().getName() == 'sitting' or self.fsm.getCurrentState().getName() == 'observing':
            if self.tutorial == None:
                self.gameZone = base.cr.addInterest(base.localAvatar.defaultShard, zoneId, 'gameBoard')
                if self.gameMenu != None:
                    self.gameMenu.removeButtons()
                    self.gameMenu.picnicFunction = None
                    self.gameMenu = None
        return

    def fillSlot(self, avId, index, x, y, z, h, p, r, timestamp, parentDoId):
        self.notify.debug('fill Slot: %d for %d' % (index, avId))
        if avId not in self.haveAnimated:
            self.haveAnimated.append(avId)
        if avId == base.localAvatar.getDoId():
            if self.inGame == True:
                return
            else:
                self.inGame = True
                self.seatPos = index
        if avId in self.cr.doId2do:
            toon = self.cr.doId2do[avId]
            toon.stopSmooth()
            toon.wrtReparentTo(self.tableCloth)
            sitStartDuration = toon.getDuration('sit-start')
            jumpTrack = self.generateToonJumpTrack(toon, index)
            track = Sequence(autoFinish=1)
            if avId == base.localAvatar.getDoId():
                if not base.cr.playGame.getPlace() == None:
                    self.moveCamera(index)
                    track.append(Func(self.__disableCollisions))
            track.append(jumpTrack)
            track.append(Func(toon.setAnimState, 'Sit', 1.0))
            track.append(Func(self.clearToonTrack, avId))
            self.storeToonTrack(avId, track)
            track.start()
        return

    def emptySlot(self, avId, index, timestamp):
        self.notify.debug('### seat %s now empty' % index)
        if index == 255 and self.game != None:
            self.stopObserveButtonPushed()
            return
        if avId in self.haveAnimated:
            self.haveAnimated.remove(avId)
        if avId in self.cr.doId2do:
            if avId == base.localAvatar.getDoId():
                if self.gameZone:
                    base.cr.removeInterest(self.gameZone)
                if self.inGame == True:
                    self.inGame = False
                else:
                    return
            toon = self.cr.doId2do[avId]
            toon.stopSmooth()
            sitStartDuration = toon.getDuration('sit-start')
            jumpOutTrack = self.generateToonReverseJumpTrack(toon, index)
            self.outTrack = Sequence(jumpOutTrack)
            if base.localAvatar.getDoId() == avId:
                self.outTrack.append(Func(self.__enableCollisions))
                self.outTrack.append(Func(self.allowToWalk))
                self.fsm.request('off')
            val = self.jumpOffsets[index].getPos(render)
            self.outTrack.append(Func(toon.setPos, val))
            self.outTrack.append(Func(toon.startSmooth))
            self.outTrack.start()
        return

    def stopToWalk(self):
        base.cr.playGame.getPlace().setState('stopped')

    def allowToWalk(self):
        base.cr.playGame.getPlace().setState('walk')

    def moveCamera(self, seatIndex):
        self.oldCameraPos = camera.getPos()
        self.oldCameraHpr = camera.getHpr()
        camera.wrtReparentTo(self.picnicTable)
        heading = PythonUtil.fitDestAngle2Src(camera.getH(), 90)
        if seatIndex < 3:
            self.cameraBoardTrack = LerpPosHprInterval(camera, 2.0, Point3(0, 0, 17), Point3(0, -90, 0))
        elif camera.getH() < 0:
            self.cameraBoardTrack = LerpPosHprInterval(camera, 2.0, Point3(0, 0, 17), Point3(-180, -90, 0))
        else:
            self.cameraBoardTrack = LerpPosHprInterval(camera, 2.0, Point3(0, 0, 17), Point3(180, -90, 0))
        self.cameraBoardTrack.start()

    def moveCameraBack(self):
        self.cameraBoardTrack = LerpPosHprInterval(camera, 2.5, self.oldCameraPos, self.oldCameraHpr)
        self.cameraBoardTrack.start()

    def __enableCollisions(self):
        for i in xrange(self.numSeats):
            self.accept('enterpicnicTable_sphere_%d_%d' % (self.getDoId(), i), self.handleEnterPicnicTableSphere, [i])
            self.picnicTableSphereNodes[i].setCollideMask(ToontownGlobals.WallBitmask)

        self.tableclothSphereNode.setCollideMask(ToontownGlobals.WallBitmask)

    def __disableCollisions(self):
        for i in xrange(self.numSeats):
            self.ignore('enterpicnicTable_sphere_%d_%d' % (self.getDoId(), i))
            self.ignore('enterPicnicTableOK_%d_%d' % (self.getDoId(), i))

        for i in xrange(self.numSeats):
            self.picnicTableSphereNodes[i].setCollideMask(BitMask32(0))

        self.tableclothSphereNode.setCollideMask(BitMask32(0))

    def enterOff(self):
        base.setCellsAvailable(base.leftCells + base.bottomCells, 0)

    def exitOff(self):
        base.setCellsAvailable(base.bottomCells, 0)

    def enterChooseMode(self):
        self.winTrack = Sequence(autoFinish=1)
        self.enableChoiceButtons()

    def exitChooseMode(self):
        self.disableChoiceButtons()

    def enterObserving(self):
        self.enableStopObserveButton()
        self.moveCamera(self.seatBumpForObserve)
        self.sendUpdate('requestGameZone')

    def exitObserving(self):
        if self.cameraBoardTrack.isPlaying():
            self.cameraBoardTrack.pause()
        self.allowToWalk()
        self.stopObserveButton.destroy()

    def enterSitting(self):
        pass

    def exitSitting(self):
        self.gameMenu = None
        return

    def setGameZone(self, zoneId, gamestate):
        self.gameZone = base.cr.addInterest(base.localAvatar.defaultShard, zoneId, 'gameBoard')
        self.gameState = gamestate

    def observeButtonPushed(self):
        self.requestSeat = None
        self.fsm.request('observing')
        return

    def enableStopObserveButton(self):
        self.stopObserveButton = DirectButton(
            relief=None,
            text='Stop Observing',
            text_fg=(1, 1, 0.65, 1),
            text_pos=(0, -.23),
            text_scale=0.45,
            image=(self.upButton, self.downButton, self.rolloverButton),
            image_color=(1, 0, 0, 1),
            image_scale=(20, 1, 11),
            pos=(0.92, 0, 0.4),
            scale=0.15,
            command=lambda self = self: self.stopObserveButtonPushed())
        return

    def stopObserveButtonPushed(self):
        self.sendUpdate('leaveObserve', [])
        self.gameState = None
        if self.game:
            self.game.fsm.request('gameOver')
            base.cr.removeInterest(self.gameZone)
        self.fsm.request('off')
        return

    def generateToonReverseJumpTrack(self, av, seatIndex):
        self.notify.debug('av.getH() = %s' % av.getH())

        def getToonJumpTrack(av, destNode):

            def getJumpDest(av = av, node = destNode):
                dest = node.getPos(self.tableCloth)
                dest += self.jumpOffsets[seatIndex].getPos(self.tableCloth)
                return dest

            def getJumpHpr(av = av, node = destNode):
                hpr = node.getHpr(av.getParent())
                hpr.setX(hpr.getX() + 180)
                angle = PythonUtil.fitDestAngle2Src(av.getH(), hpr.getX())
                hpr.setX(angle)
                return hpr

            toonJumpTrack = Parallel(ActorInterval(av, 'jump'), Sequence(Wait(0.1), Parallel(ProjectileInterval(av, endPos=getJumpDest, duration=0.9))))
            return toonJumpTrack

        toonJumpTrack = getToonJumpTrack(av, self.tableCloth)
        jumpTrack = Sequence(toonJumpTrack, Func(av.loop, 'neutral'), Func(av.wrtReparentTo, render))
        return jumpTrack

    def generateToonJumpTrack(self, av, seatIndex):
        av.pose('sit', 47)
        hipOffset = av.getHipsParts()[2].getPos(av)

        def getToonJumpTrack(av, seatIndex):

            def getJumpDest(av = av, node = self.tableCloth):
                dest = Vec3(self.tableCloth.getPos(av.getParent()))
                seatNode = self.picnicTable.find('**/seat' + str(seatIndex + 1))
                dest += seatNode.getPos(self.tableCloth)
                dna = av.getStyle()
                dest -= hipOffset
                if seatIndex > 2:
                    dest.setY(dest.getY() - 2.0)
                if seatIndex == 1:
                    dest.setY(dest.getY() - 0.5)
                dest.setZ(dest.getZ() + 0.2)
                return dest

            def getJumpHpr(av = av, node = self.tableCloth):
                hpr = self.seats[seatIndex].getHpr(av.getParent())
                if seatIndex < 3:
                    hpr.setX(hpr.getX())
                elif av.getH() < 0:
                    hpr.setX(hpr.getX() - 180)
                else:
                    hpr.setX(hpr.getX() + 180)
                return hpr

            toonJumpTrack = Parallel(ActorInterval(av, 'jump'), Sequence(Wait(0.43), Parallel(LerpHprInterval(av, hpr=getJumpHpr, duration=1), ProjectileInterval(av, endPos=getJumpDest, duration=1))))
            return toonJumpTrack

        def getToonSitTrack(av):
            toonSitTrack = Sequence(ActorInterval(av, 'sit-start'), Func(av.loop, 'sit'))
            return toonSitTrack

        toonJumpTrack = getToonJumpTrack(av, seatIndex)
        toonSitTrack = getToonSitTrack(av)
        jumpTrack = Sequence(Parallel(toonJumpTrack, Sequence(Wait(1), toonSitTrack)), Func(av.wrtReparentTo, self.tableCloth))
        return jumpTrack

    def storeToonTrack(self, avId, track):
        self.clearToonTrack(avId)
        self.__toonTracks[avId] = track

    def clearToonTrack(self, avId):
        oldTrack = self.__toonTracks.get(avId)
        if oldTrack:
            oldTrack.pause()
            DelayDelete.cleanupDelayDeletes(oldTrack)

    def clearToonTracks(self):
        keyList = []
        for key in self.__toonTracks:
            keyList.append(key)

        for key in keyList:
            if key in self.__toonTracks:
                self.clearToonTrack(key)

    def doNothing(self):
        pass
예제 #6
0
class CogdoMazeGuiManager:
    def __init__(self, maze, bossCode):
        self.maze = maze
        self.root = NodePath('CogdoMazeGui')
        self.root.reparentTo(aspect2d)
        self.mazeMapGui = CogdoMazeMapGui(self.maze.collisionTable)
        if bossCode is not None:
            self._bossGui = CogdoMazeBossGui(bossCode)
        else:
            self._bossGui = None
        self._memoGui = CogdoMemoGui(self.root)
        self._memoGui.posNextToLaffMeter()
        self._presentGuiIval = None
        self._presentTimerIval = None
        self._hud = CogdoMazeHud()
        self._timer = None
        self._initMessageDisplay()
        return

    def _initTimer(self):
        self._timer = ToontownTimer()
        self._timer.hide()
        self._timer.posInTopRightCorner()

    def _initMessageDisplay(self):
        self.messageDisplay = CogdoGameMessageDisplay(
            'CogdoMazeMessageDisplay', self.root, pos=Globals.MessageLabelPos)

    def destroy(self):
        ToontownIntervals.cleanup('present_gui')
        ToontownIntervals.cleanup('present_timer')
        ToontownIntervals.cleanup('present_memo')
        self._hud.destroy()
        self._hud = None
        self._memoGui.destroy()
        self._memoGui = None
        if self._bossGui is not None:
            self._bossGui.destroy()
            self._bossGui = None
        self.messageDisplay.destroy()
        self.messageDisplay = None
        self.destroyMazeMap()
        self.destroyTimer()
        if self._presentGuiIval:
            self._presentGuiIval.pause()
            self._presentGuiIval = None
        if self._presentTimerIval:
            self._presentTimerIval.pause()
            self._presentTimerIval = None
        return

    def destroyMazeMap(self):
        if hasattr(self, 'mazeMapGui') and self.mazeMapGui is not None:
            self.mazeMapGui.destroy()
            del self.mazeMapGui
        return

    def destroyTimer(self):
        if self._timer is not None:
            self._timer.stop()
            self._timer.destroy()
            self._timer = None
        return

    def showPickupCounter(self):
        ToontownIntervals.start(
            ToontownIntervals.getPresentGuiIval(self._memoGui, 'present_memo'))

    def startGame(self, firstMessage):
        self._presentGuiIval = ToontownIntervals.start(
            Sequence(ToontownIntervals.getPresentGuiIval(self._bossGui,
                                                         '',
                                                         startPos=(0, 0,
                                                                   -0.15)),
                     Func(self.mazeMapGui.show),
                     ToontownIntervals.getPulseLargerIval(
                         self.mazeMapGui, '',
                         scale=self.mazeMapGui.getScale()),
                     Func(self.setMessage, firstMessage),
                     name='present_gui'))

    def hideMazeMap(self):
        self.mazeMapGui.hide()

    def showBossGui(self):
        if self._bossGui is not None:
            self._bossGui.show()
        return

    def hideBossGui(self):
        if self._bossGui is not None:
            self._bossGui.hide()
        return

    def revealMazeMap(self):
        self.mazeMapGui.revealAll()

    def hideLock(self, lockIndex):
        self.mazeMapGui.hideLock(lockIndex)

    def showTimer(self, duration, timerExpiredCallback=None):
        if self._timer is None:
            self._initTimer()
        self._timer.setTime(duration)
        self._timer.countdown(duration, timerExpiredCallback)
        self._timer.show()
        self._presentTimerIval = ToontownIntervals.start(
            ToontownIntervals.getPresentGuiIval(self._timer,
                                                'present_timer',
                                                startPos=(0, 0, 0.35)))
        return

    def hideTimer(self):
        if hasattr(self, 'timer') and self._timer is not None:
            self._timer.hide()
            self._timer.stop()
        return

    def setMessage(self, text, color=None, transition='fade'):
        self.messageDisplay.updateMessage(text, color, transition)

    def setMessageTemporary(self, text, time=3.0):
        self.messageDisplay.showMessageTemporarily(text, time)

    def clearMessage(self):
        self.messageDisplay.updateMessage('')

    def setPickupCount(self, count):
        self._memoGui.setCount(count)

    def showBossCode(self, bossIndex):
        self._bossGui.showNumber(bossIndex)

    def showBossHit(self, bossIndex):
        self._bossGui.showHit(bossIndex)

    def showQuestArrow(self, toon, target, offset):
        self._hud.showQuestArrow(toon, target, offset)

    def hideQuestArrow(self):
        self._hud.hideQuestArrow()
class DistributedChineseCheckers(DistributedNode.DistributedNode):

    def __init__(self, cr):
        NodePath.__init__(self, 'DistributedChineseCheckers')
        DistributedNode.DistributedNode.__init__(self, cr)
        self.cr = cr
        self.reparentTo(render)
        self.boardNode = loader.loadModel('phase_6/models/golf/checker_game.bam')
        self.boardNode.reparentTo(self)
        self.board = ChineseCheckersBoard()
        self.playerTags = render.attachNewNode('playerTags')
        self.playerTagList = []
        self.exitButton = None
        self.inGame = False
        self.waiting = True
        self.startButton = None
        self.playerNum = None
        self.turnText = None
        self.isMyTurn = False
        self.wantTimer = True
        self.leaveButton = None
        self.screenText = None
        self.turnText = None
        self.exitButton = None
        self.numRandomMoves = 0
        self.blinker = Sequence()
        self.playersTurnBlinker = Sequence()
        self.yourTurnBlinker = Sequence()
        self.moveList = []
        self.mySquares = []
        self.playerSeats = None
        self.accept('mouse1', self.mouseClick)
        self.traverser = base.cTrav
        self.pickerNode = CollisionNode('mouseRay')
        self.pickerNP = camera.attachNewNode(self.pickerNode)
        self.pickerNode.setFromCollideMask(ToontownGlobals.WallBitmask)
        self.pickerRay = CollisionRay()
        self.pickerNode.addSolid(self.pickerRay)
        self.myHandler = CollisionHandlerQueue()
        self.traverser.addCollider(self.pickerNP, self.myHandler)
        self.buttonModels = loader.loadModel('phase_3.5/models/gui/inventory_gui')
        self.upButton = self.buttonModels.find('**//InventoryButtonUp')
        self.downButton = self.buttonModels.find('**/InventoryButtonDown')
        self.rolloverButton = self.buttonModels.find('**/InventoryButtonRollover')
        self.clockNode = ToontownTimer()
        self.clockNode.setPos(1.16, 0, -0.83)
        self.clockNode.setScale(0.3)
        self.clockNode.hide()
        self.playerColors = [Vec4(0, 0.9, 0, 1),
         Vec4(0.9, 0.9, 0, 1),
         Vec4(0.45, 0, 0.45, 1),
         Vec4(0.2, 0.4, 0.8, 1),
         Vec4(1, 0.45, 1, 1),
         Vec4(0.8, 0, 0, 1)]
        self.tintConstant = Vec4(0.25, 0.25, 0.25, 0)
        self.ghostConstant = Vec4(0, 0, 0, 0.5)
        self.startingPositions = [[0,
          1,
          2,
          3,
          4,
          5,
          6,
          7,
          8,
          9],
         [10,
          11,
          12,
          13,
          23,
          24,
          25,
          35,
          36,
          46],
         [65,
          75,
          76,
          86,
          87,
          88,
          98,
          99,
          100,
          101],
         [111,
          112,
          113,
          114,
          115,
          116,
          117,
          118,
          119,
          120],
         [74,
          84,
          85,
          95,
          96,
          97,
          107,
          108,
          109,
          110],
         [19,
          20,
          21,
          22,
          32,
          33,
          34,
          44,
          45,
          55]]
        self.nonOpposingPositions = []
        self.knockSound = base.loadSfx('phase_5/audio/sfx/GUI_knock_1.ogg')
        self.clickSound = base.loadSfx('phase_3/audio/sfx/GUI_balloon_popup.ogg')
        self.moveSound = base.loadSfx('phase_6/audio/sfx/CC_move.ogg')
        self.accept('stoppedAsleep', self.handleSleep)
        from direct.fsm import ClassicFSM, State
        self.fsm = ClassicFSM.ClassicFSM('ChineseCheckers', [State.State('waitingToBegin', self.enterWaitingToBegin, self.exitWaitingToBegin, ['playing', 'gameOver']), State.State('playing', self.enterPlaying, self.exitPlaying, ['gameOver']), State.State('gameOver', self.enterGameOver, self.exitGameOver, ['waitingToBegin'])], 'waitingToBegin', 'waitingToBegin')
        x = self.boardNode.find('**/locators')
        self.locatorList = x.getChildren()
        tempList = []
        for x in xrange(0, 121):
            self.locatorList[x].setTag('GamePeiceLocator', '%d' % x)
            tempList.append(self.locatorList[x].attachNewNode(CollisionNode('picker%d' % x)))
            tempList[x].node().addSolid(CollisionSphere(0, 0, 0, 0.115))

        for z in self.locatorList:
            y = loader.loadModel('phase_6/models/golf/checker_marble.bam')
            z.setColor(0, 0, 0, 0)
            y.reparentTo(z)

        return

    def setName(self, name):
        self.name = name

    def announceGenerate(self):
        DistributedNode.DistributedNode.announceGenerate(self)
        if self.table.fsm.getCurrentState().getName() != 'observing':
            if base.localAvatar.doId in self.table.tableState:
                self.seatPos = self.table.tableState.index(base.localAvatar.doId)
        self.playerTags.setPos(self.getPos())

    def handleSleep(self, task = None):
        if self.fsm.getCurrentState().getName() == 'waitingToBegin':
            self.exitButtonPushed()
        if task != None:
            task.done
        return

    def setTableDoId(self, doId):
        self.tableDoId = doId
        self.table = self.cr.doId2do[doId]
        self.table.setTimerFunc(self.startButtonPushed)
        self.fsm.enterInitialState()
        self.table.setGameDoId(self.doId)

    def disable(self):
        DistributedNode.DistributedNode.disable(self)
        if self.leaveButton:
            self.leaveButton.destroy()
            self.leavebutton = None
        if self.screenText:
            self.screenText.destroy()
            self.screenText = None
        if self.turnText:
            self.turnText.destroy()
            self.turnText = None
        self.clockNode.stop()
        self.clockNode.hide()
        self.ignore('mouse1')
        self.ignore('stoppedAsleep')
        self.fsm = None
        self.cleanPlayerTags()
        return

    def delete(self):
        DistributedNode.DistributedNode.delete(self)
        self.table.gameDoId = None
        self.table.game = None
        if self.exitButton:
            self.exitButton.destroy()
        if self.startButton:
            self.startButton.destroy()
        self.clockNode.stop()
        self.clockNode.hide()
        self.table.startButtonPushed = None
        self.ignore('mouse1')
        self.ignore('stoppedAsleep')
        self.fsm = None
        self.table = None
        self.cleanPlayerTags()
        del self.playerTags
        del self.playerTagList
        self.playerSeats = None
        self.yourTurnBlinker.finish()
        return

    def getTimer(self):
        self.sendUpdate('requestTimer', [])

    def setTimer(self, timerEnd):
        if self.fsm.getCurrentState() != None and self.fsm.getCurrentState().getName() == 'waitingToBegin' and not self.table.fsm.getCurrentState().getName() == 'observing':
            self.clockNode.stop()
            time = globalClockDelta.networkToLocalTime(timerEnd)
            timeLeft = int(time - globalClock.getRealTime())
            if timeLeft > 0 and timerEnd != 0:
                if timeLeft > 60:
                    timeLeft = 60
                self.clockNode.setPos(1.16, 0, -0.83)
                self.clockNode.countdown(timeLeft, self.startButtonPushed)
                self.clockNode.show()
            else:
                self.clockNode.stop()
                self.clockNode.hide()
        return

    def setTurnTimer(self, turnEnd):
        if self.fsm.getCurrentState() != None and self.fsm.getCurrentState().getName() == 'playing':
            self.clockNode.stop()
            time = globalClockDelta.networkToLocalTime(turnEnd)
            timeLeft = int(time - globalClock.getRealTime())
            if timeLeft > 0:
                self.clockNode.setPos(-.74, 0, -0.2)
                if self.isMyTurn:
                    self.clockNode.countdown(timeLeft, self.doRandomMove)
                else:
                    self.clockNode.countdown(timeLeft, self.doNothing)
                self.clockNode.show()
        return

    def gameStart(self, playerNum):
        if playerNum != 255:
            self.playerNum = playerNum
            self.playerColor = self.playerColors[playerNum - 1]
            self.moveCameraForGame()
            playerPos = playerNum - 1
            import copy
            self.nonOpposingPositions = copy.deepcopy(self.startingPositions)
            if playerPos == 0:
                self.nonOpposingPositions.pop(0)
                self.opposingPositions = self.nonOpposingPositions.pop(2)
            elif playerPos == 1:
                self.nonOpposingPositions.pop(1)
                self.opposingPositions = self.nonOpposingPositions.pop(3)
            elif playerPos == 2:
                self.nonOpposingPositions.pop(2)
                self.opposingPositions = self.nonOpposingPositions.pop(4)
            elif playerPos == 3:
                self.nonOpposingPositions.pop(3)
                self.opposingPositions = self.nonOpposingPositions.pop(0)
            elif playerPos == 4:
                self.nonOpposingPositions.pop(4)
                self.opposingPositions = self.nonOpposingPositions.pop(1)
            elif playerPos == 5:
                self.nonOpposingPositions.pop(5)
                self.opposingPositions = self.nonOpposingPositions.pop(2)
        self.fsm.request('playing')

    def sendTurn(self, playersTurn):
        self.playersTurnBlinker.finish()
        if self.fsm.getCurrentState().getName() == 'playing':
            if self.playerSeats == None:
                self.sendUpdate('requestSeatPositions', [])
            else:
                if playersTurn == self.playerNum:
                    self.isMyTurn = True
                self.enableTurnScreenText(playersTurn)
                self.playersTurnBlinker = Sequence()
                origColor = self.playerColors[playersTurn - 1]
                self.playersTurnBlinker.append(LerpColorInterval(self.playerTagList[self.playerSeats.index(playersTurn)], 0.4, origColor - self.tintConstant - self.ghostConstant, origColor))
                self.playersTurnBlinker.append(LerpColorInterval(self.playerTagList[self.playerSeats.index(playersTurn)], 0.4, origColor, origColor - self.tintConstant - self.ghostConstant))
                self.playersTurnBlinker.loop()
        return

    def announceSeatPositions(self, playerPos):
        self.playerSeats = playerPos
        for x in xrange(6):
            pos = self.table.seats[x].getPos(render)
            renderedPeice = loader.loadModel('phase_6/models/golf/checker_marble.bam')
            renderedPeice.reparentTo(self.playerTags)
            renderedPeice.setPos(pos)
            renderedPeice.setScale(1.5)
            if x == 1:
                renderedPeice.setZ(renderedPeice.getZ() + 3.3)
                renderedPeice.setScale(1.3)
            elif x == 4:
                renderedPeice.setZ(renderedPeice.getZ() + 3.3)
                renderedPeice.setScale(1.45)
            else:
                renderedPeice.setZ(renderedPeice.getZ() + 3.3)
            renderedPeice.hide()

        self.playerTagList = self.playerTags.getChildren()
        for x in playerPos:
            if x != 0:
                self.playerTagList[playerPos.index(x)].setColor(self.playerColors[x - 1])
                self.playerTagList[playerPos.index(x)].show()

    def cleanPlayerTags(self):
        for x in self.playerTagList:
            x.removeNode()

        self.playerTagList = []
        self.playerTags.removeNode()

    def moveCameraForGame(self):
        if self.table.cameraBoardTrack.isPlaying():
            self.table.cameraBoardTrack.finish()
        rotation = 0
        if self.seatPos > 2:
            if self.playerNum == 1:
                rotation = 180
            elif self.playerNum == 2:
                rotation = -120
            elif self.playerNum == 3:
                rotation = -60
            elif self.playerNum == 4:
                rotation = 0
            elif self.playerNum == 5:
                rotation = 60
            elif self.playerNum == 6:
                rotation = 120
        elif self.playerNum == 1:
            rotation = 0
        elif self.playerNum == 2:
            rotation = 60
        elif self.playerNum == 3:
            rotation = 120
        elif self.playerNum == 4:
            rotation = 180
        elif self.playerNum == 5:
            rotation = -120
        elif self.playerNum == 6:
            rotation = -60
        if rotation == 60 or rotation == -60:
            int = LerpHprInterval(self.boardNode, 2.5, Vec3(rotation, self.boardNode.getP(), self.boardNode.getR()), self.boardNode.getHpr())
        elif rotation == 120 or rotation == -120:
            int = LerpHprInterval(self.boardNode, 3.5, Vec3(rotation, self.boardNode.getP(), self.boardNode.getR()), self.boardNode.getHpr())
        else:
            int = LerpHprInterval(self.boardNode, 4.2, Vec3(rotation, self.boardNode.getP(), self.boardNode.getR()), self.boardNode.getHpr())
        int.start()

    def enterWaitingToBegin(self):
        if self.table.fsm.getCurrentState().getName() != 'observing':
            self.enableExitButton()
            self.enableStartButton()

    def exitWaitingToBegin(self):
        if self.exitButton:
            self.exitButton.destroy()
            self.exitButton = None
        if self.startButton:
            self.startButton.destroy()
            self.exitButton = None
        self.clockNode.stop()
        self.clockNode.hide()
        return

    def enterPlaying(self):
        self.inGame = True
        self.enableScreenText()
        if self.table.fsm.getCurrentState().getName() != 'observing':
            self.enableLeaveButton()

    def exitPlaying(self):
        self.inGame = False
        if self.leaveButton:
            self.leaveButton.destroy()
            self.leavebutton = None
        self.playerNum = None
        if self.screenText:
            self.screenText.destroy()
            self.screenText = None
        if self.turnText:
            self.turnText.destroy()
            self.turnText = None
        self.clockNode.stop()
        self.clockNode.hide()
        self.cleanPlayerTags()
        return

    def enterGameOver(self):
        pass

    def exitGameOver(self):
        pass

    def exitWaitCountdown(self):
        self.__disableCollisions()
        self.ignore('trolleyExitButton')
        self.clockNode.reset()

    def enableExitButton(self):
        self.exitButton = DirectButton(relief=None, text=TTLocalizer.ChineseCheckersGetUpButton, text_fg=(1, 1, 0.65, 1), text_pos=(0, -.23), text_scale=0.8, image=(self.upButton, self.downButton, self.rolloverButton), image_color=(1, 0, 0, 1), image_scale=(20, 1, 11), pos=(0.92, 0, 0.4), scale=0.15, command=lambda self = self: self.exitButtonPushed())
        return

    def enableScreenText(self):
        defaultPos = (-.8, -0.4)
        if self.playerNum == 1:
            message = TTLocalizer.ChineseCheckersColorG
            color = self.playerColors[0]
        elif self.playerNum == 2:
            message = TTLocalizer.ChineseCheckersColorY
            color = self.playerColors[1]
        elif self.playerNum == 3:
            message = TTLocalizer.ChineseCheckersColorP
            color = self.playerColors[2]
        elif self.playerNum == 4:
            message = TTLocalizer.ChineseCheckersColorB
            color = self.playerColors[3]
        elif self.playerNum == 5:
            message = TTLocalizer.ChineseCheckersColorPink
            color = self.playerColors[4]
        elif self.playerNum == 6:
            message = TTLocalizer.ChineseCheckersColorR
            color = self.playerColors[5]
        else:
            message = TTLocalizer.ChineseCheckersColorO
            color = Vec4(0.0, 0.0, 0.0, 1.0)
            defaultPos = (-.8, -0.4)
        self.screenText = OnscreenText(text=message, pos=defaultPos, scale=0.1, fg=color, align=TextNode.ACenter, mayChange=1)

    def enableStartButton(self):
        self.startButton = DirectButton(relief=None, text=TTLocalizer.ChineseCheckersStartButton, text_fg=(1, 1, 0.65, 1), text_pos=(0, -.23), text_scale=0.6, image=(self.upButton, self.downButton, self.rolloverButton), image_color=(1, 0, 0, 1), image_scale=(20, 1, 11), pos=(0.92, 0, 0.1), scale=0.15, command=lambda self = self: self.startButtonPushed())
        return

    def enableLeaveButton(self):
        self.leaveButton = DirectButton(relief=None, text=TTLocalizer.ChineseCheckersQuitButton, text_fg=(1, 1, 0.65, 1), text_pos=(0, -.13), text_scale=0.5, image=(self.upButton, self.downButton, self.rolloverButton), image_color=(1, 0, 0, 1), image_scale=(20, 1, 11), pos=(0.92, 0, 0.4), scale=0.15, command=lambda self = self: self.exitButtonPushed())
        return

    def enableTurnScreenText(self, player):
        self.yourTurnBlinker.finish()
        playerOrder = [1,
         4,
         2,
         5,
         3,
         6]
        message1 = TTLocalizer.ChineseCheckersIts
        if self.turnText != None:
            self.turnText.destroy()
        if player == self.playerNum:
            message2 = TTLocalizer.ChineseCheckersYourTurn
            color = (0, 0, 0, 1)
        elif player == 1:
            message2 = TTLocalizer.ChineseCheckersGreenTurn
            color = self.playerColors[0]
        elif player == 2:
            message2 = TTLocalizer.ChineseCheckersYellowTurn
            color = self.playerColors[1]
        elif player == 3:
            message2 = TTLocalizer.ChineseCheckersPurpleTurn
            color = self.playerColors[2]
        elif player == 4:
            message2 = TTLocalizer.ChineseCheckersBlueTurn
            color = self.playerColors[3]
        elif player == 5:
            message2 = TTLocalizer.ChineseCheckersPinkTurn
            color = self.playerColors[4]
        elif player == 6:
            message2 = TTLocalizer.ChineseCheckersRedTurn
            color = self.playerColors[5]
        self.turnText = OnscreenText(text=message1 + message2, pos=(-0.8, -0.5), scale=0.092, fg=color, align=TextNode.ACenter, mayChange=1)
        if player == self.playerNum:
            self.yourTurnBlinker = Sequence()
            self.yourTurnBlinker.append(LerpScaleInterval(self.turnText, 0.6, 1.045, 1))
            self.yourTurnBlinker.append(LerpScaleInterval(self.turnText, 0.6, 1, 1.045))
            self.yourTurnBlinker.loop()
        return

    def startButtonPushed(self):
        self.sendUpdate('requestBegin')
        self.startButton.hide()
        self.clockNode.stop()
        self.clockNode.hide()

    def exitButtonPushed(self):
        self.fsm.request('gameOver')
        self.table.fsm.request('off')
        self.clockNode.stop()
        self.clockNode.hide()
        self.table.sendUpdate('requestExit')

    def mouseClick(self):
        messenger.send('wakeup')
        if self.isMyTurn == True and self.inGame == True:
            mpos = base.mouseWatcherNode.getMouse()
            self.pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())
            self.traverser.traverse(render)
            if self.myHandler.getNumEntries() > 0:
                self.myHandler.sortEntries()
                pickedObj = self.myHandler.getEntry(0).getIntoNodePath()
                pickedObj = pickedObj.getNetTag('GamePeiceLocator')
                if pickedObj:
                    self.handleClicked(int(pickedObj))

    def handleClicked(self, index):
        self.sound = Sequence(SoundInterval(self.clickSound))
        if self.moveList == []:
            if index not in self.mySquares:
                return
            self.moveList.append(index)
            if index in self.opposingPositions:
                self.isOpposing = True
            else:
                self.isOpposing = False
            self.blinker = Sequence()
            self.blinker.append(LerpColorInterval(self.locatorList[index], 0.7, self.playerColor - self.tintConstant, self.playerColor))
            self.blinker.append(LerpColorInterval(self.locatorList[index], 0.7, self.playerColor, self.playerColor - self.tintConstant))
            self.blinker.loop()
            self.sound.start()
        elif self.board.squareList[index].getState() == self.playerNum:
            for x in self.moveList:
                self.locatorList[x].setColor(1, 1, 1, 1)
                self.locatorList[x].hide()

            self.blinker.finish()
            self.blinker = Sequence()
            self.blinker.append(LerpColorInterval(self.locatorList[index], 0.7, self.playerColor - self.tintConstant, self.playerColor))
            self.blinker.append(LerpColorInterval(self.locatorList[index], 0.7, self.playerColor, self.playerColor - self.tintConstant))
            self.blinker.loop()
            self.sound.start()
            self.locatorList[self.moveList[0]].setColor(self.playerColor)
            self.locatorList[self.moveList[0]].show()
            self.moveList = []
            self.moveList.append(index)
            if index in self.opposingPositions:
                self.isOpposing = True
            else:
                self.isOpposing = False
        elif self.board.squareList[index].getState() != 0:
            return
        else:
            if len(self.moveList) == 1 and self.board.squareList[index].getState() == 0:
                if index in self.board.squareList[self.moveList[0]].getAdjacent():
                    for x in self.nonOpposingPositions:
                        if index in x:
                            return

                    self.moveList.append(index)
                    self.blinker.finish()
                    self.d_requestMove(self.moveList)
                    self.moveList = []
                    self.isMyTurn = False
                    self.sound.start()
            if len(self.moveList) >= 1:
                if index == self.moveList[len(self.moveList) - 1]:
                    for x in self.nonOpposingPositions:
                        if index in x:
                            return

                    if self.existsLegalJumpsFrom(index) == True:
                        self.blinker.finish()
                        self.d_requestMove(self.moveList)
                        self.moveList = []
                        self.isMyTurn = False
                        self.sound.start()
                elif self.checkLegalMove(self.board.getSquare(self.moveList[len(self.moveList) - 1]), self.board.getSquare(index)) == True:
                    if index not in self.board.squareList[self.moveList[len(self.moveList) - 1]].getAdjacent():
                        for x in self.nonOpposingPositions:
                            if self.existsLegalJumpsFrom(index) == False:
                                if index in x:
                                    return

                        self.moveList.append(index)
                        self.locatorList[index].setColor(self.playerColor - self.tintConstant - self.ghostConstant)
                        self.locatorList[index].show()
                        self.sound.start()
                        if self.existsLegalJumpsFrom(index) == False:
                            self.blinker.finish()
                            self.d_requestMove(self.moveList)
                            self.moveList = []
                            self.isMyTurn = False

    def existsLegalJumpsFrom(self, index):
        for x in self.board.squareList[index].getAdjacent():
            if x == None:
                pass
            elif x in self.moveList:
                pass
            elif self.board.getState(x) == 0:
                pass
            elif self.board.squareList[x].getAdjacent()[self.board.squareList[index].getAdjacent().index(x)] == None:
                pass
            elif self.board.getState(self.board.squareList[x].getAdjacent()[self.board.squareList[index].getAdjacent().index(x)]) == 0 and self.board.squareList[x].getAdjacent()[self.board.squareList[index].getAdjacent().index(x)] not in self.moveList:
                return True

        return False

    def checkLegalMove(self, firstSquare, secondSquare):
        if secondSquare.getNum() in firstSquare.getAdjacent():
            return True
        else:
            for x in firstSquare.getAdjacent():
                if x == None:
                    pass
                elif self.board.squareList[x].getState() == 0:
                    pass
                elif self.board.squareList[x].getAdjacent()[firstSquare.getAdjacent().index(x)] == secondSquare.getNum():
                    return True

            return False
        return

    def d_requestMove(self, moveList):
        self.sendUpdate('requestMove', [moveList])

    def setGameState(self, tableState, moveList):
        if moveList != []:
            self.animatePeice(tableState, moveList)
        else:
            self.updateGameState(tableState)

    def updateGameState(self, squares):
        self.board.setStates(squares)
        self.mySquares = []
        messenger.send('wakeup')
        for x in xrange(121):
            self.locatorList[x].clearColor()
            owner = self.board.squareList[x].getState()
            if owner == self.playerNum:
                self.mySquares.append(x)
            if owner == 0:
                self.locatorList[x].hide()
            else:
                self.locatorList[x].show()
            if owner == 1:
                self.locatorList[x].setColor(self.playerColors[0])
            elif owner == 2:
                self.locatorList[x].setColor(self.playerColors[1])
            elif owner == 3:
                self.locatorList[x].setColor(self.playerColors[2])
            elif owner == 4:
                self.locatorList[x].setColor(self.playerColors[3])
            elif owner == 5:
                self.locatorList[x].setColor(self.playerColors[4])
            elif owner == 6:
                self.locatorList[x].setColor(self.playerColors[5])

        self.mySquares.sort()
        self.checkForWin()

    def animatePeice(self, tableState, moveList):
        messenger.send('wakeup')
        gamePeiceForAnimation = loader.loadModel('phase_6/models/golf/checker_marble.bam')
        gamePeiceForAnimation.setColor(self.locatorList[moveList[0]].getColor())
        gamePeiceForAnimation.reparentTo(self.boardNode)
        gamePeiceForAnimation.setPos(self.locatorList[moveList[0]].getPos())
        self.locatorList[moveList[0]].hide()
        checkersPeiceTrack = Sequence()
        length = len(moveList)
        for x in xrange(length - 1):
            checkersPeiceTrack.append(Parallel(SoundInterval(self.moveSound), ProjectileInterval(gamePeiceForAnimation, endPos=self.locatorList[moveList[x + 1]].getPos(), duration=0.5)))

        checkersPeiceTrack.append(Func(gamePeiceForAnimation.removeNode))
        checkersPeiceTrack.append(Func(self.updateGameState, tableState))
        checkersPeiceTrack.start()

    def checkForWin(self):
        if self.playerNum == 1:
            if self.mySquares == self.startingPositions[3]:
                self.sendUpdate('requestWin', [])
        elif self.playerNum == 2:
            if self.mySquares == self.startingPositions[4]:
                self.sendUpdate('requestWin', [])
        elif self.playerNum == 3:
            if self.mySquares == self.startingPositions[5]:
                self.sendUpdate('requestWin', [])
        elif self.playerNum == 4:
            if self.mySquares == self.startingPositions[0]:
                self.sendUpdate('requestWin', [])
        elif self.playerNum == 5:
            if self.mySquares == self.startingPositions[1]:
                self.sendUpdate('requestWin', [])
        elif self.playerNum == 6:
            if self.mySquares == self.startingPositions[2]:
                self.sendUpdate('requestWin', [])

    def announceWin(self, avId):
        self.fsm.request('gameOver')

    def doRandomMove(self):
        if len(self.moveList) >= 2:
            self.blinker.finish()
            self.d_requestMove(self.moveList)
            self.moveList = []
            self.isMyTurn = False
            self.playSound = Sequence(SoundInterval(self.knockSound))
            self.playSound.start()
        else:
            import random
            move = []
            foundLegal = False
            self.blinker.pause()
            self.numRandomMoves += 1
            while not foundLegal:
                x = random.randint(0, 9)
                for y in self.board.getAdjacent(self.mySquares[x]):
                    if y != None and self.board.getState(y) == 0:
                        for zz in self.nonOpposingPositions:
                            if y not in zz:
                                move.append(self.mySquares[x])
                                move.append(y)
                                foundLegal = True
                                break

                        break

            if move == []:
                pass
            playSound = Sequence(SoundInterval(self.knockSound))
            playSound.start()
            self.d_requestMove(move)
            self.moveList = []
            self.isMyTurn = False
            if self.numRandomMoves >= 5:
                self.exitButtonPushed()
        return

    def doNothing(self):
        pass
class CogdoMazeGuiManager:

    def __init__(self, maze, bossCode):
        self.maze = maze
        self.root = NodePath('CogdoMazeGui')
        self.root.reparentTo(aspect2d)
        self.mazeMapGui = CogdoMazeMapGui(self.maze.collisionTable)
        if bossCode is not None:
            self._bossGui = CogdoMazeBossGui(bossCode)
        else:
            self._bossGui = None
        self._memoGui = CogdoMemoGui(self.root)
        self._memoGui.posNextToLaffMeter()
        self._presentGuiIval = None
        self._presentTimerIval = None
        self._hud = CogdoMazeHud()
        self._timer = None
        self._initMessageDisplay()
        return

    def _initTimer(self):
        self._timer = ToontownTimer()
        self._timer.hide()
        self._timer.posInTopRightCorner()

    def _initMessageDisplay(self):
        self.messageDisplay = CogdoGameMessageDisplay('CogdoMazeMessageDisplay', self.root, pos=Globals.MessageLabelPos)

    def destroy(self):
        ToontownIntervals.cleanup('present_gui')
        ToontownIntervals.cleanup('present_timer')
        ToontownIntervals.cleanup('present_memo')
        self._hud.destroy()
        self._hud = None
        self._memoGui.destroy()
        self._memoGui = None
        if self._bossGui is not None:
            self._bossGui.destroy()
            self._bossGui = None
        self.messageDisplay.destroy()
        self.messageDisplay = None
        self.destroyMazeMap()
        self.destroyTimer()
        if self._presentGuiIval:
            self._presentGuiIval.pause()
            self._presentGuiIval = None
        if self._presentTimerIval:
            self._presentTimerIval.pause()
            self._presentTimerIval = None
        return

    def destroyMazeMap(self):
        if hasattr(self, 'mazeMapGui') and self.mazeMapGui is not None:
            self.mazeMapGui.destroy()
            del self.mazeMapGui
        return

    def destroyTimer(self):
        if self._timer is not None:
            self._timer.stop()
            self._timer.destroy()
            self._timer = None
        return

    def showPickupCounter(self):
        ToontownIntervals.start(ToontownIntervals.getPresentGuiIval(self._memoGui, 'present_memo'))

    def startGame(self, firstMessage):
        self._presentGuiIval = ToontownIntervals.start(Sequence(ToontownIntervals.getPresentGuiIval(self._bossGui, '', startPos=(0, 0, -0.15)), Func(self.mazeMapGui.show), ToontownIntervals.getPulseLargerIval(self.mazeMapGui, '', scale=self.mazeMapGui.getScale()), Func(self.setMessage, firstMessage), name='present_gui'))

    def hideMazeMap(self):
        self.mazeMapGui.hide()

    def showBossGui(self):
        if self._bossGui is not None:
            self._bossGui.show()
        return

    def hideBossGui(self):
        if self._bossGui is not None:
            self._bossGui.hide()
        return

    def revealMazeMap(self):
        self.mazeMapGui.revealAll()

    def hideLock(self, lockIndex):
        self.mazeMapGui.hideLock(lockIndex)

    def showTimer(self, duration, timerExpiredCallback = None):
        if self._timer is None:
            self._initTimer()
        self._timer.setTime(duration)
        self._timer.countdown(duration, timerExpiredCallback)
        self._timer.show()
        self._presentTimerIval = ToontownIntervals.start(ToontownIntervals.getPresentGuiIval(self._timer, 'present_timer', startPos=(0, 0, 0.35)))
        return

    def hideTimer(self):
        if hasattr(self, 'timer') and self._timer is not None:
            self._timer.hide()
            self._timer.stop()
        return

    def setMessage(self, text, color = None, transition = 'fade'):
        self.messageDisplay.updateMessage(text, color, transition)

    def setMessageTemporary(self, text, time = 3.0):
        self.messageDisplay.showMessageTemporarily(text, time)

    def clearMessage(self):
        self.messageDisplay.updateMessage('')

    def setPickupCount(self, count):
        self._memoGui.setCount(count)

    def showBossCode(self, bossIndex):
        self._bossGui.showNumber(bossIndex)

    def showBossHit(self, bossIndex):
        self._bossGui.showHit(bossIndex)

    def showQuestArrow(self, toon, target, offset):
        self._hud.showQuestArrow(toon, target, offset)

    def hideQuestArrow(self):
        self._hud.hideQuestArrow()
예제 #9
0
class CogdoFlyingGuiManager:
    ClearMessageDisplayEventName = 'ClearMessageDisplayEvent'
    EagleTargetingLocalPlayerEventName = 'EagleTargetingLocalPlayerEvent'
    EagleAttackingLocalPlayerEventName = 'EagleAttackingLocalPlayerEvent'
    FirstPressOfCtrlEventName = 'FirstPressOfCtrlEvent'
    PickedUpFirstPropellerEventName = 'PickedUpFirstPropellerEvent'
    InvulnerableEventName = 'InvulnerableEvent'
    StartRunningOutOfTimeMusicEventName = 'StartRunningOutOfTimeEvent'

    def __init__(self, level):
        self._level = level
        self.root = NodePath('CogdoFlyingGui')
        self.root.reparentTo(aspect2d)
        self.root.stash()
        self.fuelGui = NodePath('CogdoFlyingFuelGui')
        self.fuelGui.reparentTo(base.a2dBottomLeft)
        self.fuelGui.stash()
        self.progressGui = NodePath('CogdoFlyingProgressGui')
        self.progressGui.reparentTo(base.a2dBottomRight)
        self.progressGui.stash()
        self._initTimer()
        self._initHud()
        self._initMessageDisplay()
        self.sentTimeRunningOutMessage = False
        self._refuelGui = CogdoFlyingFuelGui(self.fuelGui)
        self._progressGui = CogdoFlyingProgressGui(self.progressGui,
                                                   self._level)

    def _initHud(self):
        self._memoGui = CogdoMemoGui(self.root, 'memo_card')
        self._memoGui.posNextToLaffMeter()

    def _initTimer(self):
        self._timer = ToontownTimer()
        self._timer.hide()
        self._timer.posInTopRightCorner()

    def _initMessageDisplay(self):
        audioMgr = base.cogdoGameAudioMgr
        sound = audioMgr.createSfx('popupHelpText')
        self._messageDisplay = CogdoGameMessageDisplay(
            'CogdoFlyingMessageDisplay', self.root, sfx=sound)

    def destroyTimer(self):
        if self._timer is not None:
            self._timer.stop()
            self._timer.destroy()
            self._timer = None
        return

    def onstage(self):
        self.root.unstash()
        self.fuelGui.unstash()
        self.progressGui.unstash()
        self._refuelGui.hide()
        self._progressGui.hide()

    def presentProgressGui(self):
        ToontownIntervals.start(
            ToontownIntervals.getPresentGuiIval(self._progressGui,
                                                'present_progress_gui'))

    def presentRefuelGui(self):
        ToontownIntervals.start(
            ToontownIntervals.getPresentGuiIval(self._refuelGui,
                                                'present_fuel_gui'))

    def presentTimerGui(self):
        ToontownIntervals.start(
            ToontownIntervals.getPresentGuiIval(self._timer,
                                                'present_timer_gui'))

    def presentMemoGui(self):
        ToontownIntervals.start(
            ToontownIntervals.getPresentGuiIval(self._memoGui,
                                                'present_memo_gui'))

    def offstage(self):
        self.root.stash()
        self.fuelGui.stash()
        self.progressGui.stash()
        self._refuelGui.hide()
        self._progressGui.hide()
        self.hideTimer()

    def getTimeLeft(self):
        return Globals.Gameplay.SecondsUntilGameOver - self._timer.getElapsedTime(
        )

    def isTimeRunningOut(self):
        return self.getTimeLeft() < Globals.Gameplay.TimeRunningOutSeconds

    def startTimer(self,
                   duration,
                   timerExpiredCallback=None,
                   keepHidden=False):
        if self._timer is None:
            self._initTimer()
        self._timer.setTime(duration)
        self._timer.countdown(duration, timerExpiredCallback)
        if keepHidden:
            self.hideTimer()
        else:
            self.showTimer()
        return

    def stopTimer(self):
        if hasattr(self, '_timer') and self._timer is not None:
            self.hideTimer()
            self._timer.stop()
        return

    def showTimer(self):
        self._timer.show()

    def hideTimer(self):
        self._timer.hide()

    def forceTimerDone(self):
        if self._timer.countdownTask != None:
            self._timer.countdownTask.duration = 0
        return

    def showRefuelGui(self):
        self._refuelGui.show()

    def hideRefuelGui(self):
        self._refuelGui.hide()

    def setMessage(self, text, color=None, transition='fade'):
        self._messageDisplay.updateMessage(text, color, transition)

    def setTemporaryMessage(self, text, duration=3.0, color=None):
        self._messageDisplay.showMessageTemporarily(text, duration, color)

    def setFuel(self, fuel):
        self._refuelGui.setFuel(fuel)

    def resetBlades(self):
        self._refuelGui.resetBlades()

    def setBlades(self, fuelState):
        self._refuelGui.setBlades(fuelState)

    def bladeLost(self):
        self._refuelGui.bladeLost()

    def setPropellerSpinRate(self, newRate):
        self._refuelGui.setPropellerSpinRate(newRate)

    def setMemoCount(self, score):
        self._memoGui.setCount(score)

    def addToonToProgressMeter(self, toon):
        self._progressGui.addToon(toon)

    def removeToonFromProgressMeter(self, toon):
        self._progressGui.removeToon(toon)

    def update(self):
        if self.isTimeRunningOut() and not self.sentTimeRunningOutMessage:
            messenger.send(
                CogdoFlyingGuiManager.StartRunningOutOfTimeMusicEventName)
            self.sentTimeRunningOutMessage = True
        self._refuelGui.update()
        self._progressGui.update()

    def destroy(self):
        ToontownIntervals.cleanup('present_fuel_gui')
        ToontownIntervals.cleanup('present_timer_gui')
        ToontownIntervals.cleanup('present_memo_gui')
        ToontownIntervals.cleanup('present_progress_gui')
        self._refuelGui.destroy()
        self._refuelGui = None
        self._memoGui.destroy()
        self._memoGui = None
        self._progressGui.destroy()
        self._progressGui = None
        self.destroyTimer()
        self._messageDisplay.destroy()
        self._messageDisplay = None
        self.root.removeNode()
        self.root = None
        self.fuelGui.removeNode()
        self.fuelGui = None
        self.progressGui.removeNode()
        self.progressGui = None
        return
class CogdoFlyingGuiManager:
    ClearMessageDisplayEventName = 'ClearMessageDisplayEvent'
    EagleTargetingLocalPlayerEventName = 'EagleTargetingLocalPlayerEvent'
    EagleAttackingLocalPlayerEventName = 'EagleAttackingLocalPlayerEvent'
    FirstPressOfCtrlEventName = 'FirstPressOfCtrlEvent'
    PickedUpFirstPropellerEventName = 'PickedUpFirstPropellerEvent'
    InvulnerableEventName = 'InvulnerableEvent'
    StartRunningOutOfTimeMusicEventName = 'StartRunningOutOfTimeEvent'

    def __init__(self, level):
        self._level = level
        self.root = NodePath('CogdoFlyingGui')
        self.root.reparentTo(aspect2d)
        self.root.stash()
        self.fuelGui = NodePath('CogdoFlyingFuelGui')
        self.fuelGui.reparentTo(base.a2dBottomLeft)
        self.fuelGui.stash()
        self.progressGui = NodePath('CogdoFlyingProgressGui')
        self.progressGui.reparentTo(base.a2dBottomRight)
        self.progressGui.stash()
        self._initTimer()
        self._initHud()
        self._initMessageDisplay()
        self.sentTimeRunningOutMessage = False
        self._refuelGui = CogdoFlyingFuelGui(self.fuelGui)
        self._progressGui = CogdoFlyingProgressGui(self.progressGui, self._level)

    def _initHud(self):
        self._memoGui = CogdoMemoGui(self.root, 'memo_card')
        self._memoGui.posNextToLaffMeter()

    def _initTimer(self):
        self._timer = ToontownTimer()
        self._timer.hide()
        self._timer.posInTopRightCorner()

    def _initMessageDisplay(self):
        audioMgr = base.cogdoGameAudioMgr
        sound = audioMgr.createSfx('popupHelpText')
        self._messageDisplay = CogdoGameMessageDisplay('CogdoFlyingMessageDisplay', self.root, sfx=sound)

    def destroyTimer(self):
        if self._timer is not None:
            self._timer.stop()
            self._timer.destroy()
            self._timer = None
        return

    def onstage(self):
        self.root.unstash()
        self.fuelGui.unstash()
        self.progressGui.unstash()
        self._refuelGui.hide()
        self._progressGui.hide()

    def presentProgressGui(self):
        ToontownIntervals.start(ToontownIntervals.getPresentGuiIval(self._progressGui, 'present_progress_gui'))

    def presentRefuelGui(self):
        ToontownIntervals.start(ToontownIntervals.getPresentGuiIval(self._refuelGui, 'present_fuel_gui'))

    def presentTimerGui(self):
        ToontownIntervals.start(ToontownIntervals.getPresentGuiIval(self._timer, 'present_timer_gui'))

    def presentMemoGui(self):
        ToontownIntervals.start(ToontownIntervals.getPresentGuiIval(self._memoGui, 'present_memo_gui'))

    def offstage(self):
        self.root.stash()
        self.fuelGui.stash()
        self.progressGui.stash()
        self._refuelGui.hide()
        self._progressGui.hide()
        self.hideTimer()

    def getTimeLeft(self):
        return Globals.Gameplay.SecondsUntilGameOver - self._timer.getElapsedTime()

    def isTimeRunningOut(self):
        return self.getTimeLeft() < Globals.Gameplay.TimeRunningOutSeconds

    def startTimer(self, duration, timerExpiredCallback = None, keepHidden = False):
        if self._timer is None:
            self._initTimer()
        self._timer.setTime(duration)
        self._timer.countdown(duration, timerExpiredCallback)
        if keepHidden:
            self.hideTimer()
        else:
            self.showTimer()
        return

    def stopTimer(self):
        if hasattr(self, '_timer') and self._timer is not None:
            self.hideTimer()
            self._timer.stop()
        return

    def showTimer(self):
        self._timer.show()

    def hideTimer(self):
        self._timer.hide()

    def forceTimerDone(self):
        if self._timer.countdownTask != None:
            self._timer.countdownTask.duration = 0
        return

    def showRefuelGui(self):
        self._refuelGui.show()

    def hideRefuelGui(self):
        self._refuelGui.hide()

    def setMessage(self, text, color = None, transition = 'fade'):
        self._messageDisplay.updateMessage(text, color, transition)

    def setTemporaryMessage(self, text, duration = 3.0, color = None):
        self._messageDisplay.showMessageTemporarily(text, duration, color)

    def setFuel(self, fuel):
        self._refuelGui.setFuel(fuel)

    def resetBlades(self):
        self._refuelGui.resetBlades()

    def setBlades(self, fuelState):
        self._refuelGui.setBlades(fuelState)

    def bladeLost(self):
        self._refuelGui.bladeLost()

    def setPropellerSpinRate(self, newRate):
        self._refuelGui.setPropellerSpinRate(newRate)

    def setMemoCount(self, score):
        self._memoGui.setCount(score)

    def addToonToProgressMeter(self, toon):
        self._progressGui.addToon(toon)

    def removeToonFromProgressMeter(self, toon):
        self._progressGui.removeToon(toon)

    def update(self):
        if self.isTimeRunningOut() and not self.sentTimeRunningOutMessage:
            messenger.send(CogdoFlyingGuiManager.StartRunningOutOfTimeMusicEventName)
            self.sentTimeRunningOutMessage = True
        self._refuelGui.update()
        self._progressGui.update()

    def destroy(self):
        ToontownIntervals.cleanup('present_fuel_gui')
        ToontownIntervals.cleanup('present_timer_gui')
        ToontownIntervals.cleanup('present_memo_gui')
        ToontownIntervals.cleanup('present_progress_gui')
        self._refuelGui.destroy()
        self._refuelGui = None
        self._memoGui.destroy()
        self._memoGui = None
        self._progressGui.destroy()
        self._progressGui = None
        self.destroyTimer()
        self._messageDisplay.destroy()
        self._messageDisplay = None
        self.root.removeNode()
        self.root = None
        self.fuelGui.removeNode()
        self.fuelGui = None
        self.progressGui.removeNode()
        self.progressGui = None
        return