コード例 #1
0
 def __init__(self, doneEvent = None):
     FSM.__init__(self, 'PartyPlannerFSM')
     DirectFrame.__init__(self)
     self.doneEvent = doneEvent
     self.stateArray = ['Off',
      'Welcome',
      'PartyEditor',
      'Guests',
      'Date',
      'Time',
      'Invitation',
      'Farewell']
     self.partyTime = base.cr.toontownTimeManager.getCurServerDateTime()
     self.partyNowTime = base.cr.toontownTimeManager.getCurServerDateTime()
     minutesToNextFifteen = 15 - self.partyTime.minute % 15
     self.cleanPartyTime = self.partyTime + timedelta(minutes=minutesToNextFifteen, seconds=-self.partyTime.second)
     self.partyTime = self.cleanPartyTime
     self.guests = []
     self.isPrivate = False
     self.selectedCalendarGuiDay = None
     self.gui = loader.loadModel('phase_4/models/parties/partyPlannerGUI')
     self.partyDuration = timedelta(hours=PartyGlobals.DefaultPartyDuration)
     self.timeTypeToMaxValue = {'hour': 23,
      'minute': 59}
     self.timeTypeToChangeAmount = {'hour': (1, -1),
      'minute': (15, -15),
      'ampm': (1, -1)}
     self.partyInfo = None
     self.asapMinuteRounding = base.config.GetInt('party-asap-minute-rounding', PartyGlobals.PartyPlannerAsapMinuteRounding)
     self.load()
     self.request('Welcome')
     return
コード例 #2
0
 def __init__(self, repairGame, name, startText):
     DirectFrame.__init__(self, parent = repairGame.gui, relief = None)
     FSM.FSM.__init__(self, '%sFSM' % name)
     self.defaultTransitions = {
         'Idle': [
             'Intro',
             'Final'],
         'Intro': [
             'Game',
             'Idle',
             'Final'],
         'Game': [
             'Outro',
             'Idle',
             'Final'],
         'Outro': [
             'Idle',
             'Final'],
         'Final': [] }
     self.name = name
     self.repairGame = repairGame
     self.startText = startText
     self._initVars()
     self._initAudio()
     self._initVisuals()
     self._initIntervals()
     self.request('Idle')
コード例 #3
0
 def show(self):
     self.reparentTo(self.parent)
     self.setPos(0.1, 0, -0.018)
     newParent = self.parent.getParent().getParent()
     self.wrtReparentTo(newParent)
     if self.whosePartyLabel['text'] == ' ':
         host = base.cr.identifyAvatar(self.partyInfo.hostId)
         if host:
             name = host.getName()
             self.whosePartyLabel['text'] = name
     if self.whenTextLabel['text'] == ' ':
         time = myStrftime(self.partyInfo.startTime)
         self.whenTextLabel['text'] = time
     if self.partyStatusLabel['text'] == ' ':
         if self.partyInfo.status == PartyGlobals.PartyStatus.Cancelled:
             self.partyStatusLabel['text'] = TTLocalizer.CalendarPartyCancelled
         elif self.partyInfo.status == PartyGlobals.PartyStatus.Finished:
             self.partyStatusLabel['text'] = TTLocalizer.CalendarPartyFinished
         elif self.partyInfo.status == PartyGlobals.PartyStatus.Started:
             self.partyStatusLabel['text'] = TTLocalizer.CalendarPartyGo
         elif self.partyInfo.status == PartyGlobals.PartyStatus.NeverStarted:
             self.partyStatusLabel['text'] = TTLocalizer.CalendarPartyNeverStarted
         else:
             self.partyStatusLabel['text'] = TTLocalizer.CalendarPartyGetReady
     DirectFrame.show(self)
コード例 #4
0
 def _createFarewellPage(self):
     page = DirectFrame(self.frame)
     page.setName('PartyPlannerFarewellPage')
     self.confirmTitleLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerConfirmationAllOkTitle, textMayChange=True, pos=self.gui.find('**/title_locator').getPos(), scale=self.titleScale)
     pos = self.gui.find('**/step_07_close_text_locator').getPos()
     self.closePlannerButton = DirectButton(parent=page, relief=None, geom=(self.gui.find('**/close_up'), self.gui.find('**/close_down'), self.gui.find('**/close_rollover')), text=TTLocalizer.PartyPlannerClosePlanner, text_scale=0.055, text_pos=(pos[0], pos[2]), command=self.__acceptExit)
     return page
コード例 #5
0
ファイル: LaffMeter.py プロジェクト: OldToontown/OldToontown
 def destroy(self):
     if self.av:
         ToontownIntervals.cleanup(self.av.uniqueName('laffMeterBoing') + '-' + str(self.this))
         ToontownIntervals.cleanup(self.av.uniqueName('laffMeterBoing') + '-' + str(self.this) + '-play')
         self.ignore(self.av.uniqueName('hpChange'))
     
     del self.style
     del self.av
     del self.hp
     del self.maxHp
     if self.isToon:
         del self.frown
         del self.smile
         del self.openSmile
         del self.tooth1
         del self.tooth2
         del self.tooth3
         del self.tooth4
         del self.tooth5
         del self.tooth6
         del self.teeth
         del self.fractions
         del self.maxLabel
         del self.hpLabel
     
     DirectFrame.destroy(self)
コード例 #6
0
ファイル: craftingGui.py プロジェクト: grimfang/OWP_Miner
    def __init__(self):
        self.itemFrame = DirectScrolledFrame(
            text="Inventory",
            text_scale=0.25,
            text_pos=(0, 0.75, 0),
            text_bg=(1, 1, 1, 1),
            # make the frame occupy the whole window
            frameSize=(-0.6, 0.6, -0.8, 0.8),
            pos=(-0.7, 0, 0),
            # make the canvas as big as the frame
            canvasSize=(-0.6, 0.6, -0.8, 0.8),
            # set the frames color to white
            frameColor=(1, 1, 1, 1),
        )
        self.itemList = []

        self.craftFrame = DirectFrame(
            text="Crafting",
            text_scale=0.25,
            text_pos=(0, 0.75, 0),
            text_bg=(1, 1, 1, 1),
            # make the frame occupy the whole window
            frameSize=(-0.6, 0.6, -0.8, 0.8),
            pos=(0.7, 0, 0),
            # set the frames color to white
            frameColor=(1, 1, 1, 1),
        )
        self.craftDrop = DirectFrame(
            text="drop ore",
            text_scale=0.1,
            pos=(0, 0.4, 0),
            frameSize=(-0.25, 0.25, -0.25, 0.25),
            frameColor=(1, 0, 0, 1),
        )
        self.craftDrop.reparentTo(self.craftFrame)
コード例 #7
0
 def destroy(self):
     ToontownIntervals.cleanup('memocount_pulse')
     self._countLabel.removeNode()
     del self._countLabel
     self._memoIcon.removeNode()
     del self._memoIcon
     DirectFrame.destroy(self)
コード例 #8
0
    def __init__(self, mazeCollTable, maskResolution = None, radiusRatio = None, bgColor = (0.8, 0.8, 0.8), fgColor = (0.5, 0.5, 0.5, 1.0)):
        DirectFrame.__init__(self, relief=None, state=DGG.NORMAL, sortOrder=DGG.BACKGROUND_SORT_INDEX)
        self.hide()
        self._bgColor = bgColor
        self._fgColor = fgColor
        self._mazeCollTable = mazeCollTable
        self._mazeWidth = len(self._mazeCollTable[0])
        self._mazeHeight = len(self._mazeCollTable)
        self._maskResolution = maskResolution or DEFAULT_MASK_RESOLUTION
        if radiusRatio is None:
            self._radius = self._maskResolution * DEFAULT_RADIUS_RATIO
        else:
            self._radius = self._maskResolution * radiusRatio
        self._revealedCells = []
        for y in xrange(self._mazeHeight):
            self._revealedCells.append([])
            for u in xrange(self._mazeWidth):
                self._revealedCells[y].append(False)

        self._revealFunctions = {MazeRevealType.SmoothCircle: self._revealSmoothCircle,
         MazeRevealType.HardCircle: self._revealHardCircle,
         MazeRevealType.Square: self._revealSquare}
        self._revealFunction = MAZE_REVEAL_TYPE
        self.map = self._createMapTextureCard()
        self.map.reparentTo(self)
        self.maskedLayer = self.attachNewNode('maskedLayer')
        self.mask = self._createMaskTextureCard()
        self.mask.reparentTo(self)
        self.visibleLayer = self.attachNewNode('visibleLayer')
        self._laffMeterModel = loader.loadModel('phase_3/models/gui/laff_o_meter')
        self._toon2marker = {}
        return
コード例 #9
0
 def __init__(self, doneEvent):
     self.doneEvent = doneEvent
     DirectFrame.__init__(self)
     self.reparentTo(aspect2d)
     self.setPos(0.0, 0.0, 0.16)
     self.stash()
     publicPartyGui = loader.loadModel('phase_4/models/parties/publicPartyGUI')
     self.frame = DirectFrame(parent=self, geom=publicPartyGui.find('**/activities_background'), geom_pos=(-0.8, 0.0, 0.2), geom_scale=2.0, relief=None)
     self.earnedLabel = DirectLabel(parent=self, relief=None, text=str(0), text_align=TextNode.ACenter, text_pos=(0.0, -0.07), text_scale=0.2, text_fg=(0.95, 0.95, 0.0, 1.0), text_font=ToontownGlobals.getSignFont(), textMayChange=True, image=DirectGuiGlobals.getDefaultDialogGeom(), image_scale=(0.33, 1.0, 0.33), pos=(-0.3, 0.0, 0.2), scale=0.9)
     purchaseModels = loader.loadModel('phase_4/models/gui/purchase_gui')
     jarImage = purchaseModels.find('**/Jar')
     self.jarLabel = DirectLabel(parent=self, relief=None, text=str(0), text_align=TextNode.ACenter, text_pos=(0.0, -0.07), text_scale=0.2, text_fg=JellybeanRewardGui.JarLabelTextColor, text_font=ToontownGlobals.getSignFont(), textMayChange=True, image=jarImage, scale=0.7, pos=(0.3, 0.0, 0.17))
     purchaseModels.removeNode()
     del purchaseModels
     jarImage.removeNode()
     del jarImage
     self.messageLabel = DirectLabel(parent=self, relief=None, text='', text_align=TextNode.ALeft, text_wordwrap=16.0, text_scale=0.07, pos=(-0.52, 0.0, -0.1), textMayChange=True)
     self.doubledJellybeanLabel = DirectLabel(parent=self, relief=None, text=TTLocalizer.PartyRewardDoubledJellybean, text_align=TextNode.ACenter, text_wordwrap=12.0, text_scale=0.09, text_fg=(1.0, 0.125, 0.125, 1.0), pos=(0.0, 0.0, -0.465), textMayChange=False)
     self.doubledJellybeanLabel.hide()
     self.closeButton = DirectButton(parent=self, relief=None, text=TTLocalizer.PartyJellybeanRewardOK, text_align=TextNode.ACenter, text_scale=0.065, text_pos=(0.0, -0.625), geom=(publicPartyGui.find('**/startButton_up'),
      publicPartyGui.find('**/startButton_down'),
      publicPartyGui.find('**/startButton_rollover'),
      publicPartyGui.find('**/startButton_inactive')), geom_pos=(-0.39, 0.0, 0.125), command=self._close)
     publicPartyGui.removeNode()
     del publicPartyGui
     self.countSound = base.loadSfx('phase_13/audio/sfx/tick_counter_short.mp3')
     self.overMaxSound = base.loadSfx('phase_13/audio/sfx/tick_counter_overflow.mp3')
     return
コード例 #10
0
ファイル: Transitions.py プロジェクト: frostbane/panda3d
    def loadLetterbox(self):
        if not self.letterbox:
            # We create a DirectFrame for the fade polygon, instead of
            # simply loading the polygon model and using it directly,
            # so that it will also obscure mouse events for objects
            # positioned behind it.
            self.letterbox = NodePath("letterbox")
            # Allow fade in and out of the bars
            self.letterbox.setTransparency(1)

            # Allow DirectLabels to be parented to the letterbox sensibly
            self.letterbox.setBin('unsorted', 0)

            # Allow a custom look to the letterbox graphic.

            # TODO: This model isn't available everywhere.  We should
            # pass it in as a parameter.
            button = loader.loadModel('models/gui/toplevel_gui',
                                      okMissing = True)

            barImage = None
            if button:
                barImage = button.find('**/generic_button')

            self.letterboxTop = DirectFrame(
                parent = self.letterbox,
                guiId = 'letterboxTop',
                relief = DGG.FLAT,
                state = DGG.NORMAL,
                frameColor = (0, 0, 0, 1),
                borderWidth = (0, 0),
                frameSize = (-1, 1, 0, 0.2),
                pos = (0, 0, 0.8),
                image = barImage,
                image_scale = (2.25,1,.5),
                image_pos = (0,0,.1),
                image_color = (0.3,0.3,0.3,1),
                sortOrder = 0,
                )
            self.letterboxBottom = DirectFrame(
                parent = self.letterbox,
                guiId = 'letterboxBottom',
                relief = DGG.FLAT,
                state = DGG.NORMAL,
                frameColor = (0, 0, 0, 1),
                borderWidth = (0, 0),
                frameSize = (-1, 1, 0, 0.2),
                pos = (0, 0, -1),
                image = barImage,
                image_scale = (2.25,1,.5),
                image_pos = (0,0,.1),
                image_color = (0.3,0.3,0.3,1),
                sortOrder = 0,
                )

            # masad: always place these at the bottom of render
            self.letterboxTop.setBin('sorted',0)
            self.letterboxBottom.setBin('sorted',0)
            self.letterbox.reparentTo(render2d, -1)
            self.letterboxOff(0)
コード例 #11
0
ファイル: FriendsList.py プロジェクト: coginvasion/src
 def __init__(self):
     DirectFrame.__init__(self, parent=base.a2dTopRight, pos=(-0.25, 0.0, -0.46))
     gui = loader.loadModel('phase_3.5/models/gui/friendslist_gui.bam')
     self['image'] = gui.find('**/FriendsBox_Open')
     self.headingText = OnscreenText(text='', parent=self, pos=(0.01, 0.2), fg=(0.1, 0.1, 0.4, 1.0), scale=0.04)
     self.frameForNames = DirectScrolledList(frameSize=(0.0, 0.35, 0, 0.35), incButton_geom=(gui.find('**/FndsLst_ScrollUp'),
      gui.find('**/FndsLst_ScrollDN'),
      gui.find('**/FndsLst_ScrollUp_Rllvr'),
      gui.find('**/FndsLst_ScrollUp')), incButton_relief=None, incButton_hpr=(0, 0, 180), incButton_pos=(0.17, 0, -0.04), decButton_geom=(gui.find('**/FndsLst_ScrollUp'),
      gui.find('**/FndsLst_ScrollDN'),
      gui.find('**/FndsLst_ScrollUp_Rllvr'),
      gui.find('**/FndsLst_ScrollUp')), decButton_relief=None, decButton_pos=(0.17, 0, 0.395), pos=(-0.1625, 0.0, -0.27), parent=self, numItemsVisible=9, forceHeight=0.04, itemFrame_frameSize=(-0.15, 0.15, 0, -0.35), itemFrame_pos=(0, 0, 0.3275), itemFrame_relief=None, relief=None)
     self.fwdBtn = DirectButton(geom=(gui.find('**/Horiz_Arrow_UP'),
      gui.find('**/Horiz_Arrow_DN'),
      gui.find('**/Horiz_Arrow_Rllvr'),
      gui.find('**/Horiz_Arrow_UP')), relief=None, parent=self, pos=(0.17, 0.0, -0.38), command=self.doState)
     self.backBtn = DirectButton(geom=(gui.find('**/Horiz_Arrow_UP'),
      gui.find('**/Horiz_Arrow_DN'),
      gui.find('**/Horiz_Arrow_Rllvr'),
      gui.find('**/Horiz_Arrow_UP')), relief=None, parent=self, pos=(-0.15, 0.0, -0.38), hpr=(180, 0, 0), command=self.doState)
     self.closeBtn = DirectButton(geom=CIGlobals.getCancelBtnGeom(), relief=None, parent=self, command=self.exitClicked)
     self.closeBtn.setPos(0.015, 0.0, -0.375)
     gui.removeNode()
     del gui
     self.hide()
     self.friends = {}
     self.onlineFriends = {}
     self.fsm = ClassicFSM.ClassicFSM('FriendsList', [State.State('off', self.enterOff, self.exitOff), State.State('onlineFriendsList', self.enterOnlineFriendsList, self.exitOnlineFriendsList), State.State('allFriendsList', self.enterAllFriendsList, self.exitAllFriendsList)], 'off', 'off')
     self.fsm.enterInitialState()
     self.accept('gotFriendsList', self.handleFriendsList)
     return
コード例 #12
0
ファイル: actor.py プロジェクト: NanoDano/cookbook
    def __init__(self):
        ShowBase.__init__(self)
 
        # Load the environment model.
        self.environ = self.loader.loadModel("models/environment")
        # Reparent the model to render.
        self.environ.reparentTo(self.render)
        # Apply scale and position transforms on the model.
        self.environ.setScale(0.25, 0.25, 0.25)
        self.environ.setPos(-8, 42, 0)
 
        # Add the spinCameraTask procedure to the task manager.
        self.taskMgr.add(self.spinCameraTask, "SpinCameraTask")
 
        # Load and transform the panda actor.
        self.pandaActor = Actor("models/panda-model",
                                {"walk": "models/panda-walk4"})
        self.pandaActor.setScale(0.005, 0.005, 0.005)
        self.pandaActor.reparentTo(self.render)
        # Loop its animation.
        self.pandaActor.loop("walk")
        
        
 
        myFrame = DirectFrame(frameColor=(0, 0, 0, 1),
            frameSize=(-1, 1, -1, 1))
        myFrame.setPos(-0.5, 0, -0.5)
コード例 #13
0
ファイル: QuestMap.py プロジェクト: vincent15k/Toontown-House
    def __init__(self, av, **kw):
        DirectFrame.__init__(self, relief=None, sortOrder=50)
        self.initialiseoptions(QuestMap)
        self.container = DirectFrame(parent=self, relief=None)
        self.marker = DirectFrame(parent=self.container, relief=None)
        self.cogInfoFrame = DirectFrame(parent=self.container, relief=None)
        cm = CardMaker('bg')
        cm.setFrame(-0.5, 0.5, -0.5, 0.5)
        bg = self.cogInfoFrame.attachNewNode(cm.generate())
        bg.setTransparency(1)
        bg.setColor(0.5, 0.5, 0.5, 0.5)
        bg.setBin('fixed', 0)
        self.cogInfoFrame['geom'] = bg
        self.cogInfoFrame['geom_pos'] = (0, 0, 0)
        self.cogInfoFrame['geom_scale'] = (6, 1, 2)
        self.cogInfoFrame.setScale(0.05)
        self.cogInfoFrame.setPos(0, 0, 0.6)
        self.buildingMarkers = []
        self.av = av
        self.wantToggle = base.config.GetBool('want-toggle-quest-map', True)
        self.updateMarker = True
        self.cornerPosInfo = None
        self.hqPosInfo = None
        self.fishingSpotInfo = None
        self.load()
        self.setScale(1.5)
        bg.removeNode()
        self.hoodId = None
        self.zoneId = None
        self.suitPercentage = {}
        for currHoodInfo in SuitPlannerBase.SuitPlannerBase.SuitHoodInfo:
            tracks = currHoodInfo[SuitPlannerBase.SuitPlannerBase.SUIT_HOOD_INFO_TRACK]
            self.suitPercentage[currHoodInfo[SuitPlannerBase.SuitPlannerBase.SUIT_HOOD_INFO_ZONE]] = tracks

        return
コード例 #14
0
 def __init__(self, parent):
     DirectFrame.__init__(self, relief=None, state=DGG.NORMAL, sortOrder=DGG.BACKGROUND_SORT_INDEX)
     self.reparentTo(parent)
     self.active = 0
     self._initModel()
     self._initIntervals()
     return
コード例 #15
0
ファイル: QuestMap.py プロジェクト: CalebSmith376/src
 def destroy(self):
     self.ignore('questPageUpdated')
     self.mapOpenButton.destroy()
     self.mapCloseButton.destroy()
     del self.mapOpenButton
     del self.mapCloseButton
     DirectFrame.destroy(self)
コード例 #16
0
ファイル: QuestMap.py プロジェクト: OldToontown/OldToontown
 def hide(self):
     taskMgr.remove('questMapInit')
     DirectFrame.hide(self)
     if self.container['image']:
         self.mapOpenButton.show()
     
     self.mapCloseButton.hide()
コード例 #17
0
 def createPage(self, section, subsection, fullFilename):
     upsellBackground = loader.loadModel("phase_3.5/models/gui/tt_m_gui_ign_newsStatusBackground")
     imageScaleX = self.FrameDimensions[1] - self.FrameDimensions[0]
     imageScaleY = self.FrameDimensions[3] - self.FrameDimensions[2]
     pageFrame = DirectFrame(
         frameColor=(1, 1, 1, 0),
         frameSize=self.FrameDimensions,
         image=upsellBackground,
         image_scale=(imageScaleX, 1, imageScaleY),
         relief=DGG.FLAT,
         parent=self,
         text="",
         text_scale=0.06,
         text_pos=(0, -0.4),
     )
     if "error_" in str(fullFilename):
         pageFrame["text"] = TTLocalizer.NewsPageErrorDownloadingFileCanStillRead % fullFilename[len("error_") :]
     else:
         quad = self.loadFlatQuad(fullFilename)
         if quad:
             quad.reparentTo(pageFrame)
         else:
             pageFrame["text"] = TTLocalizer.NewsPageErrorDownloadingFileCanStillRead % fullFilename
     self.loadRightArrow(section, subsection, pageFrame)
     self.loadLeftArrow(section, subsection, pageFrame)
     if section == 0 and subsection == 0:
         self.loadHomePageButtons(section, subsection, pageFrame)
     else:
         self.loadNavButtons(pageFrame)
         pageFrame.hide()
     return pageFrame
コード例 #18
0
 def __init__(self, parent, **kwargs):
     cm = CardMaker('Portrait')
     cm.setFrame(Vec4(-1, 1, -1, 1))
     b = SceneBuffer('worldmap-buffer', size = (512, 512), clearColor = Vec4(0.84999999999999998))
     b.camLens.setNear(0.001)
     b.camLens.setFar(5.0)
     b.camera.node().getDisplayRegion(0).setIncompleteRender(False)
     self.buffer = b
     shot = NodePath(cm.generate())
     shot.setTexture(b.getTexture(), 1)
     optiondefs = (('relief', None, None), ('geom', shot, None))
     self.defineoptions(kwargs, optiondefs)
     DirectFrame.__init__(self, parent)
     self.initialiseoptions(WorldMap)
     self.setTransparency(1)
     self.radius = 1.0
     self.camY = [
         -0.29999999999999999,
         0.25]
     self.tiltLimit = [ x * math.pi / 180 for x in (27, 33) ]
     self.mapBall = DecoratedMapBall('WorldMapArcBall', self, self.tiltLimit[1], mapSize = 242000, radius = self.radius, scrollFactor = 0.125, camera = b.camera, keepUpright = 1, mouseDownEvent = self.getMouseDownEvent(), mouseUpEvent = self.getMouseUpEvent())
     self.render = b.getSceneRoot()
     self.worldRoot = self.render.attachNewNode('world')
     self.worldRoot.setTransparency(1)
     self.ballRoot = self.worldRoot.attachNewNode('ballRoot')
     self.ballRoot.setY(self.radius / 2.0)
     self.mapBall.reparentTo(self.ballRoot)
     self.mapBall.setInternalHpr(Vec3(0, 90, 0))
     self.mapBall.setNorth(Vec3(0, 1, 0))
     self.mapBall.setY(self.radius)
     self.setZoom(0)
     self.addLocalAvDart()
     self._hasLocalShip = False
     self._fleets = []
     self._enabled = False
コード例 #19
0
ファイル: mainmenu.py プロジェクト: grimfang/pyweek21
    def __init__(self):
        self.frameMain = DirectFrame(
            image="gui/MenuBackground.png",
            image_scale=(1.7778, 1, 1),
            #image_pos=(0, 0, 0.25),
            frameSize=(
                base.a2dLeft, base.a2dRight,
                base.a2dTop, base.a2dBottom),
            frameColor=(0,0,0,0))
        self.frameMain.setTransparency(True)

        self.logo = DirectFrame(
            image="Logo.png",
            image_scale=0.45,
            image_pos=(0, 0, 0.35),
            frameSize=(
                base.a2dLeft, base.a2dRight,
                base.a2dTop, base.a2dBottom),
            frameColor=(0,0,0,0))
        self.logo.reparentTo(self.frameMain)

        btnGeom = "gui/button"

        self.btnStart = menuHelper.createButton(_("Start"), btnGeom, 0, -0.7, ["menu_start"])
        self.btnStart.reparentTo(self.frameMain)

        self.btnOptions = menuHelper.createButton(_("Options"), btnGeom, -1.0, -0.7, ["menu_options"])
        self.btnOptions.reparentTo(self.frameMain)

        self.btnQuit = menuHelper.createButton(_("Quit"), btnGeom, 1.0, -0.7, ["menu_quit"])
        self.btnQuit.reparentTo(self.frameMain)

        self.hide()
コード例 #20
0
 def load(self):
     gui = loader.loadModel("phase_3/models/gui/laff_o_meter")
     if self.isToon:
         hType = self.style.getType()
         if hType == "dog":
             headModel = gui.find("**/doghead")
         elif hType == "cat":
             headModel = gui.find("**/cathead")
         elif hType == "mouse":
             headModel = gui.find("**/mousehead")
         elif hType == "horse":
             headModel = gui.find("**/horsehead")
         elif hType == "rabbit":
             headModel = gui.find("**/bunnyhead")
         elif hType == "duck":
             headModel = gui.find("**/duckhead")
         elif hType == "monkey":
             headModel = gui.find("**/monkeyhead")
         elif hType == "bear":
             headModel = gui.find("**/bearhead")
         elif hType == "pig":
             headModel = gui.find("**/pighead")
         else:
             raise StandardError("unknown toon species: ", hType)
         self.color = self.style.getHeadColor()
         self.container["image"] = headModel
         self.container["image_color"] = self.color
         self.resetFrameSize()
         self.setScale(0.1)
         self.frown = DirectFrame(parent=self.container, relief=None, image=gui.find("**/frown"))
         self.smile = DirectFrame(parent=self.container, relief=None, image=gui.find("**/smile"))
         self.eyes = DirectFrame(parent=self.container, relief=None, image=gui.find("**/eyes"))
         self.openSmile = DirectFrame(parent=self.container, relief=None, image=gui.find("**/open_smile"))
         self.tooth1 = DirectFrame(parent=self.openSmile, relief=None, image=gui.find("**/tooth_1"))
         self.tooth2 = DirectFrame(parent=self.openSmile, relief=None, image=gui.find("**/tooth_2"))
         self.tooth3 = DirectFrame(parent=self.openSmile, relief=None, image=gui.find("**/tooth_3"))
         self.tooth4 = DirectFrame(parent=self.openSmile, relief=None, image=gui.find("**/tooth_4"))
         self.tooth5 = DirectFrame(parent=self.openSmile, relief=None, image=gui.find("**/tooth_5"))
         self.tooth6 = DirectFrame(parent=self.openSmile, relief=None, image=gui.find("**/tooth_6"))
         self.maxLabel = DirectLabel(
             parent=self.eyes,
             relief=None,
             pos=(0.442, 0, 0.051),
             text="120",
             text_scale=0.4,
             text_font=ToontownGlobals.getInterfaceFont(),
         )
         self.hpLabel = DirectLabel(
             parent=self.eyes,
             relief=None,
             pos=(-0.398, 0, 0.051),
             text="120",
             text_scale=0.4,
             text_font=ToontownGlobals.getInterfaceFont(),
         )
         self.teeth = [self.tooth6, self.tooth5, self.tooth4, self.tooth3, self.tooth2, self.tooth1]
         self.fractions = [0.0, 0.166666, 0.333333, 0.5, 0.666666, 0.833333]
     gui.removeNode()
     return
コード例 #21
0
 def __init__(self, name, barnacleGeom):
     self.config = RepairGlobals.Careening
     DirectFrame.__init__(self, parent = None, relief = None)
     self.barnacleGeom = barnacleGeom
     FSM.FSM.__init__(self, 'Barnacle_%sFSM' % name)
     self._initAudio()
     self._initVars()
     self._initGUI()
コード例 #22
0
 def destroy(self):
     taskMgr.remove('RepairGameGUIUpdate')
     DirectFrame.destroy(self)
     for b in self.buttons:
         self.buttons[b].destroy()
     
     del self.buttons
     del self.repairGame
コード例 #23
0
    def destroy(self):
        self.ignoreAll()

        if self.timer:
            self.timer.destroy()

        taskMgr.remove(self.taskName('runLaffCounter'))
        DirectFrame.destroy(self)
コード例 #24
0
 def destroy(self):
     self.movie.finish()
     del self.movie
     del self.winVoteSfx
     del self.noVoteSfx
     del self.upArrowSfx
     del self.loseVoteSfx
     del self.downArrowSfx
     DirectFrame.destroy(self)
コード例 #25
0
 def _createDatePage(self):
     page = DirectFrame(self.frame)
     page.setName('PartyPlannerDatePage')
     self.createDateTitleLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerDateTitle, pos=self.gui.find('**/title_locator').getPos(), scale=self.titleScale)
     pos = self.gui.find('**/step_06_sendInvitation_locator').getPos()
     self.makePartyNowButton = DirectButton(parent=page, relief=None, geom=(self.gui.find('**/send_up'), self.gui.find('**/send_down'), self.gui.find('**/send_rollover')), text=TTLocalizer.PartyPlannerPartyNow, text_pos=(pos[0], pos[2]), text_scale=0.05, command=self.__doMakePartyNow)
     curServerDate = base.cr.toontownTimeManager.getCurServerDateTime()
     self.calendarGuiMonth = CalendarGuiMonth(page, curServerDate, scale=0.95, pos=(-0.05, 0.0, -0.33), dayClickCallback=self._dayClickCallback, onlyFutureDaysClickable=True)
     return page
コード例 #26
0
 def destroy(self):
     del self.checkedHeight
     del self.partyInfo
     del self.parent
     del self.background
     del self.whosePartyLabel
     del self.whenTextLabel
     del self.partyStatusLabel
     DirectFrame.destroy(self)
コード例 #27
0
ファイル: LaffMeter.py プロジェクト: OldToontown/OldToontown
 def load(self):
     gui = loader.loadModel('phase_3/models/gui/laff_o_meter')
     if self.isToon:
         hType = self.style.getType()
         if hType == 'dog':
             headModel = gui.find('**/doghead')
         elif hType == 'cat':
             headModel = gui.find('**/cathead')
         elif hType == 'mouse':
             headModel = gui.find('**/mousehead')
         elif hType == 'horse':
             headModel = gui.find('**/horsehead')
         elif hType == 'rabbit':
             headModel = gui.find('**/bunnyhead')
         elif hType == 'duck':
             headModel = gui.find('**/duckhead')
         elif hType == 'monkey':
             headModel = gui.find('**/monkeyhead')
         elif hType == 'bear':
             headModel = gui.find('**/bearhead')
         elif hType == 'pig':
             headModel = gui.find('**/pighead')
         else:
             raise StandardError('unknown toon species: ', hType)
         self.color = self.style.getHeadColor()
         self.container['image'] = headModel
         self.container['image_color'] = self.color
         self.resetFrameSize()
         self.setScale(0.10000000000000001)
         self.frown = DirectFrame(parent = self.container, relief = None, image = gui.find('**/frown'))
         self.smile = DirectFrame(parent = self.container, relief = None, image = gui.find('**/smile'))
         self.eyes = DirectFrame(parent = self.container, relief = None, image = gui.find('**/eyes'))
         self.openSmile = DirectFrame(parent = self.container, relief = None, image = gui.find('**/open_smile'))
         self.tooth1 = DirectFrame(parent = self.openSmile, relief = None, image = gui.find('**/tooth_1'))
         self.tooth2 = DirectFrame(parent = self.openSmile, relief = None, image = gui.find('**/tooth_2'))
         self.tooth3 = DirectFrame(parent = self.openSmile, relief = None, image = gui.find('**/tooth_3'))
         self.tooth4 = DirectFrame(parent = self.openSmile, relief = None, image = gui.find('**/tooth_4'))
         self.tooth5 = DirectFrame(parent = self.openSmile, relief = None, image = gui.find('**/tooth_5'))
         self.tooth6 = DirectFrame(parent = self.openSmile, relief = None, image = gui.find('**/tooth_6'))
         self.maxLabel = DirectLabel(parent = self.eyes, relief = None, pos = (0.442, 0, 0.050999999999999997), text = '120', text_scale = 0.40000000000000002, text_font = ToontownGlobals.getInterfaceFont())
         self.hpLabel = DirectLabel(parent = self.eyes, relief = None, pos = (-0.39800000000000002, 0, 0.050999999999999997), text = '120', text_scale = 0.40000000000000002, text_font = ToontownGlobals.getInterfaceFont())
         self.teeth = [
             self.tooth6,
             self.tooth5,
             self.tooth4,
             self.tooth3,
             self.tooth2,
             self.tooth1]
         self.fractions = [
             0.0,
             0.16666600000000001,
             0.33333299999999999,
             0.5,
             0.66666599999999998,
             0.83333299999999999]
     
     gui.removeNode()
コード例 #28
0
 def destroy(self):
     taskMgr.remove('JellybeanRewardGuiTransferOneJellybean')
     del self.countSound
     del self.overMaxSound
     self.frame.destroy()
     self.earnedLabel.destroy()
     self.jarLabel.destroy()
     self.messageLabel.destroy()
     self.closeButton.destroy()
     DirectFrame.destroy(self)
コード例 #29
0
ファイル: Shop.py プロジェクト: coginvasion/src
    def destroy(self):
        self.items = {}
        del self.items
        for key, entry in self.itemEntries.iteritems():
            entry[0].destroy()
            entry[1].destroy()
            self.itemEntries[key] = None

        DirectFrame.destroy(self)
        return
コード例 #30
0
 def __init__(self, parent, useColor = 'blue', autoload = True):
     DirectFrame.__init__(self, parent)
     self.useColor = useColor
     self.endOffset = 1.5
     self.startOffset = 0.0
     self.shrinkRange = 7.0
     self.ratioDrawn = 0.0
     if autoload:
         self.load()
     self.stash()
コード例 #31
0
 def __init__(self, parent, pos=(0, 0, 0), hourCallback=None):
     DirectFrame.__init__(self, parent=parent, pos=pos)
     self.createGuiObjects()
     self.hourCallback = hourCallback
     self.lastHour = -1
     self.lastMinute = -1
コード例 #32
0
class CameraShyFirstPerson(FirstPerson):
    toonInFocusColor = VBase4(0.25, 1.0, 0.25, 1.0)
    toonOutOfFocusColor = VBase4(1.0, 1.0, 1.0, 1.0)
    fullyChargedState = 5

    def __init__(self, mg):
        self.mg = mg
        self.cameraFocus = None
        self.batteryFrame = None
        self.batteryBg = None
        self.batteryBar = None
        self.rechargeSound = None
        self.fullyChargedSound = None
        self.hasToonInFocus = False
        self.toonToTakePicOf = None
        self.cameraRechargeState = None
        self.cameraRechargingLabel = None
        self.cameraFlashSeq = None
        self.camFSM = ClassicFSM('CameraFSM', [
            State('off', self.enterOff, self.exitOff),
            State('ready', self.enterCameraReady, self.exitCameraReady),
            State('recharge', self.enterCameraRecharge,
                  self.exitCameraRecharge)
        ], 'off', 'off')
        self.camFSM.enterInitialState()
        FirstPerson.__init__(self)
        return

    def enterOff(self):
        pass

    def exitOff(self):
        pass

    def enterCameraReady(self):
        self.acceptOnce('mouse1', self.__mouse1Pressed)

    def stopCameraFlash(self):
        if self.cameraFlashSeq:
            self.cameraFlashSeq.finish()
            self.cameraFlashSeq = None
        return

    def __mouse1Pressed(self):
        self.cameraFlashSeq = Sequence(
            Func(base.transitions.setFadeColor, 1, 1, 1),
            Func(base.transitions.fadeOut, 0.1), Wait(0.1),
            Func(base.transitions.fadeIn, 0.1), Wait(0.1),
            Func(base.transitions.setFadeColor, 0, 0, 0))
        self.cameraFlashSeq.start()
        self.mg.sendUpdate('remoteAvatarTakePicture', [base.localAvatar.doId])
        self.mg.myRemoteAvatar.takePicture()
        if self.hasToonInFocus and self.toonToTakePicOf:
            self.mg.sendUpdate('tookPictureOfToon',
                               [self.toonToTakePicOf.doId])
        self.camFSM.request('recharge')

    def exitCameraReady(self):
        self.ignore('mouse1')

    def enterCameraRecharge(self):
        self.batteryBar.update(0)
        taskMgr.add(self.__rechargeNextState, 'rechargeCamera')

    def __rechargeNextState(self, task):
        if self.cameraRechargeState == None:
            self.cameraRechargeState = -1
        self.cameraRechargeState += 1
        if self.cameraRechargeState > 0:
            base.playSfx(self.rechargeSound)
        self.batteryBar.update(self.cameraRechargeState)
        if self.cameraRechargeState == self.fullyChargedState:
            base.playSfx(self.fullyChargedSound)
            self.camFSM.request('ready')
            return task.done
        task.delayTime = 1.0
        return task.again

    def exitCameraRecharge(self):
        taskMgr.remove('rechargeCamera')
        self.cameraRechargeState = None
        return

    def __traverse(self, task):
        if not base.mouseWatcherNode.hasMouse():
            return task.cont
        mpos = base.mouseWatcherNode.getMouse()
        self.focusRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())
        self.focusTrav.traverse(render)
        if self.focusHandler.getNumEntries() > 0:
            self.focusHandler.sortEntries()
            firstObj = self.focusHandler.getEntry(0).getIntoNodePath()
            avId = firstObj.getParent().getPythonTag('player')
            avatar = self.mg.cr.doId2do.get(avId)
            toonInFoc = False
            if avatar:
                remoteAvatar = self.mg.getRemoteAvatar(avatar.doId)
                if remoteAvatar:
                    toonInFoc = True
                    self.__handleToonInFocus(avatar)
            if not toonInFoc:
                self.toonToTakePicOf = None
                self.hasToonInFocus = False
                if self.cameraFocus.getColorScale() == self.toonInFocusColor:
                    self.cameraFocus.setColorScale(self.toonOutOfFocusColor)
        return task.cont

    def __handleToonInFocus(self, toon):
        if not self.hasToonInFocus or self.toonToTakePicOf is not None or self.toonToTakePicOf.doId != toon.doId:
            self.toonToTakePicOf = toon
            self.hasToonInFocus = True
            self.cameraFocus.setColorScale(self.toonInFocusColor)
        return

    def start(self):
        self.fullyChargedSound = base.loadSfx(
            'phase_4/audio/sfx/MG_pairing_match.ogg')
        self.rechargeSound = base.loadSfx(
            'phase_4/audio/sfx/MG_sfx_travel_game_blue_arrow.ogg')
        self.batteryFrame = DirectFrame(parent=base.a2dBottomRight,
                                        pos=(-0.2, 0, 0.1),
                                        scale=(0.8, 0, 1))
        self.batteryBg = OnscreenImage(
            image='phase_4/maps/battery_charge_frame.png',
            parent=self.batteryFrame)
        self.batteryBg.setTransparency(1)
        self.batteryBg.setX(0.03)
        self.batteryBg.setScale(0.17, 0, 0.05)
        self.batteryBar = DirectWaitBar(value=0,
                                        range=5,
                                        barColor=(1, 1, 1, 1),
                                        relief=None,
                                        scale=(0.12, 0.0, 0.3),
                                        parent=self.batteryFrame)
        self.cameraFocus = loader.loadModel(
            'phase_4/models/minigames/photo_game_viewfinder.bam')
        self.cameraFocus.reparentTo(base.aspect2d)
        self.focusTrav = CollisionTraverser('CSFP.focusTrav')
        ray = CollisionRay()
        rayNode = CollisionNode('CSFP.rayNode')
        rayNode.addSolid(ray)
        rayNode.setCollideMask(BitMask32(0))
        rayNode.setFromCollideMask(CIGlobals.WallBitmask)
        self.focusRay = ray
        self.focusRayNode = base.camera.attachNewNode(rayNode)
        self.focusHandler = CollisionHandlerQueue()
        self.focusTrav.addCollider(self.focusRayNode, self.focusHandler)
        base.localAvatar.walkControls.setWalkSpeed(CIGlobals.ToonForwardSpeed,
                                                   0.0,
                                                   CIGlobals.ToonReverseSpeed,
                                                   CIGlobals.ToonRotateSpeed)
        FirstPerson.start(self)
        return

    def reallyStart(self):
        taskMgr.add(self.__traverse, 'CSFP.__traverse')
        self.camFSM.request('recharge')
        base.localAvatar.startTrackAnimToSpeed()
        FirstPerson.reallyStart(self)

    def end(self):
        self.camFSM.request('off')
        taskMgr.remove('movementTask')
        taskMgr.remove('CSFP.__traverse')
        FirstPerson.end(self)

    def reallyEnd(self):
        self.batteryBar.destroy()
        self.batteryBar = None
        self.batteryBg.destroy()
        self.batteryBg = None
        self.batteryFrame.destroy()
        self.batteryFrame = None
        self.cameraFocus.removeNode()
        self.cameraFocus = None
        self.focusHandler = None
        self.focusRay = None
        self.focusRayNode.removeNode()
        self.focusRayNode = None
        self.focusTrav = None
        self.hasToonInFocus = None
        self.toonToTakePicOf = None
        self.fullyChargedSound = None
        self.rechargeSound = None
        self.stopCameraFlash()
        FirstPerson.reallyEnd(self)
        base.localAvatar.walkControls.setWalkSpeed(CIGlobals.ToonForwardSpeed,
                                                   CIGlobals.ToonJumpForce,
                                                   CIGlobals.ToonReverseSpeed,
                                                   CIGlobals.ToonRotateSpeed)
        return

    def cleanup(self):
        self.camFSM.requestFinalState()
        self.camFSM = None
        FirstPerson.cleanup(self)
        return
コード例 #33
0
 def destroy(self):
     ToontownIntervals.cleanup('boss_code%i' % self._id)
     DirectFrame.destroy(self)
コード例 #34
0
class OptionsPage(BookPage):
    notify = directNotify.newCategory("OptionsPage")

    # Keys are categories and values are x-positions for the text.
    Categories = OrderedDict()
    Categories[AboutCategory] = 0.09
    Categories[GeneralCategory] = 0.07
    Categories[ControlsCategory] = 0.05
    Categories[SoundCategory] = 0.0825
    Categories[DisplayCategory] = 0.07
    Categories[AdvancedDisplayCategory] = 0.05

    def __init__(self, book):
        BookPage.__init__(self, book, "Options")
        self.currentCategory = None
        self.tabs = []

    def load(self):
        BookPage.load(self)
        icons = loader.loadModel('phase_3.5/models/gui/sos_textures.bam')
        self.icon = icons.find('**/switch')
        icons.detachNode()

    def enter(self):
        BookPage.enter(self)
        self.tabScaleFrame = DirectFrame(parent=self.book)
        self.tabScaleFrame.setZ(0.7683)
        self.tabsFrame = DirectFrame(parent=self.tabScaleFrame)

        tabWidth = 0.379136800766
        spacing = 0.075

        totalWidth = 0.0
        bookWidth = 2.0

        for i in xrange(len(self.Categories.keys())):
            if i > 0:
                totalWidth += spacing
            totalWidth += tabWidth
            cl = self.Categories.keys()[i]
            tab = CategoryTab(self, cl.Name, [cl],
                              ((tabWidth + spacing) * i, 0, 0),
                              self.Categories.values()[i])
            self.tabs.append(tab)

        self.tabsFrame.setX(totalWidth / -2.0)
        self.tabScaleFrame.setScale(min(1.0, 1.0 / (totalWidth / bookWidth)))

        self.pickCategory(AboutCategory)

    def closeWindow(self):
        if self.currentCategory:
            self.currentCategory.cleanup()
            self.currentCategory = None

    def pickCategory(self, cat):
        if self.currentCategory:
            self.currentCategory.cleanup()
            self.currentCategory = None
        self.currentCategory = cat(self)
        for tab in self.tabs:
            if tab['extraArgs'][0] is cat:
                tab['state'] = DGG.DISABLED
            else:
                tab['state'] = DGG.NORMAL
        #self.currentCategory.show()

    def exit(self):
        if self.currentCategory:
            self.currentCategory.cleanup()
            self.currentCategory = None
        for tab in self.tabs:
            tab.destroy()
        self.tabsFrame.destroy()
        del self.tabsFrame
        self.tabScaleFrame.destroy()
        del self.tabScaleFrame
        self.tabs = []
        BookPage.exit(self)
コード例 #35
0
ファイル: LaffMeter.py プロジェクト: RippedTelemarketer/rttim
 def load(self):
     gui = loader.loadModel('phase_3/models/gui/laff_o_meter')
     if self.isToon:
         hType = self.style.getType()
         if hType == 'dog':
             headModel = gui.find('**/doghead')
         elif hType == 'cat':
             headModel = gui.find('**/cathead')
         elif hType == 'mouse':
             headModel = gui.find('**/mousehead')
         elif hType == 'horse':
             headModel = gui.find('**/horsehead')
         elif hType == 'rabbit':
             headModel = gui.find('**/bunnyhead')
         elif hType == 'duck':
             headModel = gui.find('**/duckhead')
         elif hType == 'monkey':
             headModel = gui.find('**/monkeyhead')
         elif hType == 'bear':
             headModel = gui.find('**/bearhead')
         elif hType == 'pig':
             headModel = gui.find('**/pighead')
         elif hType == 'riggy':
             headModel = gui.find('**/bunnyhead')
         elif hType == 'deer':
             headModel = gui.find('**/deerhead')  #Placeholder
         elif hType == 'crocodile':
             headModel = gui.find('**/crocodilehead')  #Placeholder
         else:
             raise StandardError('unknown toon species: ', hType)
         self.color = self.style.getHeadColor()
         self.container['image'] = headModel
         self.container['image_color'] = self.color
         self.resetFrameSize()
         self.setScale(0.1)
         self.frown = DirectFrame(parent=self.container,
                                  relief=None,
                                  image=gui.find('**/frown'))
         self.smile = DirectFrame(parent=self.container,
                                  relief=None,
                                  image=gui.find('**/smile'))
         self.eyes = DirectFrame(parent=self.container,
                                 relief=None,
                                 image=gui.find('**/eyes'))
         self.openSmile = DirectFrame(parent=self.container,
                                      relief=None,
                                      image=gui.find('**/open_smile'))
         self.tooth1 = DirectFrame(parent=self.openSmile,
                                   relief=None,
                                   image=gui.find('**/tooth_1'))
         self.tooth2 = DirectFrame(parent=self.openSmile,
                                   relief=None,
                                   image=gui.find('**/tooth_2'))
         self.tooth3 = DirectFrame(parent=self.openSmile,
                                   relief=None,
                                   image=gui.find('**/tooth_3'))
         self.tooth4 = DirectFrame(parent=self.openSmile,
                                   relief=None,
                                   image=gui.find('**/tooth_4'))
         self.tooth5 = DirectFrame(parent=self.openSmile,
                                   relief=None,
                                   image=gui.find('**/tooth_5'))
         self.tooth6 = DirectFrame(parent=self.openSmile,
                                   relief=None,
                                   image=gui.find('**/tooth_6'))
         self.maxLabel = DirectLabel(
             parent=self.eyes,
             relief=None,
             pos=(0.442, 0, 0.051),
             text='120',
             text_scale=0.4,
             text_font=ToontownGlobals.getInterfaceFont())
         self.hpLabel = DirectLabel(
             parent=self.eyes,
             relief=None,
             pos=(-0.398, 0, 0.051),
             text='120',
             text_scale=0.4,
             text_font=ToontownGlobals.getInterfaceFont())
         self.teeth = [
             self.tooth6, self.tooth5, self.tooth4, self.tooth3,
             self.tooth2, self.tooth1
         ]
         self.fractions = [0.0, 0.166666, 0.333333, 0.5, 0.666666, 0.833333]
     gui.removeNode()
     return
コード例 #36
0
ファイル: pregame.py プロジェクト: H3LLB0Y/Centipede
    def __init__(self, showbase):
        self.showbase = showbase

        self.ready = False

        self.background = DirectFrame(
            frameSize=(-1, 1, -1, 1),
            frameTexture='media/gui/mainmenu/menu.png',
            parent=self.showbase.render2d,
        )

        self.title = OnscreenText(text='Lobby!',
                                  fg=(1, 1, 1, 1),
                                  parent=self.background,
                                  pos=(-0.6, 0.1),
                                  scale=0.06)

        self.buttons = []
        controlButtons = Vec3(-0.60, 0, -0.79)
        # Toggle ready
        p = controlButtons + Vec3(-0.25, 0, 0)
        self.toggleReadyButton = DirectButton(
            text='Ready/Unready',
            pos=p,
            scale=0.048,
            relief=DGG.GROOVE,
            command=self.toggleReady,
        )
        self.buttons.append(self.toggleReadyButton)
        # Disconnect
        p = controlButtons + Vec3(0.0, 0.0, 0.0)
        self.disconnectButton = DirectButton(
            text='Disconnect',
            pos=p,
            scale=0.048,
            relief=DGG.GROOVE,
            command=self.disconnect,
        )
        self.buttons.append(self.disconnectButton)

        # Send message
        p = controlButtons + Vec3(0.25, 0.0, 0.0)
        self.sendMessageButton = DirectButton(
            text='Send Message',
            pos=p,
            scale=0.048,
            relief=DGG.GROOVE,
            command=self.sendMessage,
            extraArgs=[''],
        )
        self.buttons.append(self.sendMessageButton)
        # Message input
        self.message = DirectEntry(
            command=self.sendMessage,
            focusInCommand=self.clearText,
            frameSize=(-3, 3, -.5, 1),
            initialText='',
            parent=self.buttons[2],
            pos=(0, -0.6, -1.5),
            text_align=TextNode.ACenter,
        )

        self.showbase.gameData = GameData()

        self.showbase.users = []

        self.hide()
コード例 #37
0
def add_button(self, text, label_id, pos_x, pos_y, width=0.0, hight=0.1):
    if width == 0.0:
        for c in range(len(text) / 2):
            width += 0.08
    ls = LineSegs("lines")
    ls.setColor(0, 1, 0, 1)
    ls.drawTo(-width / 2, 0, hight / 2)
    ls.drawTo(width / 2, 0, hight / 2)
    ls.drawTo(width / 2, 0, -hight / 2)
    ls.drawTo(-width / 2, 0, -hight / 2)
    ls.drawTo(-width / 2, 0, hight / 2)
    border = ls.create(False)
    border.setTag('back_ground', '1')

    array = GeomVertexArrayFormat()
    array.addColumn("vertex", 4, Geom.NTFloat32, Geom.CPoint)
    arr_format = GeomVertexFormat()
    arr_format.addArray(array)
    arr_format = GeomVertexFormat.registerFormat(arr_format)

    vdata = GeomVertexData('fill', arr_format, Geom.UHStatic)
    vdata.setNumRows(4)
    vertex = GeomVertexWriter(vdata, 'vertex')

    vertex.addData3f(-width / 2, 0, hight / 2)
    vertex.addData3f(width / 2, 0, hight / 2)
    vertex.addData3f(-width / 2, 0, -hight / 2)
    vertex.addData3f(width / 2, 0, -hight / 2)

    prim = GeomTristrips(Geom.UHStatic)
    prim.addVertex(0)
    prim.addVertex(1)
    prim.addVertex(2)
    prim.addVertex(3)

    geom = Geom(vdata)
    geom.addPrimitive(prim)
    node = GeomNode('gnode')
    node.addGeom(geom)
    nodePath = NodePath("button")
    nodePath.attachNewNode(node)
    nodePath.setPos(0, 0, 0)
    nodePath.setTag('button', '1')
    nodePath.setBin("unsorted", 0)
    nodePath.setDepthTest(False)
    nodePath.setColor(0, 0, 0, 1)
    nodePath.attachNewNode(border)

    nodePath1 = NodePath("button")
    nodePath1.attachNewNode(node)
    nodePath1.setPos(0, 0, 0)
    nodePath1.setTag('button1', '1')
    nodePath1.setBin("unsorted", 0)
    nodePath1.setDepthTest(False)
    nodePath1.setColor(0, 1, 0, 1)
    nodePath1.attachNewNode(border)

    button = DirectFrame(enableEdit=1,
                         text=text,
                         geom=nodePath,
                         text_scale=0.05,
                         text_fg=(0, 1, 0, 1),
                         borderWidth=(1, 1),
                         relief=None,
                         text_pos=(0, -0.01, 0),
                         textMayChange=1,
                         state=DGG.NORMAL,
                         parent=aspect2d)
    button.setPos(pos_x, 0, pos_y)
    button.bind(DGG.B1PRESS, button_click, [button])
    button.bind(DGG.WITHIN, button_hover, [button])
    button.bind(DGG.WITHOUT, button_no_hover, [button])
    # button.resetFrameSize()
    # self.button.bind(DGG.WITHIN, self.onMouseHoverInFunction, [button, some_value1])

    defines.ENTITIES[defines.ENTITY_ID] = {
        'CATEGORY': 'button',
        'BUTTON': button,
        'NODE': nodePath,
        'LABEL': label_id,
        'STATUS': 0
    }
    defines.ENTITY_ID += 1
コード例 #38
0
    def initRaceMode(self):
        self.mapScene = base.a2dTopRight.attachNewNode('MapScene')
        self.mapScene.setPos(-0.2, 0, -0.2)
        self.mapScene.setScale(0.25, 0.001, 0.25)
        maxT = self.race.curve.getMaxT()
        pt = Vec3(0, 0, 0)
        ls = LineSegs('MapLines')
        ls.setColor(1, 1, 1, 1)
        ls.setThickness(2)
        for x in xrange(101):
            self.race.curve.getPoint(x / 100.0 * maxT, pt)
            if x == 0:
                ls.moveTo(pt[0], pt[1], pt[2])
            else:
                ls.drawTo(pt[0], pt[1], pt[2])

        self.mapLines = self.mapScene.attachNewNode(ls.create())
        self.mapLines.setScale(0.00025 *
                               RaceGlobals.TrackDict[self.race.trackId][6])
        self.mapLines.setP(90)
        self.faceStartPos = Vec3(-0.8, 0, 0.93)
        self.faceEndPos = Vec3(0.8, 0, 0.93)
        self.placeLabelNum = DirectLabel(
            relief=None,
            pos=TTLocalizer.RGUIplaceLabelNumPos,
            text='1',
            text_scale=0.35,
            text_fg=(0.95, 0.95, 0, 1),
            text_font=ToontownGlobals.getSignFont())
        self.placeLabelNum.reparentTo(base.a2dBottomLeft)
        self.directObjList.append(self.placeLabelNum)
        self.placeLabelStr = DirectLabel(
            relief=None,
            pos=TTLocalizer.RGUIplaceLabelStrPos,
            text=TTLocalizer.KartRace_FirstSuffix,
            text_scale=0.1,
            text_fg=(0.95, 0.95, 0, 1),
            text_font=ToontownGlobals.getSignFont())
        self.placeLabelStr.reparentTo(base.a2dBottomLeft)
        self.directObjList.append(self.placeLabelStr)
        self.lapLabel = DirectLabel(relief=None,
                                    pos=(-0.22, 0, -0.5),
                                    text='1/' + str(self.race.lapCount),
                                    text_scale=0.1,
                                    text_fg=(0.95, 0.95, 0, 1),
                                    text_font=ToontownGlobals.getSignFont())
        self.lapLabel.reparentTo(base.a2dTopRight)
        self.directObjList.append(self.lapLabel)
        self.photoFinishLabel = DirectLabel(
            relief=None,
            pos=(0, 0, -0.1),
            text=TTLocalizer.KartRace_PhotoFinish,
            text_scale=TTLocalizer.RGUIphotoFinish,
            text_fg=(0.95, 0.95, 0, 1),
            text_font=ToontownGlobals.getSignFont())
        self.photoFinishLabel.hide()
        self.directObjList.append(self.photoFinishLabel)
        self.wrongWayLabel = DirectLabel(
            relief=None,
            pos=(-0.22, 0, -0.2),
            text=TTLocalizer.KartRace_WrongWay,
            text_scale=0.1,
            text_fg=(0.95, 0, 0, 1),
            text_font=ToontownGlobals.getSignFont())
        self.wrongWayLabel.reparentTo(base.a2dTopRight)
        self.directObjList.append(self.wrongWayLabel)
        self.wrongWayLabel.setColorScale(Vec4(1, 1, 1, 0))
        self.wrongWaySeq = Sequence(
            self.wrongWayLabel.colorScaleInterval(0.25,
                                                  colorScale=Vec4(1, 1, 1, 1),
                                                  startColorScale=Vec4(
                                                      1, 1, 1, 0)),
            self.wrongWayLabel.colorScaleInterval(0.25,
                                                  colorScale=Vec4(1, 1, 1, 0),
                                                  startColorScale=Vec4(
                                                      1, 1, 1, 1)))
        interpolateFacePos = lambda x: self.faceStartPos * (
            1.0 - x) + self.faceEndPos * x
        self.timeLabels = []
        for x in xrange(self.race.lapCount):
            minLabel = DirectLabel(
                relief=None,
                pos=(interpolateFacePos(
                    (2.0 * x + 1) / (self.race.lapCount * 2))[0] - 0.06, 0,
                     0.84),
                text="0'",
                text_scale=0.06,
                text_fg=(0.95, 0.95, 0, 1),
                text_font=ToontownGlobals.getSignFont(),
                text_align=TextNode.ARight)
            minLabel.reparentTo(self.raceModeRoot)
            self.directObjList.append(minLabel)
            secLabel = DirectLabel(
                relief=None,
                pos=(interpolateFacePos(
                    (2.0 * x + 1) / (self.race.lapCount * 2))[0] + 0.06, 0,
                     0.84),
                text="00''",
                text_scale=0.06,
                text_fg=(0.95, 0.95, 0, 1),
                text_font=ToontownGlobals.getSignFont(),
                text_align=TextNode.ARight)
            secLabel.reparentTo(self.raceModeRoot)
            self.directObjList.append(secLabel)
            fractionLabel = DirectLabel(
                relief=None,
                pos=(interpolateFacePos(
                    (2.0 * x + 1) / (self.race.lapCount * 2))[0] + 0.14, 0,
                     0.84),
                text='00',
                text_scale=0.06,
                text_fg=(0.95, 0.95, 0, 1),
                text_font=ToontownGlobals.getSignFont(),
                text_align=TextNode.ARight)
            fractionLabel.reparentTo(self.raceModeRoot)
            self.directObjList.append(fractionLabel)
            self.timeLabels.append((minLabel, secLabel, fractionLabel))

        self.cardMaker.reset()
        self.cardMaker.setName('GagIndicator')
        self.cardMaker.setFrame(-0.5, 0.5, -0.5, 0.5)
        self.cardMaker.setColor(1, 1, 1, 1)
        self.gagPanel = DirectFrame(
            parent=base.a2dBottomLeft,
            relief=None,
            image=loader.loadModel('phase_6/models/karting/gag_panel'),
            image_scale=0.25,
            pos=(0.2, 0, 0.55))
        self.directObjList.append(self.gagPanel)
        self.gag = self.gagPanel.attachNewNode('gag')
        self.gag.setScale(0.2)
        for gag in self.gagTextures:
            gag.reparentTo(self.gag)
            gag.hide()

        self.cardMaker.reset()
        self.cardMaker.setName('RaceProgressLine')
        self.cardMaker.setFrame(-0.5, 0.5, -0.5, 0.5)
        line = self.raceModeRoot.attachNewNode(self.cardMaker.generate())
        line.setScale(self.faceEndPos[0] - self.faceStartPos[0], 1, 0.01)
        line.setPos(0, 0, self.faceStartPos[2])
        self.cardMaker.setName('RaceProgressLineHash')
        for n in xrange(self.race.lapCount + 1):
            hash = self.raceModeRoot.attachNewNode(self.cardMaker.generate())
            hash.setScale(line.getScale()[2], 1, line.getScale()[2] * 5)
            t = float(n) / self.race.lapCount
            hash.setPos(
                self.faceStartPos[0] * (1 - t) + self.faceEndPos[0] * t,
                self.faceStartPos[1], self.faceStartPos[2])
        self.closeButton.show
        self.raceModeReady = True
        self.disable()
        return
コード例 #39
0
class RaceGUI:
    GagPie = 0
    gagRoot = 'phase_3.5/maps/inventory_'

    class RacerInfo:
        def __init__(self, face, mapSpot):
            self.curvetime = 0
            self.maxlaphit = 0
            self.face = face
            self.mapspot = mapSpot
            self.place = 1
            self.enabled = True
            self.finished = False
            self.gag = None
            return

        def update(self,
                   curvetime=None,
                   maxlaphit=None,
                   faceX=None,
                   mapspotPt=None,
                   place=None,
                   finished=None):
            if self.enabled:
                if not curvetime == None:
                    self.curvetime = curvetime
                if not maxlaphit == None:
                    self.maxlaphit = maxlaphit
                if not faceX == None:
                    self.face.setX(faceX)
                if not mapspotPt == None:
                    self.mapspot.setPos(mapspotPt)
                if not place == None:
                    self.place = place
                if not finished == None:
                    self.finished = finished
            return

        def disable(self):
            self.enabled = False
            if not self.finished:
                self.face.hide()
            self.mapspot.hide()

        def enable(self):
            self.enabled = True
            self.face.show()
            self.mapspot.show()

    def __init__(self, distRace):
        self.race = distRace
        self.timerEnabled = False
        self.maxLapHit = 0
        self.photoFinish = False
        toonInteriorTextures = loader.loadModel(
            'phase_3.5/models/modules/toon_interior_textures')
        invTextures = loader.loadModel('phase_3.5/models/gui/inventory_icons')
        racingTextures = loader.loadModel(
            'phase_6/models/karting/racing_textures')
        self.gagTextures = [
            toonInteriorTextures.find('**/couch'),
            invTextures.find('**/inventory_bannana_peel'),
            racingTextures.find('**/boost_arrow'),
            invTextures.find('**/inventory_anvil'),
            invTextures.find('**/inventory_creampie')
        ]
        self.gagTextures[1].setScale(7.5)
        self.gagTextures[3].setScale(7.5)
        self.gagTextures[4].setScale(7.5)
        self.cardMaker = CardMaker('card')
        self.racerDict = {}
        self.render2dRoot = render2d.attachNewNode('RaceGuiRender2dRoot')
        self.render2dRoot.setDepthWrite(1)
        self.directObjList = []
        self.aspect2dRoot = aspect2d.attachNewNode('RaceGuiAspect2dRoot')
        self.aspect2dRoot.setDepthWrite(1)
        self.raceModeRoot = self.aspect2dRoot.attachNewNode('RaceModeRoot')
        gui = loader.loadModel('phase_3.5/models/gui/avatar_panel_gui')
        self.closeButton = DirectButton(image=(gui.find('**/CloseBtn_UP'),
                                               gui.find('**/CloseBtn_DN'),
                                               gui.find('**/CloseBtn_Rllvr'),
                                               gui.find('**/CloseBtn_UP')),
                                        relief=None,
                                        scale=1.05,
                                        text=TTLocalizer.KartRace_Leave,
                                        text_scale=0.04,
                                        text_pos=(0, -0.07),
                                        text_fg=VBase4(1, 1, 1, 1),
                                        pos=(-0.99, 0, 0.925),
                                        command=self.race.leaveRace)
        self.closeButton.reparentTo(self.aspect2dRoot)
        self.directObjList.append(self.closeButton)
        self.raceTimeDelta = 0
        self.raceModeReady = False
        self.resultModeReady = False
        self.gagCycleSound = base.loader.loadSfx(
            'phase_3.5/audio/sfx/tick_counter.ogg')
        if hasattr(self.gagCycleSound, 'setPlayRate'):
            self.gagCycleSound.setPlayRate(0.2)
        self.gagCycleSound.setLoop(1)
        self.gagAcquireSound = base.loader.loadSfx(
            'phase_6/audio/sfx/SZ_MM_gliss.ogg')
        self.disable()
        return

    def initRaceMode(self):
        self.mapScene = base.a2dTopRight.attachNewNode('MapScene')
        self.mapScene.setPos(-0.2, 0, -0.2)
        self.mapScene.setScale(0.25, 0.001, 0.25)
        maxT = self.race.curve.getMaxT()
        pt = Vec3(0, 0, 0)
        ls = LineSegs('MapLines')
        ls.setColor(1, 1, 1, 1)
        ls.setThickness(2)
        for x in xrange(101):
            self.race.curve.getPoint(x / 100.0 * maxT, pt)
            if x == 0:
                ls.moveTo(pt[0], pt[1], pt[2])
            else:
                ls.drawTo(pt[0], pt[1], pt[2])

        self.mapLines = self.mapScene.attachNewNode(ls.create())
        self.mapLines.setScale(0.00025 *
                               RaceGlobals.TrackDict[self.race.trackId][6])
        self.mapLines.setP(90)
        self.faceStartPos = Vec3(-0.8, 0, 0.93)
        self.faceEndPos = Vec3(0.8, 0, 0.93)
        self.placeLabelNum = DirectLabel(
            relief=None,
            pos=TTLocalizer.RGUIplaceLabelNumPos,
            text='1',
            text_scale=0.35,
            text_fg=(0.95, 0.95, 0, 1),
            text_font=ToontownGlobals.getSignFont())
        self.placeLabelNum.reparentTo(base.a2dBottomLeft)
        self.directObjList.append(self.placeLabelNum)
        self.placeLabelStr = DirectLabel(
            relief=None,
            pos=TTLocalizer.RGUIplaceLabelStrPos,
            text=TTLocalizer.KartRace_FirstSuffix,
            text_scale=0.1,
            text_fg=(0.95, 0.95, 0, 1),
            text_font=ToontownGlobals.getSignFont())
        self.placeLabelStr.reparentTo(base.a2dBottomLeft)
        self.directObjList.append(self.placeLabelStr)
        self.lapLabel = DirectLabel(relief=None,
                                    pos=(-0.22, 0, -0.5),
                                    text='1/' + str(self.race.lapCount),
                                    text_scale=0.1,
                                    text_fg=(0.95, 0.95, 0, 1),
                                    text_font=ToontownGlobals.getSignFont())
        self.lapLabel.reparentTo(base.a2dTopRight)
        self.directObjList.append(self.lapLabel)
        self.photoFinishLabel = DirectLabel(
            relief=None,
            pos=(0, 0, -0.1),
            text=TTLocalizer.KartRace_PhotoFinish,
            text_scale=TTLocalizer.RGUIphotoFinish,
            text_fg=(0.95, 0.95, 0, 1),
            text_font=ToontownGlobals.getSignFont())
        self.photoFinishLabel.hide()
        self.directObjList.append(self.photoFinishLabel)
        self.wrongWayLabel = DirectLabel(
            relief=None,
            pos=(-0.22, 0, -0.2),
            text=TTLocalizer.KartRace_WrongWay,
            text_scale=0.1,
            text_fg=(0.95, 0, 0, 1),
            text_font=ToontownGlobals.getSignFont())
        self.wrongWayLabel.reparentTo(base.a2dTopRight)
        self.directObjList.append(self.wrongWayLabel)
        self.wrongWayLabel.setColorScale(Vec4(1, 1, 1, 0))
        self.wrongWaySeq = Sequence(
            self.wrongWayLabel.colorScaleInterval(0.25,
                                                  colorScale=Vec4(1, 1, 1, 1),
                                                  startColorScale=Vec4(
                                                      1, 1, 1, 0)),
            self.wrongWayLabel.colorScaleInterval(0.25,
                                                  colorScale=Vec4(1, 1, 1, 0),
                                                  startColorScale=Vec4(
                                                      1, 1, 1, 1)))
        interpolateFacePos = lambda x: self.faceStartPos * (
            1.0 - x) + self.faceEndPos * x
        self.timeLabels = []
        for x in xrange(self.race.lapCount):
            minLabel = DirectLabel(
                relief=None,
                pos=(interpolateFacePos(
                    (2.0 * x + 1) / (self.race.lapCount * 2))[0] - 0.06, 0,
                     0.84),
                text="0'",
                text_scale=0.06,
                text_fg=(0.95, 0.95, 0, 1),
                text_font=ToontownGlobals.getSignFont(),
                text_align=TextNode.ARight)
            minLabel.reparentTo(self.raceModeRoot)
            self.directObjList.append(minLabel)
            secLabel = DirectLabel(
                relief=None,
                pos=(interpolateFacePos(
                    (2.0 * x + 1) / (self.race.lapCount * 2))[0] + 0.06, 0,
                     0.84),
                text="00''",
                text_scale=0.06,
                text_fg=(0.95, 0.95, 0, 1),
                text_font=ToontownGlobals.getSignFont(),
                text_align=TextNode.ARight)
            secLabel.reparentTo(self.raceModeRoot)
            self.directObjList.append(secLabel)
            fractionLabel = DirectLabel(
                relief=None,
                pos=(interpolateFacePos(
                    (2.0 * x + 1) / (self.race.lapCount * 2))[0] + 0.14, 0,
                     0.84),
                text='00',
                text_scale=0.06,
                text_fg=(0.95, 0.95, 0, 1),
                text_font=ToontownGlobals.getSignFont(),
                text_align=TextNode.ARight)
            fractionLabel.reparentTo(self.raceModeRoot)
            self.directObjList.append(fractionLabel)
            self.timeLabels.append((minLabel, secLabel, fractionLabel))

        self.cardMaker.reset()
        self.cardMaker.setName('GagIndicator')
        self.cardMaker.setFrame(-0.5, 0.5, -0.5, 0.5)
        self.cardMaker.setColor(1, 1, 1, 1)
        self.gagPanel = DirectFrame(
            parent=base.a2dBottomLeft,
            relief=None,
            image=loader.loadModel('phase_6/models/karting/gag_panel'),
            image_scale=0.25,
            pos=(0.2, 0, 0.55))
        self.directObjList.append(self.gagPanel)
        self.gag = self.gagPanel.attachNewNode('gag')
        self.gag.setScale(0.2)
        for gag in self.gagTextures:
            gag.reparentTo(self.gag)
            gag.hide()

        self.cardMaker.reset()
        self.cardMaker.setName('RaceProgressLine')
        self.cardMaker.setFrame(-0.5, 0.5, -0.5, 0.5)
        line = self.raceModeRoot.attachNewNode(self.cardMaker.generate())
        line.setScale(self.faceEndPos[0] - self.faceStartPos[0], 1, 0.01)
        line.setPos(0, 0, self.faceStartPos[2])
        self.cardMaker.setName('RaceProgressLineHash')
        for n in xrange(self.race.lapCount + 1):
            hash = self.raceModeRoot.attachNewNode(self.cardMaker.generate())
            hash.setScale(line.getScale()[2], 1, line.getScale()[2] * 5)
            t = float(n) / self.race.lapCount
            hash.setPos(
                self.faceStartPos[0] * (1 - t) + self.faceEndPos[0] * t,
                self.faceStartPos[1], self.faceStartPos[2])
        self.closeButton.show
        self.raceModeReady = True
        self.disable()
        return

    def initResultMode(self):
        self.endPanel = RaceEndPanel(len(self.race.avIds), self.race)
        self.endPanel.reparentTo(self.aspect2dRoot)
        self.directObjList.append(self.endPanel)
        self.resultModeReady = True
        self.disable()

    def showGag(self, gagIndex):
        if gagIndex < len(self.gagTextures):
            for gag in self.gagTextures:
                gag.hide()

            self.gagTextures[gagIndex].show()

    def updateGag(self, gagIndex):
        if self.gag:
            if hasattr(self, 'gagCycleInterval'):
                self.gagCycleInterval.finish()
                del self.gagCycleInterval
            self.gag.setHpr(0, 0, 0)
            self.showGag(gagIndex)
            if gagIndex == 0:
                self.gag.hide()
            else:
                self.gag.show()
                self.gagAcquireSound.play()
                self.gagAcquireInterval = LerpHprInterval(self.gag,
                                                          duration=0.5,
                                                          blendType='easeOut',
                                                          startHpr=Point3(
                                                              0, -90, 0),
                                                          hpr=Point3(0, 0, 0))
                self.gagAcquireInterval.start()

    def waitingOnGag(self, cycleTime):
        if self.gag:
            numTextures = len(self.gagTextures)
            startOffset = random.choice(range(0, numTextures))
            self.gag.show()
            self.gagCycleInterval = Parallel(
                LerpFunc(self.showNextGag,
                         fromData=startOffset,
                         toData=numTextures * 2 * cycleTime + startOffset,
                         blendType='easeOut',
                         duration=cycleTime),
                LerpHprInterval(self.gag,
                                duration=cycleTime,
                                hpr=Point3(
                                    0, 180 * numTextures * 2 * cycleTime - 90,
                                    0),
                                blendType='easeOut',
                                startHpr=Point3(0, 0, 0)),
                SoundInterval(self.gagCycleSound,
                              loop=1,
                              duration=cycleTime,
                              startTime=0),
                name='gagCycleInterval')
            self.gagCycleInterval.start()

    def showNextGag(self, t):
        if self.gag:
            currGagIndex = int(t % (len(self.gagTextures) - 1)) + 1
            self.showGag(currGagIndex)

    def enableSpeedometer(self):
        self.race.localKart.showSpeedometer()

    def disableSpeedometer(self):
        self.race.localKart.hideSpeedometer()

    def disableRaceMode(self):
        self.disableSpeedometer()
        self.render2dRoot.hide()
        self.raceModeRoot.hide()
        for x in self.timeLabels:
            for y in x:
                y.hide()

        self.setTimerEnabled(False)

    def disableResultMode(self):
        self.endPanel.disable()

    def disable(self):
        # self.closeButton.hide()
        taskMgr.removeTasksMatching('clearRaceEndPanel')
        if self.raceModeReady:
            self.disableRaceMode()
        if self.resultModeReady:
            self.disableResultMode()

    def enableRaceMode(self):
        self.enableSpeedometer()
        self.render2dRoot.show()
        self.raceModeRoot.show()
        self.maxLapHit = min(self.maxLapHit, self.race.lapCount - 1)
        for x in xrange(self.maxLapHit + 1):
            for y in self.timeLabels[x]:
                y.configure(text_font=ToontownGlobals.getSignFont())
                y.show()

        for y in self.timeLabels[self.maxLapHit]:
            y.configure(text_font=ToontownGlobals.getSignFont())

    def enableResultMode(self):
        self.endPanel.enable()
        if not self.race.circuitLoop:
            taskMgr.doMethodLater(180,
                                  self.endPanel.closeButtonPressed,
                                  'clearRaceEndPanel',
                                  extraArgs=[])

    def destroy(self):
        self.disable()
        if hasattr(self, 'wrongWaySeq'):
            self.wrongWaySeq.finish()
            self.wrongWaySeq = None
        taskMgr.removeTasksMatching('removeIt')
        taskMgr.removeTasksMatching('removeCam*')
        taskMgr.removeTasksMatching('clearRaceEndPanel')
        for obj in self.directObjList:
            obj.destroy()

        if hasattr(self, 'mapScene'):
            self.mapScene.removeNode()
            self.mapScene = None
        self.aspect2dRoot.removeNode()
        self.aspect2dRoot = None
        self.raceModeRoot.removeNode()
        self.raceModeRoot = None
        self.render2dRoot.removeNode()
        self.render2dRoot = None
        self.closeButton = None
        self.gag = None
        self.lapLabel = None
        self.timeLabels = None
        self.placeLabelStr = None
        self.placeLabelNum = None
        self.photoFinishLabel = None
        self.mapScene = None
        self.race = None
        return

    def setSpotAsymptotic(self, diffT, spot):
        p = (-1, 1)[diffT > 0] * (1 - 1 / pow(abs(diffT) / self.cutoff + 1, 2))
        spot.setX(p)

    def setSpotRaceLinear(self, t, spot):
        spot.setX(-1.0 + 2.0 * (t / self.lapCount))

    def setSpotLapLinear(self, t, spot):
        spot.setX(-1.0 + 2.0 * (t - int(t)))

    def update(self, time):
        placeSorter = []
        placeCount = 0
        for key in self.racerDict.keys():
            racer = self.racerDict[key]
            curvetime = racer.curvetime
            face = racer.face
            mapspot = racer.mapspot
            maxlaphit = racer.maxlaphit
            if not racer.finished and racer.enabled:
                placeSorter.append((curvetime, key))
            if racer.finished or racer.enabled:
                placeCount += 1
            pt = Vec3(0, 0, 0)
            mapT = (curvetime % 1 + self.race.startT /
                    self.race.curve.getMaxT()) % 1 * self.race.curve.getMaxT()
            self.race.curve.getPoint(mapT, pt)
            self.race.curve.getPoint(mapT % self.race.curve.getMaxT(), pt)
            lapT = clampScalar(curvetime / self.race.lapCount, 0.0, 1.0)
            faceX = self.faceStartPos[0] * (1 -
                                            lapT) + self.faceEndPos[0] * lapT
            racer.update(faceX=faceX, mapspotPt=pt)
            t = time - self.race.baseTime - self.raceTimeDelta
            if key == localAvatar.doId:
                if self.race.laps > maxlaphit:
                    racer.update(maxlaphit=self.race.laps)
                    self.maxLapHit = racer.maxlaphit
                    if self.maxLapHit < self.race.lapCount:
                        for y in self.timeLabels[self.maxLapHit - 1]:
                            y.configure(
                                text_font=ToontownGlobals.getSignFont())

                        for y in self.timeLabels[self.maxLapHit]:
                            y.show()

                        for y in self.timeLabels[self.maxLapHit]:
                            y.configure(
                                text_font=ToontownGlobals.getSignFont())

                        self.raceTimeDelta = globalClock.getFrameTime(
                        ) - self.race.baseTime
                        lapNotice = DirectLabel()
                        lapNotice.setScale(0.1)
                        if self.maxLapHit == self.race.lapCount - 1:
                            lapNotice[
                                'text'] = TTLocalizer.KartRace_FinalLapText
                        else:
                            lapNotice[
                                'text'] = TTLocalizer.KartRace_LapText % str(
                                    self.maxLapHit + 1)
                        taskMgr.doMethodLater(2,
                                              lapNotice.remove,
                                              'removeIt',
                                              extraArgs=[])
                self.lapLabel['text'] = str(
                    clampScalar(self.maxLapHit + 1, 1,
                                self.race.lapCount)) + '/' + str(
                                    self.race.lapCount)

        suffix = {
            1: TTLocalizer.KartRace_FirstSuffix,
            2: TTLocalizer.KartRace_SecondSuffix,
            3: TTLocalizer.KartRace_ThirdSuffix,
            4: TTLocalizer.KartRace_FourthSuffix
        }
        placeSorter.sort()
        for x, p in zip(placeSorter, xrange(len(placeSorter), 0, -1)):
            self.racerDict[x[1]].update(place=p + placeCount -
                                        len(placeSorter))

        localRacer = self.racerDict[localAvatar.doId]
        nearDiff, farDiff = RaceGlobals.TrackDict[self.race.trackId][8]
        if not localRacer.finished and self.faceEndPos[
                0] - localRacer.face.getX() < nearDiff:
            for racerId in self.racerDict.keys():
                racer = self.racerDict[racerId]
                if not racer.enabled or racerId == localAvatar.doId or racer.face.getX(
                ) >= self.faceEndPos[0]:
                    continue
                if self.faceEndPos[0] - racer.face.getX() < farDiff:
                    self.photoFinish = True

        if self.photoFinish:
            self.photoFinishLabel.show()
            self.placeLabelNum['text'] = ''
            self.placeLabelStr['text'] = ''
        else:
            self.photoFinishLabel.hide()
            self.placeLabelNum['text'] = str(
                self.racerDict[localAvatar.doId].place)
            self.placeLabelStr['text'] = suffix[self.racerDict[
                localAvatar.doId].place]
        minutes = int(t / 60)
        t -= minutes * 60
        seconds = int(t)
        padding = (seconds < 10 and ['0'] or [''])[0]
        t -= seconds
        fraction = str(t)[2:4]
        fraction = fraction + '0' * (2 - len(fraction))
        if self.timerEnabled and self.maxLapHit < self.race.lapCount:
            self.timeLabels[self.maxLapHit][0]['text'] = "%d'" % minutes
            self.timeLabels[self.maxLapHit][1]['text'] = "%s%d''" % (padding,
                                                                     seconds)
            self.timeLabels[self.maxLapHit][2]['text'] = '%s' % fraction
        if self.race.wrongWay and not self.wrongWaySeq.isPlaying():
            self.wrongWaySeq.loop()
        elif not self.race.wrongWay and self.wrongWaySeq.isPlaying():
            self.wrongWaySeq.finish()

    def updateRacerInfo(self, avId, curvetime=None, maxlaphit=None):
        if avId in self.racerDict.keys():
            self.racerDict[avId].update(curvetime=curvetime,
                                        maxlaphit=maxlaphit)

    def racerEntered(self, avId):
        toon = base.cr.doId2do.get(avId, None)
        kart = base.cr.doId2do.get(self.race.kartMap.get(avId, None), None)
        if not toon or not kart:
            return
        if kart.getBodyColor() == InvalidEntry:
            bodyColor = getDefaultColor()
        else:
            bodyColor = getAccessory(kart.getBodyColor())
        headframe = RaceHeadFrame(av=toon, color=bodyColor)
        eyes = headframe.head.find('**/eyes*')
        eyes.setDepthTest(1)
        eyes.setDepthWrite(1)
        headframe.configure(geom_scale=(0.5, 0.5, 0.5))
        headframe.setZ(self.faceStartPos[2])
        headframe.setDepthWrite(True)
        headframe.setDepthTest(True)
        headframe.reparentTo(self.raceModeRoot)
        self.directObjList.append(headframe)
        mapspot = loader.loadModel('phase_6/models/karting/race_mapspot')
        mapspot.setColor(bodyColor)
        mapspot.reparentTo(self.mapLines)
        mapspot.setHpr(self.mapScene, 0, 0, 0)
        self.racerDict[avId] = self.RacerInfo(headframe, mapspot)
        for key, i in zip(self.racerDict.keys(),
                          range(len(self.racerDict.keys()))):
            face = self.racerDict[key].face
            mapspot = self.racerDict[key].mapspot
            face.setX(self.faceStartPos[0])
            face.setY(-1 - 5 * (i + 1))
            face.setScale(0.15)
            mapspot.getChild(0).setY((-5 - 5 * (i + 1)) * 1000)
            mapspot.setScale(self.mapScene, 0.15)
            mapspot.setPos(self.race.startingPos[0][0])
            if key == localAvatar.doId:
                face.setY(-1)
                face.setScale(face.getScale() * 1.25)
                mapspot.getChild(0).setY(-5 * 1000)
                mapspot.setScale(mapspot.getScale() * 1.25)
                self.face = face
                self.mapspot = mapspot

        return

    def racerLeft(self, avId, unexpected=False):
        racer = self.racerDict.get(avId, None)
        if racer:
            racer.disable()
        return

    def racerFinished(self, avId, trackId, place, totalTime, entryFee, qualify,
                      winnings, bonus, trophies, circuitPoints, circuitTime):
        racer = self.racerDict.get(avId, None)
        if racer:
            racer.update(finished=True)
            racer.disable()
            self.closeButton.hide()
            self.endPanel.displayRacer(place, entryFee, qualify, winnings,
                                       trackId, bonus, trophies, racer.face,
                                       base.cr.doId2do[avId].getName(),
                                       totalTime, circuitPoints, circuitTime)
            if racer.face in self.directObjList:
                self.directObjList.remove(racer.face)
            if avId == localAvatar.doId:
                self.disableRaceMode()
                self.enableResultMode()
                self.endPanel.startWinningsPanel(entryFee, winnings, trackId,
                                                 bonus, trophies)
        return

    def racerFinishedCircuit(self, avId, place, entryFee, winnings, bonus,
                             trophies):
        racer = self.racerDict.get(avId, None)
        if racer:
            newTotalTickets = winnings + entryFee + bonus
            self.endPanel.updateWinnings(place, newTotalTickets)
            if avId == localAvatar.doId:
                self.endPanel.updateWinningsFromCircuit(
                    place, entryFee, winnings, bonus, trophies)
        return

    def circuitFinished(self, placeFixup):
        self.endPanel.circuitFinished(placeFixup)

    def setTimerEnabled(self, enabled):
        self.timerEnabled = enabled
コード例 #40
0
 def destroy(self):
     self.movie.finish()
     DirectFrame.destroy(self)
コード例 #41
0
 def destroy(self):
     self.reset()
     self.countdownTask = None
     DirectFrame.destroy(self)
コード例 #42
0
    def __init__(self, numPlayers, avIdList, votes, directions, namesList,
                 disconnectedList, directionToGo, directionReason,
                 directionTotals, *args, **kwargs):
        opts = {
            'relief': None,
            'geom': DGG.getDefaultDialogGeom(),
            'geom_color': ToontownGlobals.GlobalDialogColor[:3] + (0.8, ),
            'geom_scale': (1.75, 1, 0.75),
            'pos': (0, 0, 0.525)
        }
        opts.update(kwargs)
        DirectFrame.__init__(self, *args, **opts)
        self.initialiseoptions(VoteResultsPanel)
        listMultiplier = 1
        if TravelGameGlobals.SpoofFour:
            listMultiplier = 4
        self.avIdList = avIdList * listMultiplier
        self.numPlayers = numPlayers * listMultiplier
        self.votes = votes * listMultiplier
        self.directions = directions * listMultiplier
        self.namesList = namesList * listMultiplier
        self.disconnectedList = disconnectedList * listMultiplier
        self.directionToGo = directionToGo
        self.directionReason = directionReason
        self.directionTotals = directionTotals
        self.entryList = []
        self.rowFrame = []
        self.upDownFrame = DirectFrame(parent=self,
                                       relief=None,
                                       pos=self.getRowPos(-1))
        self.upLabel = DirectLabel(parent=self.upDownFrame,
                                   relief=None,
                                   pos=(1.2, 0, 0.0),
                                   text=TTLocalizer.TravelGameDirections[0],
                                   text_fg=(0.0, 0.0, 1.0, 1.0),
                                   text_scale=0.05,
                                   text_align=TextNode.ARight)
        self.downLabel = DirectLabel(parent=self.upDownFrame,
                                     relief=None,
                                     pos=(1.43, 0, 0.0),
                                     text=TTLocalizer.TravelGameDirections[1],
                                     text_fg=(1.0, 0.0, 0.0, 1.0),
                                     text_scale=0.05,
                                     text_align=TextNode.ARight)
        self.totalFrame = DirectFrame(parent=self,
                                      relief=None,
                                      pos=self.getRowPos(self.numPlayers))
        self.totalText = DirectLabel(parent=self.totalFrame,
                                     relief=None,
                                     pos=(1.0, 0, 0.0),
                                     text='Total',
                                     text_fg=(0.0, 0.0, 0.0, 1.0),
                                     text_scale=0.05,
                                     text_align=TextNode.ARight)
        self.totalVotesUpLabel = DirectLabel(parent=self.totalFrame,
                                             relief=None,
                                             pos=(1.2, 0, 0.0),
                                             text='',
                                             text_fg=(0.0, 0.0, 1.0, 1.0),
                                             text_scale=0.05,
                                             text_align=TextNode.ARight)
        self.totalVotesDownLabel = DirectLabel(parent=self.totalFrame,
                                               relief=None,
                                               pos=(1.43, 0, 0.0),
                                               text='',
                                               text_fg=(1.0, 0.0, 0.0, 1.0),
                                               text_scale=0.05,
                                               text_align=TextNode.ARight)
        self.totalVotesLabels = [
            self.totalVotesUpLabel, self.totalVotesDownLabel
        ]
        self.resultFrame = DirectFrame(parent=self,
                                       relief=None,
                                       pos=self.getRowPos(5))
        self.resultLabel = DirectLabel(parent=self.resultFrame,
                                       text='',
                                       text_scale=0.06,
                                       pos=(0.7, 0, 0.0),
                                       text_align=TextNode.ACenter)
        self.setupResultLabel()
        for index in range(self.numPlayers):
            frame = DirectFrame(parent=self,
                                relief=None,
                                pos=self.getRowPos(index))
            self.rowFrame.append(frame)
            nameLabel = DirectFrame(parent=frame,
                                    relief=None,
                                    pos=(0.46, 0.0, 0.0),
                                    text=self.namesList[index],
                                    text_fg=(0.0, 0.0, 0.0, 1.0),
                                    text_scale=0.05,
                                    text_align=TextNode.ACenter,
                                    text_font=DGG.getDefaultFont())
            votesUpLabel = DirectLabel(parent=frame,
                                       relief=None,
                                       pos=(1.2, 0.0, 0.0),
                                       text='',
                                       text_fg=(0, 0, 1, 1),
                                       text_scale=0.05,
                                       text_align=TextNode.ARight,
                                       text_font=DGG.getDefaultFont())
            votesDownLabel = DirectLabel(parent=frame,
                                         relief=None,
                                         pos=(1.43, 0.0, 0.0),
                                         text='',
                                         text_fg=(1, 0, 0, 1),
                                         text_scale=0.05,
                                         text_align=TextNode.ARight,
                                         text_font=DGG.getDefaultFont())
            nameLabel.hide()
            self.entryList.append((nameLabel, votesUpLabel, votesDownLabel))

        return
コード例 #43
0
    def setup(self):
        if hasattr(self, 'mainFrame'):
            self.mainFrame.destroy()
        self.mainFrame = DirectFrame(parent=self, relief=None)

        def setVisibility():
            value = self.visSlider['value']
            self.setColorScale(Vec4(1, 1, 1, value))

        self.visSlider = DirectSlider(guiId='visSlider', parent=self.mainFrame, scale=0.4, thumb_relief=DGG.FLAT, thumb_color=(0.25,
                                                                                                                               1.0,
                                                                                                                               0.25,
                                                                                                                               1), pos=(0.4, 0, -0.85), text='Visibility', text_scale=0.2, text_pos=(0,
                                                                                                                                                                                                     0.1,
                                                                                                                                                                                                     0), text_bg=(0.8,
                                                                                                                                                                                                                  0.8,
                                                                                                                                                                                                                  0.8,
                                                                                                                                                                                                                  1), value=1.0, command=setVisibility)
        self.visSlider.getChild(0).setTransparency(0)
        self.camFrame = DirectFrame(guiId='camFrame', parent=self.mainFrame, relief=DGG.RIDGE, frameSize=(0.0,
                                                                                                          0.8,
                                                                                                          0.0,
                                                                                                          0.32), frameColor=(1,
                                                                                                                             1,
                                                                                                                             0.75,
                                                                                                                             1), borderWidth=(0.005,
                                                                                                                                              0.005), pos=(0,
                                                                                                                                                           0,
                                                                                                                                                           0.6), text='Camera', text_fg=(0,
                                                                                                                                                                                         0,
                                                                                                                                                                                         0,
                                                                                                                                                                                         1), text_scale=0.05, text_pos=(0.1,
                                                                                                                                                                                                                        0.26,
                                                                                                                                                                                                                        0))
        self.camSlider = RangeSlider(guiId='zoom', label='Zoom (Y-axis)', range=(-0.75, 0.25), value=0, parent=self.camFrame, pos=(0.395,
                                                                                                                                   0,
                                                                                                                                   0.07))
        self.worldFrame = DirectFrame(guiId='worldFrame', parent=self.mainFrame, relief=DGG.RIDGE, frameSize=(0.0, 0.8, -0.55, 0.5), frameColor=(1,
                                                                                                                                                 0.75,
                                                                                                                                                 0.75,
                                                                                                                                                 1), borderWidth=(0.005,
                                                                                                                                                                  0.005), pos=(0.0,
                                                                                                                                                                               0,
                                                                                                                                                                               0), text='World', text_fg=(0,
                                                                                                                                                                                                          0,
                                                                                                                                                                                                          0,
                                                                                                                                                                                                          1), text_scale=0.05, text_pos=(0.1,
                                                                                                                                                                                                                                         0.43,
                                                                                                                                                                                                                                         0))
        self.worldPSlider = RangeSlider(guiId='worldP', label='World P', range=(-90,
                                                                                0), value=0.0, parent=self.worldFrame, pos=(0.395,
                                                                                                                            0,
                                                                                                                            0.24))
        self.worldDecorScaleSlider = RangeSlider(guiId='worldP', label='World Decor Scale', range=(0.2,
                                                                                                   0.3), value=0.25, parent=self.worldFrame, pos=(0.395,
                                                                                                                                                  0,
                                                                                                                                                  0.0))
        self.finalSlider = RangeSlider(guiId='final', label='Final', range=(0, 1), value=0, parent=self.worldFrame, pos=(0.395, 0, -0.48))
        self.saveState0Button = DirectButton(guiId='save0Button', parent=self.mainFrame, scale=0.1, pos=(0.2, 0, -0.65), borderWidth=(0.1,
                                                                                                                                      0.1), text='save pt0')
        self.saveState1Button = DirectButton(guiId='save1Button', parent=self.mainFrame, scale=0.1, pos=(0.6, 0, -0.65), borderWidth=(0.1,
                                                                                                                                      0.1), text='save pt1')
        return
コード例 #44
0
class LegendaryFish(Fish):
    
    def __init__(self, fishManager, myData, index):
        Fish.__init__(self, fishManager, myData, index)
        self.fsm = LegendaryFishFSM(self)
        self.actor.setScale(self.myData['scaleRange'][0])
        self.staminaValue = self.myData['stamina']
        self.aboutToBitingInterval = None
        self.fishChaseLureSequence = Sequence()
        self.lfStruggleSequence = Sequence()
        self.initFishStaminaBar()
        self.lurePosition = None

    
    def initFishStaminaBar(self):
        self.legendaryGui = loader.loadModel('models/minigames/pir_m_gam_fsh_legendaryGui')
        self.iconBaseFrame = DirectFrame(relief = None, state = DGG.DISABLED, pos = (0, 0, 0), sortOrder = 30, image = self.legendaryGui.find('**/pir_t_gui_fsh_fishPortraitFrame'), image_scale = 0.17999999999999999, image_pos = (0, 0, 0))
        self.iconBaseFrame.setTransparency(TransparencyAttrib.MAlpha)
        self.fishUINodePath = NodePath(self.iconBaseFrame)
        self.fishUINodePath.setPos(-0.29999999999999999, 0.0, 0.82999999999999996)
        self.fishUINodePath.reparentTo(hidden)
        self.iconCard = loader.loadModel('models/gui/treasure_gui')
        self.iconBaseFrame.iconImage = OnscreenImage(parent = self.iconBaseFrame, image = self.iconCard.find('**/%s*' % CollectionMap.Assets[self.myData['id']]), scale = 0.34999999999999998, hpr = (0, 0, 0), pos = (0.0, 0, 0.0))
        self.fishNameLabel = TextNode('fishNameLabel')
        name = self.getName().split('_')
        self.fishNameLabel.setText(name[0])
        self.fishNameLabel.setTextColor(1.0, 1.0, 1.0, 1.0)
        self.fishNameLabelNodePath = NodePath(self.fishNameLabel)
        self.fishNameLabelNodePath.setPos(0.29999999999999999, 0, 0.040000000000000001)
        self.fishNameLabelNodePath.setScale(0.044999999999999998)
        self.fishNameLabelNodePath.reparentTo(self.iconBaseFrame)
        self.fishStaminaBar = DirectWaitBar(parent = self.iconBaseFrame, relief = DGG.FLAT, state = DGG.DISABLED, range = 100, value = 0, sortOrder = 20, frameColor = (0, 0, 0, 1.0), pos = (0.070000000000000007, 0.0, -0.014999999999999999), hpr = (0, 0, 0), frameSize = (0, 0.71999999999999997, 0, 0.028000000000000001))
        self.fishStaminaBar['value'] = self.staminaValue
        self.fishStaminaBar['barColor'] = FishingGlobals.fishingStaminaBarColor[int((self.staminaValue / 100.0) * (len(FishingGlobals.fishingStaminaBarColor) - 1))]
        self.fishStaminaValueLabel = TextNode('fishStaminaValueLabel')
        self.fishStaminaValueLabel.setText(str(self.staminaValue) + '//' + str(self.staminaValue))
        self.fishStaminaValueLabel.setTextColor(1.0, 1.0, 1.0, 1.0)
        self.fishStaminaValueLabelNodePath = NodePath(self.fishStaminaValueLabel)
        self.fishStaminaValueLabelNodePath.setPos(0.66000000000000003, 0, -0.059999999999999998)
        self.fishStaminaValueLabelNodePath.setScale(0.044999999999999998)
        self.fishStaminaValueLabelNodePath.reparentTo(self.iconBaseFrame)
        self.fishStaminaBarFrame = DirectLabel(parent = self.iconBaseFrame, relief = None, state = DGG.DISABLED, frameColor = (1, 1, 1, 0.10000000000000001), pos = (0.44, 0.0, 0.0), hpr = (0, 0, 0), sortOrder = 25, image = self.legendaryGui.find('**/pir_t_gui_fsh_staminaBarForeground'), image_scale = (1.0, 0.0, 0.050000000000000003), image_pos = (0.0, 0.0, 0.0), image_hpr = (0.0, 0.0, 0.0))
        self.fishStaminaBarFrame.setTransparency(TransparencyAttrib.MAlpha)
        self.fishStaminaBarFrame.setDepthTest(True)
        self.fishStaminaBarFrame.setDepthWrite(True)

    
    def cleanFishData(self):
        self.staminaValue = self.myData['stamina']
        self.fishStaminaBar['value'] = self.staminaValue
        self.fishStaminaValueLabel.setText(str(int(self.staminaValue)) + ' / ' + str(100))
        self.fishStaminaBar['barColor'] = FishingGlobals.fishingStaminaBarColor[int((self.staminaValue / 100.0) * (len(FishingGlobals.fishingStaminaBarColor) - 1))]
        self.hideStaminaBar()
        taskMgr.remove('updateFishStaminaTask')
        self.lurePosition = None
        self.fishChaseLureSequence.pause()
        self.fishChaseLureSequence.clearToInitial()
        self.lfStruggleSequence.pause()
        self.lfStruggleSequence.clearToInitial()
        if self.aboutToBitingInterval is None:
            return None
        
        self.aboutToBitingInterval.pause()

    
    def destroy(self):
        self.fishUINodePath.removeNode()
        Fish.destroy(self)

    
    def updateFishStaminaTask(self, task = None):
        if self.staminaValue <= 1:
            return Task.done
        
        self.staminaValue = max(1, self.staminaValue - FishingGlobals.staminaReduceValue)
        self.fishStaminaValueLabel.setText(str(int(self.staminaValue)) + ' / ' + str(100))
        self.fishStaminaBar['value'] = self.staminaValue
        self.fishStaminaBar['barColor'] = FishingGlobals.fishingStaminaBarColor[int((self.staminaValue / 100.0) * (len(FishingGlobals.fishingStaminaBarColor) - 1))]
        return Task.cont

    
    def updateFishStaminaBar(self):
        self.fishStaminaBar['value'] = self.staminaValue

    
    def fishStaminaConsume(self):
        taskMgr.add(self.updateFishStaminaTask, 'updateFishStaminaTask')

    
    def staminaPercentage(self):
        return self.staminaValue / self.myData['stamina']

    
    def showStaminaBar(self):
        self.fishUINodePath.reparentTo(aspect2d)

    
    def hideStaminaBar(self):
        self.fishUINodePath.reparentTo(hidden)

    
    def performStraightBehavior(self, lurePos, dt):
        newX = self.getX() + self.velocity[0] * dt + self.accel[0] * dt * dt
        newZ = self.getZ() + self.velocity[2] * dt + self.accel[2] * dt * dt
        return (newX, newZ)
コード例 #45
0
class DistributedMoleField(DistributedNodePathEntity,
                           MoleFieldBase.MoleFieldBase):

    notify = DirectNotifyGlobal.directNotify.newCategory(
        'DistributedMoleField')

    ScheduleTaskName = 'moleFieldScheduler'

    def __init__(self, cr):
        """Construct the mole field."""
        DistributedNodePathEntity.__init__(self, cr)
        self.gameStarted = False
        self.moleHills = []
        self.numMolesWhacked = 0
        self.timer = None
        self.frame2D = None
        self.isToonInRange = 0
        self.detectCount = 0
        self.cameraHold = None
        self.activeField = 1
        self.dimensionX = 0.0
        self.dimensionY = 0.0
        self.gameText = TTLocalizer.MolesInstruction
        self.winText = TTLocalizer.MolesFinished
        self.pityWinText = TTLocalizer.MolesPityWin
        self.restartedText = TTLocalizer.MolesRestarted
        self.toonHitTracks = {}
        self.hasRestarted = 0
        self.hasEntered = 0
        self.MolesWhackedTarget = 1000
        self.GameDuration = 1000

    def disable(self):
        """Disable the mole field."""
        self.cleanupTimer()
        for ival in list(self.toonHitTracks.values()):
            ival.finish()
        self.toonHitTracks = {}
        DistributedNodePathEntity.disable(self)
        taskMgr.remove(self.detectName)
        self.ignoreAll()

    def delete(self):
        """Delete the mole field."""
        self.soundBomb = None
        self.soundBomb2 = None
        self.soundCog = None
        DistributedNodePathEntity.delete(self)
        self.stopScheduleTask()
        for mole in self.moleHills:
            mole.destroy()
        self.moleHills = []
        self.cleanupTimer()
        self.unloadGui()

    def announceGenerate(self):
        """Load fields dependent on required fields."""
        DistributedNodePathEntity.announceGenerate(self)
        self.loadModel()
        self.loadGui()
        self.detectName = (("moleField %s") % (self.doId))
        taskMgr.doMethodLater(0.1, self.__detect, self.detectName)
        self.calcDimensions()
        self.notify.debug('announceGenerate doId=%d entId=%d' %
                          (self.doId, self.entId))

    def setNumSquaresX(self, num):
        self.numSquaresX = num
        self.calcDimensions()

    def setNumSquaresY(self, num):
        self.numSquaresY = num
        self.calcDimensions()

    def setSpacingX(self, num):
        self.spacingX = num
        self.calcDimensions()

    def setSpacingY(self, num):
        self.spacingY = num
        self.calcDimensions()

    def calcDimensions(self):
        self.dimensionX = self.numSquaresX * self.spacingX
        self.dimensionY = self.numSquaresY * self.spacingY
        self.centerCenterNode()

    def loadModel(self):
        """Create the field and load the assets."""
        moleIndex = 0
        self.moleHills = []
        for indexY in range(self.numSquaresY):
            for indexX in range(self.numSquaresX):
                xPos = indexX * self.spacingX
                yPos = indexY * self.spacingY
                newMoleHill = MoleHill.MoleHill(xPos, yPos, 0, self, moleIndex)
                newMoleHill.reparentTo(self)
                self.moleHills.append(newMoleHill)
                moleIndex += 1
        self.numMoles = len(self.moleHills)
        self.centerNode = self.attachNewNode('center')
        self.centerCenterNode()
        self.soundBomb = base.loadSfx("phase_12/audio/sfx/Mole_Surprise.mp3")
        self.soundBomb2 = base.loadSfx("phase_3.5/audio/dial/AV_pig_howl.mp3")
        self.soundCog = base.loadSfx("phase_12/audio/sfx/Mole_Stomp.mp3")
        self.soundUp = base.loadSfx("phase_4/audio/sfx/MG_Tag_C.mp3")
        self.soundDown = base.loadSfx("phase_4/audio/sfx/MG_cannon_whizz.mp3")
        upInterval = SoundInterval(self.soundUp, loop=0)
        downInterval = SoundInterval(self.soundDown, loop=0)
        self.soundIUpDown = Sequence(upInterval, downInterval)

    def centerCenterNode(self):
        self.centerNode.setPos(self.dimensionX * 0.5, self.dimensionY * 0.5,
                               0.0)

    def loadGui(self):
        """Create the GUI."""
        self.frame2D = DirectFrame(scale=1.0,
                                   pos=(0.0, 0, 0.90),
                                   relief=DGG.FLAT,
                                   parent=aspect2d,
                                   frameSize=(-0.3, 0.3, -0.05, 0.05),
                                   frameColor=(0.737, 0.573, 0.345, 0.300))
        self.scoreLabel = DirectLabel(
            parent=self.frame2D,
            relief=None,
            #image = gui2.find("**/QuitBtn_UP"),
            pos=(0, 0, 0),
            scale=1.0,
            text="",
            text_font=ToontownGlobals.getSignFont(),
            text0_fg=(1, 1, 1, 1),
            text_scale=0.075,
            text_pos=(0, -0.02),
        )
        self.updateGuiScore()
        self.frame2D.hide()

    def unloadGui(self):
        """Cleanup the GUI."""
        self.frame2D.destroy()
        self.frame2D = None

    def setGameStart(self, timestamp, molesWhackTarget, totalTime):
        """
        This method gets called from the AI when all avatars are ready
        Ready usually means they have read the rules
        Inheritors should call this plus the code to start the game
        """
        self.GameDuration = totalTime
        self.MolesWhackedTarget = molesWhackTarget
        self.activeField = 1
        self.isToonInRange = 0
        self.scheduleMoles()
        self.notify.debug("%d setGameStart: Starting game" % self.doId)
        self.gameStartTime = \
                    globalClockDelta.networkToLocalTime(timestamp)
        self.gameStarted = True
        for hill in self.moleHills:
            hill.setGameStartTime(self.gameStartTime)
        curGameTime = self.getCurrentGameTime()
        timeLeft = self.GameDuration - curGameTime
        self.cleanupTimer()
        self.timer = ToontownTimer.ToontownTimer()
        self.timer.posBelowTopRightCorner()
        self.timer.setTime(timeLeft)
        self.timer.countdown(timeLeft, self.timerExpired)

        self.startScheduleTask()
        self.frame2D.show()
        if self.hasRestarted:
            self.level.countryClub.showInfoText(self.restartedText)
            self.sendUpdate("damageMe", [])
        else:
            self.hasRestarted = 1

        self.updateGuiScore()

    # time-related utility functions
    def local2GameTime(self, timestamp):
        """
        given a local-time timestamp, returns the corresponding
        timestamp relative to the start of the game
        """
        return timestamp - self.gameStartTime

    def game2LocalTime(self, timestamp):
        """
        given a game-time timestamp, returns the corresponding
        local timestamp
        """
        return timestamp + self.gameStartTime

    def getCurrentGameTime(self):
        return self.local2GameTime(globalClock.getFrameTime())

    def startScheduleTask(self):
        taskMgr.add(self.scheduleTask, self.ScheduleTaskName)

    def stopScheduleTask(self):
        taskMgr.remove(self.ScheduleTaskName)

    def scheduleTask(self, task):
        curTime = self.getCurrentGameTime()

        # start all the drops thatpopups should already be happening
        # the drop schedule is a time-ordered list of
        # (time, moleIndex, curMoveUpTime, curStayUpTime, curMoveDownTime) tuples
        while self.schedule and self.schedule[0][
                0] <= curTime and self.activeField:
            popupInfo = self.schedule[0]
            # pop this one off the front
            self.schedule = self.schedule[1:]
            startTime, moleIndex, curMoveUpTime, curStayUpTime, curMoveDownTime, moleType = popupInfo
            hill = self.moleHills[moleIndex]
            hill.doMolePop(startTime, curMoveUpTime, curStayUpTime,
                           curMoveDownTime, moleType)
            #self.notify.debug('popping mole=%d' % moleIndex)

        if self.schedule:
            return task.cont
        else:
            return task.done

    def handleEnterHill(self, colEntry):
        """Handle the toon hitting one of the mole hills."""
        if not self.gameStarted:
            self.notify.debug('sending clientTriggered for %d' % self.doId)
            self.sendUpdate('setClientTriggered', [])

    def handleEnterMole(self, colEntry):
        """Handle the toon hitting one of the moles."""
        if not self.gameStarted:
            self.notify.debug('sending clientTriggered for %d' % self.doId)
            self.sendUpdate('setClientTriggered', [])
        surfaceNormal = colEntry.getSurfaceNormal(render)
        self.notify.debug('surfaceNormal=%s' % surfaceNormal)
        into = colEntry.getIntoNodePath()
        moleIndex = int(into.getName().split('-')[-1])
        self.notify.debug('hit mole %d' % moleIndex)
        moleHill = self.moleHills[moleIndex]
        moleHill.stashMoleCollision()
        popupNum = moleHill.getPopupNum()
        if moleHill.hillType == MoleFieldBase.HILL_MOLE:
            #print "blamO!"
            #self.__showToonHitByBomb(localAvatar.doId)
            timestamp = globalClockDelta.getFrameNetworkTime()
            moleHill.setHillType(MoleFieldBase.HILL_WHACKED)
            self.sendUpdate('whackedBomb', [moleIndex, popupNum, timestamp])
            self.__showToonHitByBomb(localAvatar.doId, moleIndex, timestamp)
        elif moleHill.hillType == MoleFieldBase.HILL_BOMB:
            #print ("type %s" % (moleHill.hillType))
            moleHill.setHillType(MoleFieldBase.HILL_COGWHACKED)
            self.soundCog.play()
            self.sendUpdate('whackedMole', [moleIndex, popupNum])

    def updateMole(self, moleIndex, status):
        """Handle the AI telling us a mole has been whacked."""
        assert self.notify.debugStateCall(self)
        if status == self.WHACKED:
            moleHill = self.moleHills[moleIndex]
            if not moleHill.hillType == MoleFieldBase.HILL_COGWHACKED:
                moleHill.setHillType(MoleFieldBase.HILL_COGWHACKED)
                self.soundCog.play()
            #self.soundCog.play()
            moleHill.doMoleDown()

    def updateGuiScore(self):
        """Show the score on the gui."""
        molesLeft = self.MolesWhackedTarget - self.numMolesWhacked
        if self.frame2D and hasattr(self, 'scoreLabel') and (molesLeft >= 0):
            newText = TTLocalizer.MolesLeft % molesLeft
            self.scoreLabel['text'] = newText

    def setScore(self, score):
        """Handle the AI telling us the new score."""
        self.notify.debug('score=%d' % score)
        self.numMolesWhacked = score
        self.updateGuiScore()
        molesLeft = self.MolesWhackedTarget - self.numMolesWhacked
        if molesLeft == 0:
            self.gameWon()

    def cleanupTimer(self):
        """Stop and remove the molefield timer."""
        if self.timer:
            self.timer.stop()
            self.timer.destroy()
            self.timer = None

    def timerExpired(self):
        """Show something when the timer expires."""
        assert self.notify.debugStateCall(self)
        self.cleanupTimer()
        self.cleanDetect()

    def gameWon(self):
        """Handle the toons winning the game."""
        for hill in self.moleHills:
            hill.forceMoleDown()
        self.cleanupTimer()
        self.frame2D.hide()
        self.level.countryClub.showInfoText(self.winText)
        self.cleanDetect()

    def setPityWin(self):
        """He's lost 4 times in a row, open the doors for him."""
        for hill in self.moleHills:
            hill.forceMoleDown()
        self.cleanupTimer()
        self.frame2D.hide()
        self.level.countryClub.showInfoText(self.pityWinText)
        self.cleanDetect()

    def cleanDetect(self):
        self.activeField = 0
        self.doToonOutOfRange()

    def __detect(self, task):
        #print "detect beat"

        distance = self.centerNode.getDistance(localAvatar)
        greaterDim = self.dimensionX
        if self.dimensionY > self.dimensionX:
            greaterDim = self.gridScaleY

        self.detectCount += 1
        if self.detectCount > 5:
            #print("Range:%s Dimension:%s" % (distance, greaterDim * 0.75))
            self.detectCount = 0

        if distance < (greaterDim * 0.75):
            if not self.isToonInRange:
                self.doToonInRange()
        else:
            if self.isToonInRange:
                self.doToonOutOfRange()

        taskMgr.doMethodLater(0.1, self.__detect, self.detectName)
        return Task.done

    def doToonInRange(self):
        #print("toon in Range")
        if not self.gameStarted:
            self.notify.debug('sending clientTriggered for %d' % self.doId)
            self.sendUpdate('setClientTriggered', [])

        self.isToonInRange = 1
        if self.activeField:
            #self.cameraHold = base.localAvatar.getIdealCameraPos()
            self.setUpCamera()

            if not self.hasEntered:
                self.level.countryClub.showInfoText(self.gameText)
                self.hasEntered = 1

    def setUpCamera(self):
        camHeight = base.localAvatar.getClampedAvatarHeight()
        heightScaleFactor = (camHeight * 0.3333333333)
        defLookAt = Point3(0.0, 1.5, camHeight)

        cameraPoint = Point3(0.0, (-22.0 * heightScaleFactor),
                             (camHeight + 12.0))

        #base.localAvatar.setCameraSettings(cameraSetting[0])
        base.localAvatar.setIdealCameraPos(cameraPoint)

    def doToonOutOfRange(self):
        #print("toon out of Range")
        self.isToonInRange = 0
        #base.localAvatar.setIdealCameraPos(self.cameraHold)
        base.localAvatar.setCameraPositionByIndex(base.localAvatar.cameraIndex)
        self.cameraHold = None

    def reportToonHitByBomb(self, avId, moleIndex, timestamp):
        if avId != localAvatar.doId:
            self.__showToonHitByBomb(avId, moleIndex, timestamp)
            moleHill = self.moleHills[moleIndex]
            if not moleHill.hillType == MoleFieldBase.HILL_WHACKED:
                moleHill.setHillType(MoleFieldBase.HILL_WHACKED)
                self.soundCog.play()
            #self.soundCog.play()
            moleHill.doMoleDown()

    def __showToonHitByBomb(self, avId, moleIndex, timestamp=0):
        toon = base.cr.doId2do.get(avId)
        moleHill = self.moleHills[moleIndex]
        if toon == None:
            return

        #print("Toon info")
        #print("Pos %s" % (toon.getPos()))
        #print("Parent %s" % (toon.getParent()))
        rng = random.Random(timestamp)

        # make sure this toon's old track is done
        curPos = toon.getPos(render)
        oldTrack = self.toonHitTracks.get(avId)
        if oldTrack:
            if oldTrack.isPlaying():
                oldTrack.finish()
        # preserve the toon's current position, in case he gets hit
        # by two suits at a time
        toon.setPos(curPos)
        toon.setZ(self.getZ())

        # put the toon under a new node
        assert (toon.getParent() == render)
        parentNode = render.attachNewNode('mazeFlyToonParent-' + repr(avId))
        parentNode.setPos(toon.getPos(render))
        toon.reparentTo(parentNode)
        toon.setPos(0, 0, 0)

        # shoot the toon up into the air
        startPos = parentNode.getPos()

        # make a copy of the toon's dropshadow
        dropShadow = toon.dropShadow.copyTo(parentNode)
        dropShadow.setScale(toon.dropShadow.getScale(render))

        trajectory = Trajectory.Trajectory(0,
                                           Point3(0, 0, 0),
                                           Point3(0, 0, 50),
                                           gravMult=1.)
        flyDur = trajectory.calcTimeOfImpactOnPlane(0.)
        assert (flyDur > 0)

        # choose a random landing point

        endTile = [
            rng.randint(0, self.numSquaresX - 1),
            rng.randint(0, self.numSquaresY - 1)
        ]

        endWorldCoords = (self.getX(render) + (endTile[0] * self.spacingX),
                          self.getY(render) + (endTile[1] * self.spacingY))
        endPos = Point3(endWorldCoords[0], endWorldCoords[1], startPos[2])

        def flyFunc(t,
                    trajectory,
                    startPos=startPos,
                    endPos=endPos,
                    dur=flyDur,
                    moveNode=parentNode,
                    flyNode=toon):
            u = (t / dur)
            moveNode.setX(startPos[0] + (u * (endPos[0] - startPos[0])))
            moveNode.setY(startPos[1] + (u * (endPos[1] - startPos[1])))
            # set the full position, since the toon might get banged
            # by telemetry
            if flyNode and not flyNode.isEmpty():
                # flyNode could be empty if we teleported out and another toon was flying
                flyNode.setPos(trajectory.getPos(t))

        def safeSetHpr(node, hpr):
            if node and not node.isEmpty():
                node.setHpr(hpr)

        flyTrack = Sequence(LerpFunctionInterval(flyFunc,
                                                 fromData=0.,
                                                 toData=flyDur,
                                                 duration=flyDur,
                                                 extraArgs=[trajectory]),
                            name=toon.uniqueName("hitBySuit-fly"))

        # if localtoon, move the camera to get a better view
        if avId != localAvatar.doId:
            cameraTrack = Sequence()
        else:
            # keep the camera parent node on the ground
            # with the toon parent node
            base.localAvatar.stopUpdateSmartCamera()
            self.camParentHold = camera.getParent()
            self.camParent = base.localAvatar.attachNewNode('iCamParent')
            self.camParent.setPos(self.camParentHold.getPos())
            self.camParent.setHpr(self.camParentHold.getHpr())
            camera.reparentTo(self.camParent)
            self.camParent.reparentTo(parentNode)
            startCamPos = camera.getPos()

            destCamPos = camera.getPos()
            # trajectory starts at Z==0, ends at Z==0
            zenith = trajectory.getPos(flyDur / 2.)[2]
            # make the camera go up above the toon's zenith...
            destCamPos.setZ(zenith * 1.3)
            # and pull in fairly far towards the toon
            destCamPos.setY(destCamPos[1] * .3)

            # make sure the camera keeps looking at the toon
            def camTask(task,
                        zenith=zenith,
                        flyNode=toon,
                        startCamPos=startCamPos,
                        camOffset=destCamPos - startCamPos):
                # move the camera proportional to the current height
                # of the toon wrt the height of its total trajectory
                u = flyNode.getZ() / zenith
                #camera.setPos(startCamPos + (camOffset * u))
                camera.lookAt(toon)
                return Task.cont

            camTaskName = "mazeToonFlyCam-" + repr(avId)
            taskMgr.add(camTask, camTaskName, priority=20)

            def cleanupCamTask(self=self,
                               toon=toon,
                               camTaskName=camTaskName,
                               startCamPos=startCamPos):
                taskMgr.remove(camTaskName)
                self.camParent.reparentTo(toon)
                camera.setPos(startCamPos)
                camera.lookAt(toon)
                camera.reparentTo(self.camParentHold)
                base.localAvatar.startUpdateSmartCamera()
                self.setUpCamera()

            cameraTrack = Sequence(Wait(flyDur),
                                   Func(cleanupCamTask),
                                   name="hitBySuit-cameraLerp")

        # make the toon spin in H and P
        # it seems like we need to put the rotations on two different
        # nodes in order to avoid interactions between the rotations
        geomNode = toon.getGeomNode()

        # apply the H rotation around the geomNode, since it's OK
        # to spin the toon in H at a node at his feet
        startHpr = geomNode.getHpr()
        destHpr = Point3(startHpr)
        # make the toon rotate in h 1..7 times
        hRot = rng.randrange(1, 8)
        if rng.choice([0, 1]):
            hRot = -hRot
        destHpr.setX(destHpr[0] + (hRot * 360))
        spinHTrack = Sequence(LerpHprInterval(geomNode,
                                              flyDur,
                                              destHpr,
                                              startHpr=startHpr),
                              Func(safeSetHpr, geomNode, startHpr),
                              name=toon.uniqueName("hitBySuit-spinH"))

        # put an extra node above the geomNode, so we can spin the
        # toon in P around his waist
        parent = geomNode.getParent()
        rotNode = parent.attachNewNode('rotNode')
        geomNode.reparentTo(rotNode)
        rotNode.setZ(toon.getHeight() / 2.)
        oldGeomNodeZ = geomNode.getZ()
        geomNode.setZ(-toon.getHeight() / 2.)

        # spin the toon in P around his waist
        startHpr = rotNode.getHpr()
        destHpr = Point3(startHpr)
        # make the toon rotate in P 1..2 times
        pRot = rng.randrange(1, 3)
        if rng.choice([0, 1]):
            pRot = -pRot
        destHpr.setY(destHpr[1] + (pRot * 360))
        spinPTrack = Sequence(LerpHprInterval(rotNode,
                                              flyDur,
                                              destHpr,
                                              startHpr=startHpr),
                              Func(safeSetHpr, rotNode, startHpr),
                              name=toon.uniqueName("hitBySuit-spinP"))

        # play some sounds
        #i = self.avIdList.index(avId)
        soundTrack = Sequence()

        #    Func(base.playSfx, self.sndTable['hitBySuit'][i]),
        #    Wait(flyDur * (2./3.)),
        #    SoundInterval(self.sndTable['falling'][i],
        #                  duration=(flyDur*(1./3.))),
        #    name=toon.uniqueName("hitBySuit-soundTrack"))

        def preFunc(self=self, avId=avId, toon=toon, dropShadow=dropShadow):
            forwardSpeed = toon.forwardSpeed
            rotateSpeed = toon.rotateSpeed

            if avId == localAvatar.doId:
                # disable control of local toon
                #self.orthoWalk.stop()
                toon.stopSmooth()
                base.cr.playGame.getPlace().fsm.request('stopped')
            else:
                toon.stopSmooth()

            # preserve old bug/feature where toon would be running in the air
            # if toon was moving, make him continue to run
            if forwardSpeed or rotateSpeed:
                toon.setSpeed(forwardSpeed, rotateSpeed)

            # set toon's speed to zero to stop any walk animations
            # leave it, it's funny to see toon running in mid-air
            #toon.setSpeed(0,0)

            # hide the toon's dropshadow
            toon.dropShadow.hide()

        def postFunc(self=self,
                     avId=avId,
                     oldGeomNodeZ=oldGeomNodeZ,
                     dropShadow=dropShadow,
                     parentNode=parentNode):
            if avId == localAvatar.doId:
                base.localAvatar.setPos(endPos)
                # game may have ended by now, check
                if hasattr(self, 'orthoWalk'):
                    # re-enable control of local toon
                    self.orthoWalk.start()

            # get rid of the dropshadow
            dropShadow.removeNode()
            del dropShadow

            # show the toon's dropshadow
            if toon and toon.dropShadow:
                toon.dropShadow.show()

            # get rid of the extra nodes
            geomNode = toon.getGeomNode()
            rotNode = geomNode.getParent()
            baseNode = rotNode.getParent()
            geomNode.reparentTo(baseNode)
            rotNode.removeNode()
            del rotNode
            geomNode.setZ(oldGeomNodeZ)

            toon.reparentTo(render)
            toon.setPos(endPos)
            parentNode.removeNode()
            del parentNode

            if avId == localAvatar.doId:
                toon.startSmooth()
                place = base.cr.playGame.getPlace()
                if place and hasattr(place, 'fsm'):
                    place.fsm.request('walk')
            else:
                toon.startSmooth()

        # call the preFunc _this_frame_ to ensure that the local toon
        # update task does not run this frame
        preFunc()

        hitTrack = Sequence(
            Func(toon.setPos, Point3(0.0, 0.0, 0.0)),
            Wait(0.25),
            Parallel(
                flyTrack,
                cameraTrack,
                self.soundIUpDown,
                #Parallel(flyTrack, self.soundIUpDown,
                spinHTrack,
                spinPTrack,
                soundTrack),
            Func(postFunc),
            name=toon.uniqueName("hitBySuit"))

        self.toonHitTracks[avId] = hitTrack
        hitTrack.start()  #globalClockDelta.localElapsedTime(timestamp))
        posM = moleHill.getPos(render)
        posN = Point3(posM[0], posM[1], posM[2] + 4.0)
        #kapow = MovieUtil.createKapowExplosionTrack(render, posN, 3.0)
        #kapow.start()
        self.soundBomb.play()
        self.soundBomb2.play()
コード例 #46
0
 def show(self):
     taskMgr.add(self.initMarker, 'questMapInit')
     DirectFrame.show(self)
     self.mapOpenButton.hide()
     if self.container['image']:
         self.mapCloseButton.show()
コード例 #47
0
ファイル: pregame.py プロジェクト: H3LLB0Y/Centipede
class Pregame():
    def __init__(self, showbase):
        self.showbase = showbase

        self.ready = False

        self.background = DirectFrame(
            frameSize=(-1, 1, -1, 1),
            frameTexture='media/gui/mainmenu/menu.png',
            parent=self.showbase.render2d,
        )

        self.title = OnscreenText(text='Lobby!',
                                  fg=(1, 1, 1, 1),
                                  parent=self.background,
                                  pos=(-0.6, 0.1),
                                  scale=0.06)

        self.buttons = []
        controlButtons = Vec3(-0.60, 0, -0.79)
        # Toggle ready
        p = controlButtons + Vec3(-0.25, 0, 0)
        self.toggleReadyButton = DirectButton(
            text='Ready/Unready',
            pos=p,
            scale=0.048,
            relief=DGG.GROOVE,
            command=self.toggleReady,
        )
        self.buttons.append(self.toggleReadyButton)
        # Disconnect
        p = controlButtons + Vec3(0.0, 0.0, 0.0)
        self.disconnectButton = DirectButton(
            text='Disconnect',
            pos=p,
            scale=0.048,
            relief=DGG.GROOVE,
            command=self.disconnect,
        )
        self.buttons.append(self.disconnectButton)

        # Send message
        p = controlButtons + Vec3(0.25, 0.0, 0.0)
        self.sendMessageButton = DirectButton(
            text='Send Message',
            pos=p,
            scale=0.048,
            relief=DGG.GROOVE,
            command=self.sendMessage,
            extraArgs=[''],
        )
        self.buttons.append(self.sendMessageButton)
        # Message input
        self.message = DirectEntry(
            command=self.sendMessage,
            focusInCommand=self.clearText,
            frameSize=(-3, 3, -.5, 1),
            initialText='',
            parent=self.buttons[2],
            pos=(0, -0.6, -1.5),
            text_align=TextNode.ACenter,
        )

        self.showbase.gameData = GameData()

        self.showbase.users = []

        self.hide()

    def clearText(self):
        self.message.set('')

    def reset(self):
        self.messages = []
        self.showbase.users = []

    def updateLobby(self, task):
        temp = self.showbase.client.getData()
        for package in temp:
            if len(package) == 2:
                print 'Received: ', str(package)
                if package[0] == 'chat':
                    if len(package[1]) == 2:
                        self.messages.append(package[1])
                        print self.messages
                elif package[0] == 'client':
                    self.showbase.users.append(User(package[1]))
                    for user in self.showbase.users:
                        print user.name, user.ready
                    print 'all users'
                elif package[0] == 'ready':
                    for user in self.showbase.users:
                        if user.name == package[1][0]:
                            user.ready = package[1][1]
                    for user in self.showbase.users:
                        print user.name, user.ready
                    print 'all users'
                elif package[0] == 'disconnect':
                    for user in self.showbase.users:
                        if user.name == package[1]:
                            self.showbase.users.remove(user)
                    for user in self.showbase.users:
                        print user.name, user.ready
                    print 'all users'
                elif package[0] == 'gamedata':
                    self.showbase.gameData.unpackageData(package[1])
                elif package[0] == 'state':
                    print 'state: ', package[1]
                    if package[1] == 'preround':
                        self.showbase.startRound()
                        return task.done
        return task.again

    def toggleReady(self):
        self.ready = not self.ready
        self.showbase.client.sendData(('ready', self.ready))

    def disconnect(self):
        self.showbase.client.sendData(('disconnect', 'disconnect'))
        self.showbase.authCon = self.showbase.client
        self.showbase.returnToMenu()

    def sendMessage(self, message):
        if message == '':
            message = self.message.get()
        if message != '':
            self.showbase.client.sendData(('chat', message))
            self.message.set('')

    def hide(self):
        self.background.hide()
        self.message.hide()
        for b in self.buttons:
            b.hide()

        self.showbase.taskMgr.remove('Update Lobby')

    def show(self):
        self.background.show()
        self.message.show()
        for b in self.buttons:
            b.show()

        # Add the game loop procedure to the task manager.
        self.showbase.taskMgr.add(self.updateLobby, 'Update Lobby')
コード例 #48
0
class QuestMap(DirectFrame):

    def __init__(self, av, **kw):
        DirectFrame.__init__(self, relief=None, sortOrder=50)
        self.initialiseoptions(QuestMap)
        self.container = DirectFrame(parent=self, relief=None)
        self.marker = DirectFrame(parent=self.container, relief=None)
        self.cogInfoFrame = DirectFrame(parent=self.container, relief=None)
        cm = CardMaker('bg')
        cm.setFrame(-0.5, 0.5, -0.5, 0.5)
        bg = self.cogInfoFrame.attachNewNode(cm.generate())
        bg.setTransparency(1)
        bg.setColor(0.5, 0.5, 0.5, 0.5)
        bg.setBin('fixed', 0)
        self.cogInfoFrame['geom'] = bg
        self.cogInfoFrame['geom_pos'] = (0, 0, 0)
        self.cogInfoFrame['geom_scale'] = (6, 1, 2)
        self.cogInfoFrame.setScale(0.05)
        self.cogInfoFrame.setPos(0, 0, 0.6)
        self.buildingMarkers = []
        self.av = av
        self.wantToggle = False
        if base.config.GetBool('want-toggle-quest-map', True):
            self.wantToggle = True
        self.updateMarker = True
        self.cornerPosInfo = None
        self.hqPosInfo = None
        self.fishingSpotInfo = None
        self.load()
        self.setScale(1.5)
        bg.removeNode()
        self.hoodId = None
        self.zoneId = None
        self.suitPercentage = {}
        for currHoodInfo in SuitPlannerBase.SuitPlannerBase.SuitHoodInfo:
            tracks = currHoodInfo[SuitPlannerBase.SuitPlannerBase.SUIT_HOOD_INFO_TRACK]
            self.suitPercentage[currHoodInfo[SuitPlannerBase.SuitPlannerBase.SUIT_HOOD_INFO_ZONE]] = tracks

        return

    def load(self):
        gui = loader.loadModel('phase_4/models/questmap/questmap_gui')
        icon = gui.find('**/tt_t_gui_qst_arrow')
        iconNP = aspect2d.attachNewNode('iconNP')
        icon.reparentTo(iconNP)
        icon.setR(90)
        self.marker['geom'] = iconNP
        self.marker['image'] = iconNP
        self.marker.setScale(0.05)
        iconNP.removeNode()
        self.mapOpenButton = DirectButton(image=(gui.find('**/tt_t_gui_qst_mapClose'), gui.find('**/tt_t_gui_qst_mapClose'), gui.find('**/tt_t_gui_qst_mapTryToOpen')), relief=None, pos=(1.25, 0, -0.63), scale=0.205, command=self.show)
        self.mapCloseButton = DirectButton(image=(gui.find('**/tt_t_gui_qst_mapOpen'), gui.find('**/tt_t_gui_qst_mapOpen'), gui.find('**/tt_t_gui_qst_mapTryToClose')), relief=None, pos=(1.25, 0, -0.63), scale=0.205, command=self.hide)
        self.mapOpenButton.hide()
        self.mapCloseButton.hide()
        gui.removeNode()
        icons = loader.loadModel('phase_3/models/gui/cog_icons')
        cIcon = icons.find('**/CorpIcon')
        lIcon = icons.find('**/LegalIcon')
        mIcon = icons.find('**/MoneyIcon')
        sIcon = icons.find('**/SalesIcon')
        cogInfoTextColor = (0.2, 0.2, 0.2, 1)
        textPos = (1.2, -0.2)
        textScale = 0.8
        self.cInfo = DirectLabel(parent=self.cogInfoFrame, text='', text_fg=cogInfoTextColor, text_pos=textPos, text_scale=textScale, geom=cIcon, geom_pos=(-0.2, 0, 0), geom_scale=0.8, relief=None)
        self.cInfo.setPos(-2.2, 0, 0.5)
        self.lInfo = DirectLabel(parent=self.cogInfoFrame, text_fg=cogInfoTextColor, text='', text_pos=textPos, text_scale=textScale, geom=lIcon, geom_pos=(-0.2, 0, 0), geom_scale=0.8, relief=None)
        self.lInfo.setPos(-2.2, 0, -0.5)
        self.mInfo = DirectLabel(parent=self.cogInfoFrame, text_fg=cogInfoTextColor, text='', text_pos=textPos, text_scale=textScale, geom=mIcon, geom_pos=(-0.2, 0, 0), geom_scale=0.8, relief=None)
        self.mInfo.setPos(0.8, 0, 0.5)
        self.sInfo = DirectLabel(parent=self.cogInfoFrame, text_fg=cogInfoTextColor, text='', text_pos=textPos, text_scale=textScale, geom=sIcon, geom_pos=(-0.2, 0, 0), geom_scale=0.8, relief=None)
        self.sInfo.setPos(0.8, 0, -0.5)
        icons.removeNode()
        return

    def updateCogInfo(self):
        currPercentage = self.suitPercentage.get(self.zoneId)
        if currPercentage is None:
            return
        self.cInfo['text'] = '%s%%' % currPercentage[0]
        self.lInfo['text'] = '%s%%' % currPercentage[1]
        self.mInfo['text'] = '%s%%' % currPercentage[2]
        self.sInfo['text'] = '%s%%' % currPercentage[3]
        return

    def destroy(self):
        self.ignore('questPageUpdated')
        self.mapOpenButton.destroy()
        self.mapCloseButton.destroy()
        del self.mapOpenButton
        del self.mapCloseButton
        DirectFrame.destroy(self)

    def putBuildingMarker(self, pos, hpr = (0, 0, 0), mapIndex = None):
        marker = DirectLabel(parent=self.container, text='', text_pos=(-0.05, -0.15), text_fg=(1, 1, 1, 1), relief=None)
        gui = loader.loadModel('phase_4/models/parties/schtickerbookHostingGUI')
        icon = gui.find('**/startPartyButton_inactive')
        iconNP = aspect2d.attachNewNode('iconNP')
        icon.reparentTo(iconNP)
        icon.setX(-12.0792 / 30.48)
        icon.setZ(-9.7404 / 30.48)
        marker['text'] = '%s' % mapIndex
        marker['text_scale'] = 0.7
        marker['image'] = iconNP
        marker['image_color'] = (1, 0, 0, 1)
        marker['image_scale'] = 6
        marker.setScale(0.05)
        relX, relY = self.transformAvPos(pos)
        marker.setPos(relX, 0, relY)
        self.buildingMarkers.append(marker)
        iconNP.removeNode()
        gui.removeNode()
        return

    def updateQuestInfo(self):
        for marker in self.buildingMarkers:
            marker.destroy()

        self.buildingMarkers = []
        dnaStore = base.cr.playGame.dnaStore
        for questIndex in list(self.av.questPage.quests.keys()):
            questDesc = self.av.questPage.quests.get(questIndex)
            if questDesc is None:
                continue
            mapIndex = questIndex + 1
            questId, fromNpcId, toNpcId, rewardId, toonProgress = questDesc
            quest = Quests.getQuest(questId)
            fComplete = quest.getCompletionStatus(self.av, questDesc) == Quests.COMPLETE
            if not fComplete:
                if quest.getType() == Quests.RecoverItemQuest:
                    if quest.getHolder() == Quests.AnyFish:
                        self.putBuildingMarker(self.fishingSpotInfo, mapIndex=mapIndex)
                    continue
                elif quest.getType() != Quests.DeliverGagQuest and quest.getType() != Quests.DeliverItemQuest and quest.getType() != Quests.VisitQuest and quest.getType() != Quests.TrackChoiceQuest:
                    continue
            if toNpcId == Quests.ToonHQ:
                self.putBuildingMarker(self.hqPosInfo, mapIndex=mapIndex)
            else:
                npcZone = NPCToons.getNPCZone(toNpcId)
                hoodId = ZoneUtil.getCanonicalHoodId(npcZone)
                branchId = ZoneUtil.getCanonicalBranchZone(npcZone)
                if self.hoodId == hoodId and self.zoneId == branchId:
                    for blockIndex in range(dnaStore.getNumBlockTitles()):
                        blockNumber = dnaStore.getTitleBlockAt(blockIndex)
                        zone = dnaStore.getZoneFromBlockNumber(blockNumber)
                        branchZone = zone - zone % 100
                        finalZone = branchZone + 500 + blockNumber
                        buildingType = dnaStore.getBlockBuildingType(blockNumber)
                        if npcZone == finalZone:
                            self.putBuildingMarker(dnaStore.getDoorPosHprFromBlockNumber(blockNumber).getPos(), dnaStore.getDoorPosHprFromBlockNumber(blockNumber).getHpr(), mapIndex=mapIndex)

        return

    def transformAvPos(self, pos):
        if self.cornerPosInfo is None:
            return (0, 0)
        topRight = self.cornerPosInfo[0]
        bottomLeft = self.cornerPosInfo[1]
        relativeX = (pos.getX() - bottomLeft.getX()) / (topRight.getX() - bottomLeft.getX()) - 0.5
        relativeY = (pos.getY() - bottomLeft.getY()) / (topRight.getY() - bottomLeft.getY()) - 0.5
        return (relativeX, relativeY)

    def update(self, task):
        if self.av:
            if self.updateMarker:
                relX, relY = self.transformAvPos(self.av.getPos())
                self.marker.setPos(relX, 0, relY)
                self.marker.setHpr(0, 0, -180 - self.av.getH())
        i = 0
        for buildingMarker in self.buildingMarkers:
            buildingMarker.setScale((math.sin(task.time * 16.0 + i * math.pi / 3.0) + 1) * 0.005 + 0.04)
            i = i + 1

        return Task.cont

    def updateMap(self):
        if self.av:
            try:
                hoodId = ZoneUtil.getCanonicalHoodId(self.av.getLocation()[1])
                zoneId = ZoneUtil.getCanonicalBranchZone(self.av.getLocation()[1])
                mapsGeom = loader.loadModel('phase_4/models/questmap/%s_maps' % ToontownGlobals.dnaMap[hoodId])
                mapImage = mapsGeom.find('**/%s_%s_english' % (ToontownGlobals.dnaMap[hoodId], zoneId))
                if not mapImage.isEmpty():
                    self.container['image'] = mapImage
                    self.resetFrameSize()
                    self.cornerPosInfo = QuestMapGlobals.CornerPosTable.get('%s_%s_english' % (ToontownGlobals.dnaMap[hoodId], zoneId))
                    self.hqPosInfo = QuestMapGlobals.HQPosTable.get('%s_%s_english' % (ToontownGlobals.dnaMap[hoodId], zoneId))
                    self.fishingSpotInfo = QuestMapGlobals.FishingSpotPosTable.get('%s_%s_english' % (ToontownGlobals.dnaMap[hoodId], zoneId))
                    self.cogInfoPos = QuestMapGlobals.CogInfoPosTable.get('%s_%s_english' % (ToontownGlobals.dnaMap[hoodId], zoneId))
                    self.cogInfoFrame.setPos(self.cogInfoPos)
                    self.hide()
                    self.hoodId = hoodId
                    self.zoneId = zoneId
                    self.updateQuestInfo()
                    self.updateCogInfo()
                    taskMgr.add(self.update, 'questMapUpdate')
                else:
                    self.stop()
                mapsGeom.removeNode()
            except:
                self.stop()

    def start(self):
        self.container.show()
        self.accept('questPageUpdated', self.updateMap)
        self.handleMarker()
        self.updateMap()

    def initMarker(self, task):
        if self.av:
            if not hasattr(base.cr.playGame.getPlace(), 'isInterior') or not base.cr.playGame.getPlace().isInterior:
                relX, relY = self.transformAvPos(self.av.getPos())
                self.marker.setPos(relX, 0, relY)
                self.marker.setHpr(0, 0, -180 - self.av.getH())
            self.marker['geom_scale'] = 1.4 * task.time % 0.5 * 10 + 1
            self.marker['geom_color'] = (1,
             1,
             1,
             0.8 - 1.4 * task.time % 0.5 * 2 / 0.8 + 0.2)
        if task.time < 1:
            return Task.cont
        else:
            self.marker['geom_color'] = (1, 1, 1, 0)
            return Task.done

    def show(self):
        taskMgr.add(self.initMarker, 'questMapInit')
        DirectFrame.show(self)
        self.mapOpenButton.hide()
        if self.container['image']:
            self.mapCloseButton.show()

    def hide(self):
        taskMgr.remove('questMapInit')
        DirectFrame.hide(self)
        if self.container['image']:
            self.mapOpenButton.show()
        self.mapCloseButton.hide()

    def toggle(self):
        if self.isHidden():
            self.show()
        else:
            self.hide()

    def obscureButton(self):
        self.mapOpenButton.hide()
        self.mapCloseButton.hide()

    def stop(self):
        self.container['image'] = None
        for marker in self.buildingMarkers:
            marker.destroy()

        self.buildingMarkers = []
        self.container.hide()
        self.hide()
        self.obscureButton()
        self.ignore('questPageUpdated')
        taskMgr.remove('questMapUpdate')
        return

    def handleMarker(self):
        if hasattr(base.cr.playGame.getPlace(), 'isInterior') and base.cr.playGame.getPlace().isInterior:
            self.updateMarker = False
        else:
            self.updateMarker = True

    def acceptOnscreenHooks(self):
        if self.wantToggle:
            self.accept(ToontownGlobals.MapHotkey, self.toggle)
        else:
            self.accept(ToontownGlobals.MapHotkeyOn, self.show)
            self.accept(ToontownGlobals.MapHotkeyOff, self.hide)
        self.updateMap()

    def ignoreOnscreenHooks(self):
        self.ignore(ToontownGlobals.MapHotkey)
        self.ignore(ToontownGlobals.MapHotkeyOn)
        self.ignore(ToontownGlobals.MapHotkeyOff)
        self.obscureButton()
コード例 #49
0
 def hide(self):
     taskMgr.remove('questMapInit')
     DirectFrame.hide(self)
     if self.container['image']:
         self.mapOpenButton.show()
     self.mapCloseButton.hide()
コード例 #50
0
 def destroy(self):
     taskMgr.remove(self.uniqueName('RepairSaw.UpdateGlow'))
     taskMgr.remove(self.uniqueName('RepairSaw.updateTask'))
     taskMgr.remove(DGG.B1PRESS)
     taskMgr.remove(DGG.B1RELEASE)
     DirectFrame.destroy(self)
コード例 #51
0
 def destroy(self):
     self.ival.finish()
     self.ival = None
     DirectFrame.destroy(self)
コード例 #52
0
class Transitions:

    # These may be reassigned before the fade or iris transitions are
    # actually invoked to change the models that will be used.
    IrisModelName = "models/misc/iris"
    FadeModelName = "models/misc/fade"

    def __init__(self, loader,
                 model=None,
                 scale=3.0,
                 pos=Vec3(0, 0, 0)):
        self.transitionIval = None
        self.__transitionFuture = None
        self.letterboxIval = None
        self.__letterboxFuture = None
        self.iris = None
        self.fade = None
        self.letterbox = None
        self.fadeModel = model
        self.imagePos = pos
        if model:
            self.alphaOff = Vec4(1, 1, 1, 0)
            self.alphaOn = Vec4(1, 1, 1, 1)
            model.setTransparency(1)
            self.lerpFunc = LerpColorScaleInterval
        else:
            self.alphaOff = Vec4(0, 0, 0, 0)
            self.alphaOn = Vec4(0, 0, 0, 1)
            self.lerpFunc = LerpColorInterval

        self.irisTaskName = "irisTask"
        self.fadeTaskName = "fadeTask"
        self.letterboxTaskName = "letterboxTask"

    def __del__(self):
        if self.fadeModel:
            self.fadeModel.removeNode()
            self.fadeModel = None

    ##################################################
    # Fade
    ##################################################

    # We can set a custom model for the fade before using it for the first time
    def setFadeModel(self, model, scale=1.0):
        self.fadeModel = model
        # We have to change some default parameters for a custom fadeModel
        self.alphaOn = Vec4(1, 1, 1, 1)

        # Reload fade if its already been created
        if self.fade:
            self.fade.destroy()
            self.fade = None
            self.loadFade()

    def loadFade(self):
        if self.fade is None:
            # We create a DirectFrame for the fade polygon, instead of
            # simply loading the polygon model and using it directly,
            # so that it will also obscure mouse events for objects
            # positioned behind it.
            self.fade = DirectFrame(
                parent = ShowBaseGlobal.hidden,
                guiId = 'fade',
                relief = None,
                image = self.fadeModel,
                image_scale = (4, 2, 2),
                state = DGG.NORMAL,
                )
            if not self.fadeModel:
                # No fade model was given, so we make this the fade model.
                self.fade["relief"] = DGG.FLAT
                self.fade["frameSize"] = (-2, 2, -1, 1)
                self.fade["frameColor"] = (0, 0, 0, 1)
                self.fade.setTransparency(TransparencyAttrib.MAlpha)
            self.fade.setBin('unsorted', 0)
            self.fade.setColor(0,0,0,0)

        self.fade.setScale(max(base.a2dRight, base.a2dTop))

    def getFadeInIval(self, t=0.5, finishIval=None, blendType='noBlend'):
        """
        Returns an interval without starting it.  This is particularly useful in
        cutscenes, so when the cutsceneIval is escaped out of we can finish the fade immediately
        """
        #self.noTransitions() masad: this creates a one frame pop, is it necessary?
        self.loadFade()

        transitionIval = Sequence(Func(self.fade.reparentTo, aspect2d, DGG.FADE_SORT_INDEX),
                                  Func(self.fade.showThrough),  # in case aspect2d is hidden for some reason
                                  self.lerpFunc(self.fade, t,
                                                self.alphaOff,
                                                # self.alphaOn,
                                                blendType=blendType
                                                ),
                                  Func(self.fade.detachNode),
                                  name = self.fadeTaskName,
                                  )
        if finishIval:
            transitionIval.append(finishIval)
        return transitionIval

    def getFadeOutIval(self, t=0.5, finishIval=None, blendType='noBlend'):
        """
        Create a sequence that lerps the color out, then
        parents the fade to hidden
        """
        self.noTransitions()
        self.loadFade()

        transitionIval = Sequence(Func(self.fade.reparentTo, aspect2d, DGG.FADE_SORT_INDEX),
                                  Func(self.fade.showThrough),  # in case aspect2d is hidden for some reason
                                  self.lerpFunc(self.fade, t,
                                                self.alphaOn,
                                                # self.alphaOff,
                                                blendType=blendType
                                                ),
                                  name = self.fadeTaskName,
                                  )
        if finishIval:
            transitionIval.append(finishIval)
        return transitionIval

    def fadeIn(self, t=0.5, finishIval=None, blendType='noBlend'):
        """
        Play a fade in transition over t seconds.
        Places a polygon on the aspect2d plane then lerps the color
        from black to transparent. When the color lerp is finished, it
        parents the fade polygon to hidden.
        """
        gsg = base.win.getGsg()
        if gsg:
            # If we're about to fade in from black, go ahead and
            # preload all the textures etc.
            base.graphicsEngine.renderFrame()
            render.prepareScene(gsg)
            render2d.prepareScene(gsg)

        if (t == 0):
            # Fade in immediately with no lerp
            #print "transitiosn: fadeIn 0.0"
            self.noTransitions()
            self.loadFade()
            self.fade.detachNode()
            fut = AsyncFuture()
            fut.setResult(None)
            return fut
        else:
            # Create a sequence that lerps the color out, then
            # parents the fade to hidden
            self.transitionIval = self.getFadeInIval(t, finishIval, blendType)
            self.transitionIval.append(Func(self.__finishTransition))
            self.__transitionFuture = AsyncFuture()
            self.transitionIval.start()
            return self.__transitionFuture

    def fadeOut(self, t=0.5, finishIval=None, blendType='noBlend'):
        """
        Play a fade out transition over t seconds.
        Places a polygon on the aspect2d plane then lerps the color
        from transparent to full black. When the color lerp is finished,
        it leaves the fade polygon covering the aspect2d plane until you
        fadeIn or call noFade.
        lerp
        """
        if (t == 0):
            # Fade out immediately with no lerp
            self.noTransitions()
            self.loadFade()

            self.fade.reparentTo(aspect2d, DGG.FADE_SORT_INDEX)
            self.fade.setColor(self.alphaOn)
        elif ConfigVariableBool('no-loading-screen', False):
            if finishIval:
                self.transitionIval = finishIval
                self.transitionIval.start()
        else:
            # Create a sequence that lerps the color out, then
            # parents the fade to hidden
            self.transitionIval = self.getFadeOutIval(t, finishIval, blendType)
            self.transitionIval.append(Func(self.__finishTransition))
            self.__transitionFuture = AsyncFuture()
            self.transitionIval.start()
            return self.__transitionFuture

        # Immediately done, so return a dummy future.
        fut = AsyncFuture()
        fut.setResult(None)
        return fut

    def fadeOutActive(self):
        return self.fade and self.fade.getColor()[3] > 0

    def fadeScreen(self, alpha=0.5):
        """
        Put a semitransparent screen over the camera plane
        to darken out the world. Useful for drawing attention to
        a dialog box for instance
        """
        #print "transitiosn: fadeScreen"
        self.noTransitions()
        self.loadFade()

        self.fade.reparentTo(aspect2d, DGG.FADE_SORT_INDEX)
        self.fade.setColor(self.alphaOn[0],
                           self.alphaOn[1],
                           self.alphaOn[2],
                           alpha)

    def fadeScreenColor(self, color):
        """
        Put a semitransparent screen over the camera plane
        to darken out the world. Useful for drawing attention to
        a dialog box for instance
        """
        #print "transitiosn: fadeScreenColor"
        self.noTransitions()
        self.loadFade()

        self.fade.reparentTo(aspect2d, DGG.FADE_SORT_INDEX)
        self.fade.setColor(color)

    def noFade(self):
        """
        Removes any current fade tasks and parents the fade polygon away
        """
        #print "transitiosn: noFade"
        if self.transitionIval:
            self.transitionIval.pause()
            self.transitionIval = None
        if self.__transitionFuture:
            self.__transitionFuture.cancel()
            self.__transitionFuture = None
        if self.fade:
            # Make sure to reset the color, since fadeOutActive() is looking at it
            self.fade.setColor(self.alphaOff)
            self.fade.detachNode()

    def setFadeColor(self, r, g, b):
        self.alphaOn.set(r, g, b, 1)
        self.alphaOff.set(r, g, b, 0)


    ##################################################
    # Iris
    ##################################################

    def loadIris(self):
        if self.iris == None:
            self.iris = loader.loadModel(self.IrisModelName)
            self.iris.setPos(0, 0, 0)

    def irisIn(self, t=0.5, finishIval=None, blendType = 'noBlend'):
        """
        Play an iris in transition over t seconds.
        Places a polygon on the aspect2d plane then lerps the scale
        of the iris polygon up so it looks like we iris in. When the
        scale lerp is finished, it parents the iris polygon to hidden.
        """
        self.noTransitions()
        self.loadIris()
        if (t == 0):
            self.iris.detachNode()
            fut = AsyncFuture()
            fut.setResult(None)
            return fut
        else:
            self.iris.reparentTo(aspect2d, DGG.FADE_SORT_INDEX)

            scale = 0.18 * max(base.a2dRight, base.a2dTop)
            self.transitionIval = Sequence(LerpScaleInterval(self.iris, t,
                                                   scale = scale,
                                                   startScale = 0.01,
                                                   blendType=blendType),
                                 Func(self.iris.detachNode),
                                 Func(self.__finishTransition),
                                 name = self.irisTaskName,
                                 )
            self.__transitionFuture = AsyncFuture()
            if finishIval:
                self.transitionIval.append(finishIval)
            self.transitionIval.start()
            return self.__transitionFuture

    def irisOut(self, t=0.5, finishIval=None, blendType='noBlend'):
        """
        Play an iris out transition over t seconds.
        Places a polygon on the aspect2d plane then lerps the scale
        of the iris down so it looks like we iris out. When the scale
        lerp is finished, it leaves the iris polygon covering the
        aspect2d plane until you irisIn or call noIris.
        """
        self.noTransitions()
        self.loadIris()
        self.loadFade()  # we need this to cover up the hole.
        if (t == 0):
            self.iris.detachNode()
            self.fadeOut(0)
            fut = AsyncFuture()
            fut.setResult(None)
            return fut
        else:
            self.iris.reparentTo(aspect2d, DGG.FADE_SORT_INDEX)

            scale = 0.18 * max(base.a2dRight, base.a2dTop)
            self.transitionIval = Sequence(LerpScaleInterval(self.iris, t,
                                                   scale = 0.01,
                                                   startScale = scale,
                                                   blendType=blendType),
                                 Func(self.iris.detachNode),
                                 # Use the fade to cover up the hole that the iris would leave
                                 Func(self.fadeOut, 0),
                                 Func(self.__finishTransition),
                                 name = self.irisTaskName,
                                 )
            self.__transitionFuture = AsyncFuture()
            if finishIval:
                self.transitionIval.append(finishIval)
            self.transitionIval.start()
            return self.__transitionFuture

    def noIris(self):
        """
        Removes any current iris tasks and parents the iris polygon away
        """
        if self.transitionIval:
            self.transitionIval.pause()
            self.transitionIval = None
        if self.iris != None:
            self.iris.detachNode()
        # Actually we need to remove the fade too,
        # because the iris effect uses it.
        self.noFade()

    def noTransitions(self):
        """
        This call should immediately remove any and all transitions running
        """
        self.noFade()
        self.noIris()
        # Letterbox is not really a transition, it is a screen overlay
        # self.noLetterbox()

    def __finishTransition(self):
        if self.__transitionFuture:
            self.__transitionFuture.setResult(None)
            self.__transitionFuture = None

    ##################################################
    # Letterbox
    ##################################################

    def loadLetterbox(self):
        if not self.letterbox:
            # We create a DirectFrame for the fade polygon, instead of
            # simply loading the polygon model and using it directly,
            # so that it will also obscure mouse events for objects
            # positioned behind it.
            self.letterbox = NodePath("letterbox")
            # Allow fade in and out of the bars
            self.letterbox.setTransparency(1)

            # Allow DirectLabels to be parented to the letterbox sensibly
            self.letterbox.setBin('unsorted', 0)

            # Allow a custom look to the letterbox graphic.

            # TODO: This model isn't available everywhere.  We should
            # pass it in as a parameter.
            button = loader.loadModel('models/gui/toplevel_gui',
                                      okMissing = True)

            barImage = None
            if button:
                barImage = button.find('**/generic_button')

            self.letterboxTop = DirectFrame(
                parent = self.letterbox,
                guiId = 'letterboxTop',
                relief = DGG.FLAT,
                state = DGG.NORMAL,
                frameColor = (0, 0, 0, 1),
                borderWidth = (0, 0),
                frameSize = (-1, 1, 0, 0.2),
                pos = (0, 0, 1.0),
                image = barImage,
                image_scale = (2.25,1,.5),
                image_pos = (0,0,.1),
                image_color = (0.3,0.3,0.3,1),
                sortOrder = 0,
                )
            self.letterboxBottom = DirectFrame(
                parent = self.letterbox,
                guiId = 'letterboxBottom',
                relief = DGG.FLAT,
                state = DGG.NORMAL,
                frameColor = (0, 0, 0, 1),
                borderWidth = (0, 0),
                frameSize = (-1, 1, 0, 0.2),
                pos = (0, 0, -1.2),
                image = barImage,
                image_scale = (2.25,1,.5),
                image_pos = (0,0,.1),
                image_color = (0.3,0.3,0.3,1),
                sortOrder = 0,
                )

            # masad: always place these at the bottom of render
            self.letterboxTop.setBin('sorted',0)
            self.letterboxBottom.setBin('sorted',0)
            self.letterbox.reparentTo(render2d, -1)
            self.letterboxOff(0)

    def noLetterbox(self):
        """
        Removes any current letterbox tasks and parents the letterbox polygon away
        """
        if self.letterboxIval:
            self.letterboxIval.pause()
            self.letterboxIval = None
        if self.__letterboxFuture:
            self.__letterboxFuture.cancel()
            self.__letterboxFuture = None
        if self.letterbox:
            self.letterbox.stash()

    def __finishLetterbox(self):
        if self.__letterboxFuture:
            self.__letterboxFuture.setResult(None)
            self.__letterboxFuture = None

    def letterboxOn(self, t=0.25, finishIval=None, blendType='noBlend'):
        """
        Move black bars in over t seconds.
        """
        self.noLetterbox()
        self.loadLetterbox()
        self.letterbox.unstash()
        if (t == 0):
            self.letterboxBottom.setPos(0, 0, -1)
            self.letterboxTop.setPos(0, 0, 0.8)
            fut = AsyncFuture()
            fut.setResult(None)
            return fut
        else:
            self.__letterboxFuture = AsyncFuture()
            self.letterboxIval = Sequence(Parallel(
                LerpPosInterval(self.letterboxBottom,
                                t,
                                pos = Vec3(0, 0, -1),
                                #startPos = Vec3(0, 0, -1.2),
                                blendType=blendType
                                ),
                LerpPosInterval(self.letterboxTop,
                                t,
                                pos = Vec3(0, 0, 0.8),
                                # startPos = Vec3(0, 0, 1),
                                blendType=blendType
                                ),
                ),
                                          Func(self.__finishLetterbox),
                                          name = self.letterboxTaskName,
                                          )
            if finishIval:
                self.letterboxIval.append(finishIval)
            self.letterboxIval.start()
            return self.__letterboxFuture

    def letterboxOff(self, t=0.25, finishIval=None, blendType='noBlend'):
        """
        Move black bars away over t seconds.
        """
        self.noLetterbox()
        self.loadLetterbox()
        self.letterbox.unstash()
        if (t == 0):
            self.letterbox.stash()
            fut = AsyncFuture()
            fut.setResult(None)
            return fut
        else:
            self.__letterboxFuture = AsyncFuture()
            self.letterboxIval = Sequence(Parallel(
                LerpPosInterval(self.letterboxBottom,
                                t,
                                pos = Vec3(0, 0, -1.2),
                                # startPos = Vec3(0, 0, -1),
                                blendType=blendType
                                ),
                LerpPosInterval(self.letterboxTop,
                                t,
                                pos = Vec3(0, 0, 1),
                                # startPos = Vec3(0, 0, 0.8),
                                blendType=blendType
                                ),
                ),
                                          Func(self.letterbox.stash),
                                          Func(self.__finishLetterbox),
                                          Func(messenger.send,'letterboxOff'),
                                          name = self.letterboxTaskName,
                                          )
            if finishIval:
                self.letterboxIval.append(finishIval)
            self.letterboxIval.start()
            return self.__letterboxFuture
コード例 #53
0
 def destroy(self):
     self._laffMeterModel.removeNode()
     del self._laffMeterModel
     DirectFrame.destroy(self)
コード例 #54
0
class InviteVisual(DirectFrame):
    notify = directNotify.newCategory('InviteVisual')

    def __init__(self, parent):
        DirectFrame.__init__(self, parent=parent)
        self.gui = loader.loadModel('phase_5.5/models/parties/partyInviteGUI')
        self.inviteThemesIdToInfo = {
            PartyGlobals.InviteTheme.Birthday:
            (self.gui.find('**/birthdayPage'),
             TTLocalizer.PartyPlannerBirthdayTheme, (0.0, 0.0, 0.0, 1.0)),
            PartyGlobals.InviteTheme.GenericMale:
            (self.gui.find('**/genericMalePage'),
             TTLocalizer.PartyPlannerGenericMaleTheme, (0.7, 0.7, 0.0, 1.0)),
            PartyGlobals.InviteTheme.GenericFemale:
            (self.gui.find('**/genericFemalePage'),
             TTLocalizer.PartyPlannerGenericFemaleTheme, (0.0, 1.0, 0.5, 1.0)),
            PartyGlobals.InviteTheme.Racing:
            (self.gui.find('**/racingPage'),
             TTLocalizer.PartyPlannerRacingTheme, (0.0, 0.0, 0.0, 1.0)),
            PartyGlobals.InviteTheme.Valentoons:
            (self.gui.find('**/valentinePage1'),
             TTLocalizer.PartyPlannerValentoonsTheme, (0.0, 0.0, 0.0, 1.0)),
            PartyGlobals.InviteTheme.VictoryParty:
            (self.gui.find('**/victoryPartyPage'),
             TTLocalizer.PartyPlannerVictoryPartyTheme, (0.0, 0.0, 0.0, 1.0)),
            PartyGlobals.InviteTheme.Winter:
            (self.gui.find('**/winterPartyPage1'),
             TTLocalizer.PartyPlannerWinterPartyTheme, (1.0, 1.0, 1.0, 1.0))
        }
        self.inviteThemeBackground = DirectFrame(
            parent=self, image=self.inviteThemesIdToInfo[0][0], relief=None)
        self.whosePartyLabel = DirectLabel(
            parent=self,
            relief=None,
            pos=self.gui.find('**/who_locator').getPos(),
            text='.',
            text_scale=0.067,
            textMayChange=True)
        self.activityTextLabel = DirectLabel(
            parent=self,
            relief=None,
            text='.\n.\n.\n.',
            pos=self.gui.find('**/what_locator').getPos(),
            text_scale=TTLocalizer.IVactivityTextLabel,
            textMayChange=True)
        self.whenTextLabel = DirectLabel(
            parent=self,
            relief=None,
            text='.\n.\n.',
            pos=self.gui.find('**/when_locator').getPos(),
            text_scale=TTLocalizer.IVwhenTextLabel,
            textMayChange=True)
        self.noFriends = False
        return None

    def setNoFriends(self, noFriends):
        self.noFriends = noFriends
        self.inviteThemeBackground.show()

    def updateInvitation(self, hostsName, partyInfo):
        self.partyInfo = partyInfo
        hostsName = TTLocalizer.GetPossesive(hostsName)
        self.whosePartyLabel[
            'text'] = TTLocalizer.PartyPlannerInvitationWhoseSentence % hostsName
        if self.partyInfo.isPrivate:
            publicPrivateText = TTLocalizer.PartyPlannerPrivate.lower()
        else:
            publicPrivateText = TTLocalizer.PartyPlannerPublic.lower()
        activities = self.getActivitiesFormattedCorrectly()
        if self.noFriends:
            self.activityTextLabel[
                'text'] = TTLocalizer.PartyPlannerInvitationThemeWhatSentenceNoFriends % (
                    publicPrivateText, activities)
        else:
            self.activityTextLabel[
                'text'] = TTLocalizer.PartyPlannerInvitationThemeWhatSentence % (
                    publicPrivateText, activities)
        if self.noFriends:
            self.whenTextLabel[
                'text'] = TTLocalizer.PartyPlannerInvitationWhenSentenceNoFriends % (
                    PartyUtils.formatDate(self.partyInfo.startTime.year,
                                          self.partyInfo.startTime.month,
                                          self.partyInfo.startTime.day),
                    PartyUtils.formatTime(self.partyInfo.startTime.hour,
                                          self.partyInfo.startTime.minute))
        else:
            self.whenTextLabel[
                'text'] = TTLocalizer.PartyPlannerInvitationWhenSentence % (
                    PartyUtils.formatDate(self.partyInfo.startTime.year,
                                          self.partyInfo.startTime.month,
                                          self.partyInfo.startTime.day),
                    PartyUtils.formatTime(self.partyInfo.startTime.hour,
                                          self.partyInfo.startTime.minute))
        self.changeTheme(partyInfo.inviteTheme)

    def getActivitiesFormattedCorrectly(self):
        activitiesString = ''
        activityList = []
        for activity in self.partyInfo.activityList:
            text = TTLocalizer.PartyActivityNameDict[
                activity.activityId]['invite']
            if text not in activityList:
                activityList.append(text)

        if len(activityList) == 1:
            return '\n' + TTLocalizer.PartyPlannerInvitationThemeWhatActivitiesBeginning + activityList[
                0]
        conjunction = TTLocalizer.PartyActivityConjunction
        for activity in activityList:
            activitiesString = '%s, %s' % (activitiesString, activity)

        activitiesString = activitiesString[2:]
        activitiesString = activitiesString[:activitiesString.rfind(
            ','
        )] + conjunction + activitiesString[activitiesString.rfind(',') + 1:]
        activitiesString = TTLocalizer.PartyPlannerInvitationThemeWhatActivitiesBeginning + activitiesString
        return self.insertCarriageReturn(activitiesString)

    def insertCarriageReturn(self, stringLeft, stringDone=''):
        desiredNumberOfCharactersInLine = 42
        if len(stringLeft) < desiredNumberOfCharactersInLine:
            return stringDone + '\n' + stringLeft
        for i in xrange(desiredNumberOfCharactersInLine - 6, len(stringLeft)):
            if stringLeft[i] == ' ':
                return self.insertCarriageReturn(
                    stringLeft[i:], stringDone + '\n' + stringLeft[:i])

        return stringDone + '\n' + stringLeft

    def changeTheme(self, newTheme):
        self.inviteThemeBackground['image'] = self.inviteThemesIdToInfo[
            newTheme][0]
        self.whosePartyLabel['text_fg'] = self.inviteThemesIdToInfo[newTheme][
            2]
        self.activityTextLabel['text_fg'] = self.inviteThemesIdToInfo[
            newTheme][2]
        self.whenTextLabel['text_fg'] = self.inviteThemesIdToInfo[newTheme][2]

    def close(self):
        self.destroy()
        del self
コード例 #55
0
class TeamMinigame:
    """An abstract class for any minigame that is team-based."""

    notify = directNotify.newCategory("TeamMinigame")

    def __init__(self, team1Name, team1BtnImg, team2Name, team2BtnImg):
        """
        team1Name - A string name of the first playable team.
        team1BtnImg - A tuple of textures for the team 1 selection button.

        team2Name - A string name of the second playable team.
        team2BtnImg - A tuple of textures for the team 2 selection button.
        """

        self.team1Name = team1Name
        self.team1BtnImg = team1BtnImg

        self.team2Name = team2Name
        self.team2BtnImg = team2BtnImg

        self.teamNameById = {TEAM1: self.team1Name, TEAM2: self.team2Name}

        # The team we are part of.
        self.team = None

        # Both teams have 0 players to start.
        self.playersByTeam = {TEAM1: 0, TEAM2: 0}

        ##### TEAM SELECTION STUFF!!! #####

        self.container = None

        self.bg = None

        self.title = None

        self.btnFrame = None

        self.team1Frame = None
        self.team1Btn = None
        self.team1Plyrs_Lbl = None

        self.team2Frame = None
        self.team2Btn = None
        self.team2Plyrs_Lbl = None

        self.teamFull_Lbl = None

    def makeSelectionGUI(self):
        font = CIGlobals.getMickeyFont()
        box = loader.loadModel('phase_3/models/gui/dialog_box_gui.bam')
        imp = CIGlobals.getToonFont()
        geom = CIGlobals.getDefaultBtnGeom()
        self.container = DirectFrame()
        self.bg = OnscreenImage(image=box,
                                color=(1, 1, 0.75, 1),
                                scale=(1.9, 1.4, 1.4),
                                parent=self.container)
        self.title = OnscreenText(text="Join  a  Team",
                                  pos=(0, 0.5, 0),
                                  font=font,
                                  scale=(0.12),
                                  parent=self.container,
                                  fg=(1, 0.9, 0.3, 1))
        self.btnFrame = DirectFrame(parent=self.container, pos=(0.14, 0, 0))
        self.team1BtnFrame = DirectFrame(parent=self.btnFrame,
                                         pos=(-0.5, 0, 0))
        self.team2BtnFrame = DirectFrame(parent=self.btnFrame,
                                         pos=(0.22, 0, 0))
        self.team1Btn = DirectButton(parent=self.team1BtnFrame,
                                     relief=None,
                                     pressEffect=0,
                                     image=self.team1BtnImg,
                                     image_scale=(0.9, 1, 1),
                                     scale=0.4,
                                     command=self.choseTeam,
                                     extraArgs=[TEAM1])
        self.team1Plyrs_Lbl = OnscreenText(parent=self.team1BtnFrame,
                                           text=str(self.playersByTeam[TEAM1]),
                                           pos=(0, -0.46, 0),
                                           font=imp)
        self.team2Btn = DirectButton(parent=self.team2BtnFrame,
                                     relief=None,
                                     pressEffect=0,
                                     image=self.team2BtnImg,
                                     image_scale=(0.9, 1, 1),
                                     scale=0.4,
                                     command=self.choseTeam,
                                     extraArgs=[TEAM2])
        self.team2Plyrs_Lbl = OnscreenText(parent=self.team2BtnFrame,
                                           text=str(self.playersByTeam[TEAM2]),
                                           pos=(0, -0.46, 0),
                                           font=imp)
        self.teamFull_Lbl = OnscreenText(parent=self.container,
                                         text="",
                                         pos=(0, -0.6, 0),
                                         font=imp)

    def destroySelectionGUI(self):
        if self.teamFull_Lbl:
            self.teamFull_Lbl.destroy()
            self.teamFull_Lbl = None
        if self.team2Plyrs_Lbl:
            self.team2Plyrs_Lbl.destroy()
            self.team2Plyrs_Lbl = None
        if self.team1Plyrs_Lbl:
            self.team1Plyrs_Lbl.destroy()
            self.team1Plyrs_Lbl = None
        if self.team2Btn:
            self.team2Btn.destroy()
            self.team2Btn = None
        if self.team1Btn:
            self.team1Btn.destroy()
            self.team1Btn = None
        if self.team2BtnFrame:
            self.team2BtnFrame.destroy()
            self.team2BtnFrame = None
        if self.team1BtnFrame:
            self.team1BtnFrame.destroy()
            self.team1BtnFrame = None
        if self.title:
            self.title.destroy()
            self.title = None
        if self.bg:
            self.bg.destroy()
            self.bg = None
        if self.container:
            self.container.destroy()
            self.container = None

    def choseTeam(self, team):
        self.team = team
        self.team1Btn['state'] = DGG.DISABLED
        self.team2Btn['state'] = DGG.DISABLED
        self.sendUpdate('choseTeam', [team])

    def acceptedIntoTeam(self):
        message = MSG_WELCOME.format(self.teamNameById[self.team])
        whisper = WhisperPopup(message, CIGlobals.getToonFont(),
                               ChatGlobals.WTSystem)
        whisper.manage(base.marginManager)

    def teamFull(self):
        # Oh, man, the team is full. Let's try again.
        self.teamFull_Lbl.setText('Sorry, that team is full.')
        self.team = None
        self.team1Btn['state'] = DGG.NORMAL
        self.team2Btn['state'] = DGG.NORMAL

    def incrementTeamPlayers(self, team):
        self.playersByTeam[team] += 1
        if self.fsm.getCurrentState().getName() == 'chooseTeam':
            if team == TEAM2:
                lbl = self.team2Plyrs_Lbl
            elif team == TEAM1:
                lbl = self.team1Plyrs_Lbl
            lbl.setText(str(self.playersByTeam[team]))

    def setTeamOfPlayer(self, avId, team):
        if not hasattr(self, 'getRemoteAvatar'):
            self.notify.error('Minigame must have remote avatars!!')

        remoteAvatar = self.getRemoteAvatar(avId)
        if remoteAvatar:
            print "setting team of {0}".format(avId)
            remoteAvatar.setTeam(team)

    def cleanup(self):
        self.destroySelectionGUI()
        del self.team1Name
        del self.teamNameById
        del self.team2Name
        del self.team1BtnImg
        del self.team2BtnImg
        del self.team
        del self.playersByTeam
コード例 #56
0
ファイル: CatalogItem.py プロジェクト: DarthNihilus1/src
 def makeFrame(self):
     from direct.gui.DirectGui import DirectFrame
     frame = DirectFrame(parent=hidden,
                         frameSize=(-1.0, 1.0, -1.0, 1.0),
                         relief=None)
     return frame
コード例 #57
0
    def setup(self, archivesNode):
        button = DirectButton(
            text='Load replay from file...',
            scale=0.04,
            command=self.showLoadReplayFileDialog,
            parent=archivesNode,
            pad=(1, 0.3),
        )
        align(button, midX=0, top=0.45)

        label = DirectLabel(
            text='- or -',
            text_scale=0.06,
            text_align=TextNode.ACenter,
            relief=None,
            parent=archivesNode,
        )
        align(label, midX=0, top=0.33)

        colours = self.app.theme.colours
        self.archivesGamesList = DirectScrolledList(
            decButton_pos=(0.4, 0, 0.17),
            decButton_text='up',
            decButton_text_scale=0.04,
            decButton_borderWidth=(0.005, 0.005),
            decButton_pad=(0.03, 0.01),
            decButton_text3_fg=colours.disabledButton,
            incButton_pos=(0.4, 0, -0.51),
            incButton_text='down',
            incButton_text_scale=0.04,
            incButton_borderWidth=(0.005, 0.005),
            incButton_pad=(0.03, 0.01),
            incButton_text3_fg=colours.disabledButton,
            frameSize=(0.0, 0.8, -0.55, 0.22),
            frameColor=colours.replayMenu,
            pos=(-0.85, 0, 0),
            numItemsVisible=13,
            forceHeight=0.045,
            itemFrame_pos=(0.02, 0, 0.1),
            parent=archivesNode,
        )

        DirectButton(
            text='refresh',
            text_align=TextNode.ACenter,
            scale=0.04,
            command=self.show,
            parent=archivesNode,
            pad=(0.9, 0.3),
            pos=(-0.175, 0, 0.162),
        )

        frame = DirectFrame(
            parent=archivesNode,
            pos=(0.45, 0, 0.07),
            frameSize=(-0.4, 0.4, -0.09, 0.15),
            frameColor=colours.replayMenu,
        )

        self.archiveNameLabel = DirectLabel(
            parent=frame,
            text='',
            pos=(0, 0, 0.1),
            text_scale=0.04,
            text_fg=colours.listboxButtons,
            text_align=TextNode.ACenter,
            relief=None,
        )
        self.archiveTimeLabel = DirectLabel(
            parent=frame,
            text='No game selected',
            pos=(0, 0, 0.05),
            text_scale=0.04,
            text_fg=colours.listboxButtons,
            text_align=TextNode.ACenter,
            relief=None,
        )
        self.archiveDurationLabel = DirectLabel(
            parent=frame,
            text='',
            pos=(0, 0, -0.05),
            text_scale=0.04,
            text_fg=colours.listboxButtons,
            text_align=TextNode.ACenter,
            relief=None,
        )

        self.archiveReplayButton = DirectButton(
            text='Watch replay',
            text_align=TextNode.ACenter,
            scale=0.04,
            parent=archivesNode,
            pad=(0.9, 0.3),
            pos=(0.45, 0, -0.1),
            text3_fg=colours.disabledButton,
            command=self.watchSelectedReplay,
        )

        self.archiveStatsButton = DirectButton(
            text='View game statistics',
            text_align=TextNode.ACenter,
            scale=0.04,
            parent=archivesNode,
            pad=(0.9, 0.3),
            pos=(0.45, 0, -0.2),
            text3_fg=colours.disabledButton,
            command=self.viewSelectedGameStats,
        )

        self.scene.button(
            'back',
            self.scene.showMainMenu,
            right=0.87,
            z=-0.67,
            parent=archivesNode,
        )
コード例 #58
0
class FrameAutenticacao(object):
    '''
    FrameAutenticacao
    '''
    def __init__(self, parent=None, **kw):
        self.__qtd_conexao = 0

        self.__frmAuth = DirectFrame(frameColor=(0, 0, 0, .3),
                                     frameSize=(-.5, .5, 0, 0.45),
                                     pos=(0, 0, -.1),
                                     enableEdit=1)

        self.__lblLogin = DirectLabel(text="Login: "******"Senha: ",
                                      scale=0.05,
                                      pos=(-0.3, 0, 0.2),
                                      frameColor=(0, 0, 0, 0),
                                      text_fg=(1, 1, 1, 1))

        self.__etySenha = DirectEntry(
            scale=0.05,
            width=12,
            pos=(-.2, 0, 0.2),
            cursorKeys=1,
            obscured=1,
            focusInCommand=self.__command_clear_senha)

        self.__btnEntrar = DirectButton(frameColor=(0, 0, 0, 1),
                                        text="Entrar",
                                        scale=0.06,
                                        pos=(0.3, 0, 0.1),
                                        text_fg=(1, 1, 1, 1),
                                        rolloverSound=None,
                                        clickSound=None,
                                        command=self.__command_entrar)

        self.__lblLogin.reparentTo(self.__frmAuth)
        self.__etyLogin.reparentTo(self.__frmAuth)
        self.__lblSenha.reparentTo(self.__frmAuth)
        self.__etySenha.reparentTo(self.__frmAuth)
        self.__btnEntrar.reparentTo(self.__frmAuth)

        self.__etyLogin.set("viner")
        self.__etySenha.set("viner")

    def __command_clear_senha(self):
        self.__etySenha.set("")

    def __command_entrar(self, txt=None):
        login = self.__etyLogin.get()
        senha = self.__etySenha.get()

        valido = True

        if login == "":
            addMensagem("O campo Login e obrigatorio !", COR_BRANCO)
            valido = False

        if senha == "":
            addMensagem("O campo Senha e obrigatorio !", COR_BRANCO)
            valido = False

        if valido:
            self.__btnEntrar["state"] = DGG.DISABLED

            taskMgr.add(self.__task_conectar_servidor,
                        'ConectarServidor',
                        extraArgs=[login, senha],
                        appendTask=True)

            #inicia_nova_thread(1, 0, "Conectar Servidor", self.__conectar_servidor, login, senha)

    def __task_conectar_servidor(self, login, senha, task):

        if self.__qtd_conexao < TENTATIVAS:

            if vinerOnline.flg_conectado == vinerOnline.ERROLOGIN:
                vinerOnline.flg_conectado = vinerOnline.DESCONECT

                self.__btnEntrar["state"] = DGG.NORMAL
                self.__qtd_conexao = 0

                addMensagem('Login ou senha invalido', COR_VERMELHO)

                self.__etyLogin.setFocus()

            elif vinerOnline.flg_conectado == vinerOnline.CONECTADO:
                #addMensagem("Conectado 12 !!!")
                #self.destroy()
                pass

            else:
                vinerOnline.conectar_servidor(login, senha)
                self.__qtd_conexao += 1

                taskMgr.doMethodLater(INTERVALO_TENTATIVAS,
                                      self.__task_conectar_servidor,
                                      'ConectarServidorLater',
                                      extraArgs=[login, senha],
                                      appendTask=True)

                msg = "Tentativa %s/5 -  Conectando..." % (self.__qtd_conexao)
                addMensagem(msg, COR_BRANCO)

        else:
            vinerOnline.flg_conectado = vinerOnline.DESCONECT
            self.__btnEntrar["state"] = DGG.NORMAL
            self.__qtd_conexao = 0
            addMensagem("Servidor nao encontrado", COR_VERMELHO)

        return task.done

    def destroy(self):
        self.__frmAuth.destroy()

        del self.__lblLogin
        del self.__etyLogin
        del self.__lblSenha
        del self.__etySenha
        del self.__btnEntrar
        del self.__frmAuth
コード例 #59
0
ファイル: Console.py プロジェクト: monicagraciela/Duelgeon
class DeveloperConsole(InteractiveInterpreter, DirectObject):
    def __init__(self):
        sys.stdout = PseudoFile(self.write_out)
        sys.stderr = PseudoFile(self.write_err)
        tp_err = TextProperties()
        tp_err.setTextColor(1, 0.5, 0.5, 1)
        TextPropertiesManager.getGlobalPtr().setProperties('err', tp_err)
        font = loader.loadFont('cmss12')
        self.frame = DirectFrame(parent=base.a2dTopCenter,
                                 text_align=TextNode.ALeft,
                                 text_pos=(base.a2dLeft + TEXT_MARGIN[0],
                                           TEXT_MARGIN[1]),
                                 text_scale=0.05,
                                 text_fg=(1, 1, 1, 1),
                                 frameSize=(-2.0, 2.0, -1, 0.0),
                                 frameColor=(0, 0, 0, 0.5),
                                 text='',
                                 text_font=font,
                                 sortOrder=4)
        self.entry = DirectEntry(parent=base.a2dTopLeft,
                                 command=self.command,
                                 scale=0.05,
                                 width=1000.0,
                                 pos=(-0.02, 0, -0.98),
                                 relief=None,
                                 text_pos=(1.5, 0, 0),
                                 text_fg=(1, 1, 0.5, 1),
                                 rolloverSound=None,
                                 clickSound=None,
                                 text_font=font)
        self.otext = OnscreenText(parent=self.entry,
                                  scale=1,
                                  align=TextNode.ALeft,
                                  pos=(1, 0, 0),
                                  fg=(1, 1, 0.5, 1),
                                  text=':',
                                  font=font)
        self.lines = [''] * 19
        self.commands = []  # All previously sent commands
        self.cscroll = None  # Index of currently navigated command, None if current
        self.command = ''  # Currently entered command
        self.block = ''  # Temporarily stores a block of commands
        self.hide()
        self.initialized = False

    def prev_command(self):
        if self.hidden:
            return
        if len(self.commands) == 0:
            return
        if self.cscroll is None:
            self.cscroll = len(self.commands)
            self.command = self.entry.get()
        elif self.cscroll <= 0:
            return
        else:
            self.commands[self.cscroll] = self.entry.get()
        self.cscroll -= 1
        self.entry.set(self.commands[self.cscroll])
        self.entry.setCursorPosition(len(self.commands[self.cscroll]))

    def next_command(self):
        if self.hidden:
            return
        if len(self.commands) == 0:
            return
        if self.cscroll is None:
            return
        self.commands[self.cscroll] = self.entry.get()
        self.cscroll += 1
        if self.cscroll >= len(self.commands):
            self.cscroll = None
            self.entry.set(self.command)
            self.entry.setCursorPosition(len(self.command))
        else:
            self.entry.set(self.commands[self.cscroll])
            self.entry.setCursorPosition(len(self.commands[self.cscroll]))

    def write_out(self, line, copy=True):
        if copy:
            sys.__stdout__.write(line)
        lines = line.split('\n')
        firstline = lines.pop(0)
        self.lines[-1] += firstline
        self.lines += lines
        self.frame['text'] = '\n'.join(self.lines[-19:])

    def write_err(self, line, copy=True):
        if copy:
            sys.__stderr__.write(line)
        line = '\1err\1%s\2' % line
        lines = line.split('\n')
        firstline = lines.pop(0)
        self.lines[-1] += firstline
        self.lines += lines
        self.frame['text'] = '\n'.join(self.lines[-19:])

    def command(self, text):
        if self.hidden:
            return

        self.cscroll = None
        self.command = ''
        self.entry.set('')
        self.entry['focus'] = True
        self.write_out(self.otext['text'] + ' ' + text + '\n', False)
        if text != '' and (len(self.commands) == 0
                           or self.commands[-1] != text):
            self.commands.append(text)

        if not self.initialized:
            InteractiveInterpreter.__init__(self)
            self.initialized = True
        try:
            if self.runsource(self.block + '\n' + text) and text != '':
                self.otext['text'] = '.'
                self.block += '\n' + text
            else:
                self.otext['text'] = ':'
                self.block = ''
        except Exception:
            self.write_err(traceback.format_exc())

    def toggle(self):
        if self.hidden:
            self.show()
        else:
            self.hide()

    def show(self):
        self.accept('arrow_up', self.prev_command)
        self.accept('arrow_up-repeat', self.prev_command)
        self.accept('arrow_down', self.next_command)
        self.accept('arrow_down-repeat', self.next_command)
        self.hidden = False
        self.entry['focus'] = True
        self.frame.show()
        self.entry.show()
        self.otext.show()

    def hide(self):
        self.ignoreAll()
        self.hidden = True
        self.entry['focus'] = False
        self.entry.set(self.entry.get()[:-1])
        self.frame.hide()
        self.entry.hide()
        self.otext.hide()

    def destroy(self):
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__
        self.ignoreAll()
        self.frame.destroy()
        self.entry.destroy()
        self.otext.destroy()
コード例 #60
0
ファイル: LaffMeter.py プロジェクト: RippedTelemarketer/rttim
class LaffMeter(DirectFrame):
    deathColor = Vec4(0.58039216, 0.80392157, 0.34117647, 1.0)

    def __init__(self, avdna, hp, maxHp):
        DirectFrame.__init__(self, relief=None, sortOrder=50)
        self.initialiseoptions(LaffMeter)
        self.container = DirectFrame(parent=self, relief=None)
        self.style = avdna
        self.av = None
        self.hp = hp
        self.maxHp = maxHp
        self.__obscured = 0
        if self.style.type == 't':
            self.isToon = 1
        else:
            self.isToon = 0
        self.load()
        return

    def obscure(self, obscured):
        self.__obscured = obscured
        if self.__obscured:
            self.hide()

    def isObscured(self):
        return self.__obscured

    def load(self):
        gui = loader.loadModel('phase_3/models/gui/laff_o_meter')
        if self.isToon:
            hType = self.style.getType()
            if hType == 'dog':
                headModel = gui.find('**/doghead')
            elif hType == 'cat':
                headModel = gui.find('**/cathead')
            elif hType == 'mouse':
                headModel = gui.find('**/mousehead')
            elif hType == 'horse':
                headModel = gui.find('**/horsehead')
            elif hType == 'rabbit':
                headModel = gui.find('**/bunnyhead')
            elif hType == 'duck':
                headModel = gui.find('**/duckhead')
            elif hType == 'monkey':
                headModel = gui.find('**/monkeyhead')
            elif hType == 'bear':
                headModel = gui.find('**/bearhead')
            elif hType == 'pig':
                headModel = gui.find('**/pighead')
            elif hType == 'riggy':
                headModel = gui.find('**/bunnyhead')
            elif hType == 'deer':
                headModel = gui.find('**/deerhead')  #Placeholder
            elif hType == 'crocodile':
                headModel = gui.find('**/crocodilehead')  #Placeholder
            else:
                raise StandardError('unknown toon species: ', hType)
            self.color = self.style.getHeadColor()
            self.container['image'] = headModel
            self.container['image_color'] = self.color
            self.resetFrameSize()
            self.setScale(0.1)
            self.frown = DirectFrame(parent=self.container,
                                     relief=None,
                                     image=gui.find('**/frown'))
            self.smile = DirectFrame(parent=self.container,
                                     relief=None,
                                     image=gui.find('**/smile'))
            self.eyes = DirectFrame(parent=self.container,
                                    relief=None,
                                    image=gui.find('**/eyes'))
            self.openSmile = DirectFrame(parent=self.container,
                                         relief=None,
                                         image=gui.find('**/open_smile'))
            self.tooth1 = DirectFrame(parent=self.openSmile,
                                      relief=None,
                                      image=gui.find('**/tooth_1'))
            self.tooth2 = DirectFrame(parent=self.openSmile,
                                      relief=None,
                                      image=gui.find('**/tooth_2'))
            self.tooth3 = DirectFrame(parent=self.openSmile,
                                      relief=None,
                                      image=gui.find('**/tooth_3'))
            self.tooth4 = DirectFrame(parent=self.openSmile,
                                      relief=None,
                                      image=gui.find('**/tooth_4'))
            self.tooth5 = DirectFrame(parent=self.openSmile,
                                      relief=None,
                                      image=gui.find('**/tooth_5'))
            self.tooth6 = DirectFrame(parent=self.openSmile,
                                      relief=None,
                                      image=gui.find('**/tooth_6'))
            self.maxLabel = DirectLabel(
                parent=self.eyes,
                relief=None,
                pos=(0.442, 0, 0.051),
                text='120',
                text_scale=0.4,
                text_font=ToontownGlobals.getInterfaceFont())
            self.hpLabel = DirectLabel(
                parent=self.eyes,
                relief=None,
                pos=(-0.398, 0, 0.051),
                text='120',
                text_scale=0.4,
                text_font=ToontownGlobals.getInterfaceFont())
            self.teeth = [
                self.tooth6, self.tooth5, self.tooth4, self.tooth3,
                self.tooth2, self.tooth1
            ]
            self.fractions = [0.0, 0.166666, 0.333333, 0.5, 0.666666, 0.833333]
        gui.removeNode()
        return

    def destroy(self):
        if self.av:
            ToontownIntervals.cleanup(
                self.av.uniqueName('laffMeterBoing') + '-' + str(self.this))
            ToontownIntervals.cleanup(
                self.av.uniqueName('laffMeterBoing') + '-' + str(self.this) +
                '-play')
            self.ignore(self.av.uniqueName('hpChange'))
        del self.style
        del self.av
        del self.hp
        del self.maxHp
        if self.isToon:
            del self.frown
            del self.smile
            del self.openSmile
            del self.tooth1
            del self.tooth2
            del self.tooth3
            del self.tooth4
            del self.tooth5
            del self.tooth6
            del self.teeth
            del self.fractions
            del self.maxLabel
            del self.hpLabel
        DirectFrame.destroy(self)

    def adjustTeeth(self):
        if self.isToon:
            for i in xrange(len(self.teeth)):
                if self.hp > self.maxHp * self.fractions[i]:
                    self.teeth[i].show()
                else:
                    self.teeth[i].hide()

    def adjustText(self):
        if self.isToon:
            if self.maxLabel['text'] != str(
                    self.maxHp) or self.hpLabel['text'] != str(self.hp):
                self.maxLabel['text'] = str(self.maxHp)
                self.hpLabel['text'] = str(self.hp)

    def animatedEffect(self, delta):
        if delta == 0 or self.av == None:
            return
        name = self.av.uniqueName('laffMeterBoing') + '-' + str(self.this)
        ToontownIntervals.cleanup(name)
        if delta > 0:
            ToontownIntervals.start(
                ToontownIntervals.getPulseLargerIval(self.container, name))
        else:
            ToontownIntervals.start(
                ToontownIntervals.getPulseSmallerIval(self.container, name))
        return

    def adjustFace(self, hp, maxHp, quietly=0):
        if self.isToon and self.hp != None:
            self.frown.hide()
            self.smile.hide()
            self.openSmile.hide()
            self.eyes.hide()
            for tooth in self.teeth:
                tooth.hide()

            delta = hp - self.hp
            self.hp = hp
            self.maxHp = maxHp
            if self.hp < 1:
                self.frown.show()
                self.container['image_color'] = self.deathColor
            elif self.hp >= self.maxHp:
                self.smile.show()
                self.eyes.show()
                self.container['image_color'] = self.color
            else:
                self.openSmile.show()
                self.eyes.show()
                self.maxLabel.show()
                self.hpLabel.show()
                self.container['image_color'] = self.color
                self.adjustTeeth()
            self.adjustText()
            if not quietly:
                self.animatedEffect(delta)
        return

    def start(self):
        if self.av:
            self.hp = self.av.hp
            self.maxHp = self.av.maxHp
        if self.isToon:
            if not self.__obscured:
                self.show()
            self.adjustFace(self.hp, self.maxHp, 1)
            if self.av:
                self.accept(self.av.uniqueName('hpChange'), self.adjustFace)

    def stop(self):
        if self.isToon:
            self.hide()
            if self.av:
                self.ignore(self.av.uniqueName('hpChange'))

    def setAvatar(self, av):
        if self.av:
            self.ignore(self.av.uniqueName('hpChange'))
        self.av = av