class Shockley:
    def __init__(self, preload=False):
        self.sceneRoot = None
        self.preload = preload

    def load(self):
        self.sceneRoot = NodePath('Shockley')
        base.setBackgroundColor(0, 0, 0, 1)

        self.title = OnscreenText(text='Shockley ', pos=(0.6, 0.15, 0.0), scale=(0.15), fg=(1, 1, 1, 1), font=ToontownGlobals.getSignFont(), align=TextNode.ACenter)
        self.description = OnscreenText(text='Lead Developer\nNetwork Technician\nGame Systems Engineer', pos=(0.25, 0.05, 0.0), scale=(0.06), fg=(1, 1, 1, 1), font=ToontownGlobals.getMinnieFont(), align=TextNode.ALeft)
        self.image = OnscreenImage(image='phase_4/maps/news/11-17-13_garden.jpg', pos=(-0.5, 0.0, 0.0), scale=(0.5, 0.30, 0.30))

        self.elements = [self.title, self.description, self.image]
        for node in self.elements:
            node.setTransparency(1)
            if self.preload:
                node.setColorScale(1, 1, 1, 0)

    def makeInterval(self):
        return Sequence(
            ParentInterval(self.sceneRoot, render),
            # This fades in during the election's WrapUp state to prevent jittering when loading this first scene.
            Wait(3),
            Func(doFade, 'out', self.elements),
            Wait(0.5),
            ParentInterval(self.sceneRoot, hidden)
            )

    def unload(self):
        self.sceneRoot.removeNode()
        self.title.removeNode()
        self.description.removeNode()
        self.image.removeNode()
Esempio n. 2
0
class Shockley:
    def __init__(self, preload=False):
        self.sceneRoot = None
        self.preload = preload

    def load(self):
        self.sceneRoot = NodePath('Shockley')
        base.setBackgroundColor(0, 0, 0, 1)

        self.title = OnscreenText(text='Shockley ',
                                  pos=(0.6, 0.15, 0.0),
                                  scale=(0.15),
                                  fg=(1, 1, 1, 1),
                                  font=ToontownGlobals.getSignFont(),
                                  align=TextNode.ACenter)
        self.description = OnscreenText(
            text='Lead Developer\nNetwork Technician\nGame Systems Engineer',
            pos=(0.25, 0.05, 0.0),
            scale=(0.06),
            fg=(1, 1, 1, 1),
            font=ToontownGlobals.getMinnieFont(),
            align=TextNode.ALeft)
        self.image = OnscreenImage(
            image='phase_4/maps/news/11-17-13_garden.jpg',
            pos=(-0.5, 0.0, 0.0),
            scale=(0.5, 0.30, 0.30))

        self.elements = [self.title, self.description, self.image]
        for node in self.elements:
            node.setTransparency(1)
            if self.preload:
                node.setColorScale(1, 1, 1, 0)

    def makeInterval(self):
        return Sequence(
            ParentInterval(self.sceneRoot, render),
            # This fades in during the election's WrapUp state to prevent jittering when loading this first scene.
            Wait(3),
            Func(doFade, 'out', self.elements),
            Wait(0.5),
            ParentInterval(self.sceneRoot, hidden))

    def unload(self):
        self.sceneRoot.removeNode()
        self.title.removeNode()
        self.description.removeNode()
        self.image.removeNode()
Esempio n. 3
0
class HUDBottomRight(DirectObject):
    
    def __init__(self):
        self.node = base.a2dBottomRight.attachNewNode('hudBottomRight')#GUIOrder.ORDER[GUIOrder.HUD])
        self.node.setBin('fixed', GUIOrder.ORDER[GUIOrder.HUD])
        
        self.ammoIcon = OnscreenImage(image = 'Assets/Images/HUD/HUDBottomRight.png', scale = 512.0 / 1024, pos = (-0.5, 0, 0.5))
        self.ammoIcon.setTransparency(TransparencyAttrib.MAlpha)
        self.ammoIcon.reparentTo(self.node)
        
        self.ammoTextClip = OnscreenText(text = '30', pos = (-0.35, 0.09), scale = 0.12, fg = (1, 1, 1, 1), shadow = (0, 0, 0, 1), mayChange = True, align=TextNode.ARight, font = Globals.FONT_SAF)
        self.ammoTextClip.reparentTo(self.node)
        self.ammoTextClip.setBin('fixed', GUIOrder.ORDER[GUIOrder.HUD])
        
        self.ammoTextLeft = OnscreenText(text = '90', pos = (-0.23, 0.05), scale = 0.07, fg = (1, 1, 1, 1), shadow = (0, 0, 0, 1), mayChange = True, align=TextNode.ARight, font = Globals.FONT_SAF)
        self.ammoTextLeft.reparentTo(self.node)
        self.ammoTextLeft.setBin('fixed', GUIOrder.ORDER[GUIOrder.HUD])
        
        self.accept(AmmoChangeEvent.EventName, self.OnAmmoChangeEvent)
        self.accept(SelectedItemChangeEvent.EventName, self.OnSelectedItemChangeEvent)
        
    def OnAmmoChangeEvent(self, event):
        item = event.GetItem()
        if(item and item.GetCurrentClipAmmo() == ''):
            self.ChangeAmmoText('', '')
        else:
            self.ChangeAmmoText(str(item.GetCurrentClipAmmo()), str(item.GetTotalRemainingAmmo()))
            
    def ChangeAmmoText(self, clip, total):
        self.ammoTextClip.setText(clip)
        self.ammoTextLeft.setText(total)
        
    def OnSelectedItemChangeEvent(self, event):
        if(event.GetItemStack() and event.GetItemStack().GetItem()):
            self.OnAmmoChangeEvent(AmmoChangeEvent(None, event.GetItemStack().GetItem()))
        else:
            self.ChangeAmmoText('', '')
        
    def Destroy(self):
        self.ignoreAll()
        self.ammoIcon.removeNode()
        self.ammoTextClip.removeNode()
        self.ammoTextLeft.removeNode()
        self.node.removeNode()
Esempio n. 4
0
class CogdoMazeHud:
    LETTERS_PER_SECOND = 4.0
    NEXT_NOTIFICATION_TASK_NAME = "CogdoMazeHud_NextNotification"

    def __init__(self):
        self._initNotificationText()

    def _initNotificationText(self):
        self._notificationText = OnscreenText(
            text="",
            font=ToontownGlobals.getSignFont(),
            pos=(0, -0.8),
            scale=0.11,
            fg=(1.0, 1.0, 0.0, 1.0),
            align=TextNode.ACenter,
            mayChange=True,
            )
        self._notificationText.hide()

    def destroy(self):
        self._stopDelayedNotification()

        self._notificationText.removeNode()
        del self._notificationText

    def displayNotification(self, messageText, nextMessageText=None):
        assert messageText is not None

        self._stopDelayedNotification()

        self._notificationText["text"] = messageText
        self._notificationText.show()

        if nextMessageText is not None:
            taskMgr.doMethodLater(
                len(messageText) / CogdoMazeHud.LETTERS_PER_SECOND,
                self.displayNotification,
                CogdoMazeHud.NEXT_NOTIFICATION_TASK_NAME,
                extraArgs=[nextMessageText]
                )

    def _stopDelayedNotification(self):
        taskMgr.remove(CogdoMazeHud.NEXT_NOTIFICATION_TASK_NAME)
Esempio n. 5
0
class HUDBottomLeft(DirectObject):
    
    def __init__(self):
        self.node = base.a2dBottomLeft.attachNewNode('hudhealth')#GUIOrder.ORDER[GUIOrder.HUD])
        self.node.setBin('fixed', GUIOrder.ORDER[GUIOrder.HUD])
        
        self.health = OnscreenImage(image = 'Assets/Images/HUD/HUDBottomLeft.png', scale = 512.0 / 1024, pos = (0.5, 0, 0.5))
        self.health.setTransparency(TransparencyAttrib.MAlpha)
        self.health.reparentTo(self.node)
        
        self.healthText = OnscreenText(text = '100', pos = (0.2, 0.07), scale = 0.12, fg = (1, 1, 1, 1), shadow = (0, 0, 0, 1), mayChange = True, font = Globals.FONT_SAF, align=TextNode.ALeft)
        self.healthText.reparentTo(self.node)
        self.healthText.setBin('fixed', GUIOrder.ORDER[GUIOrder.HUD])
        
        self.healthColorSeq = Sequence(LerpColorScaleInterval(self.node, 0.25, Globals.COLOR_RED),
                                       LerpColorScaleInterval(self.node, 0.25, Globals.COLOR_WHITE))
        
        self.dieingColorSeq = Sequence(LerpColorScaleInterval(self.node, 1, Globals.COLOR_RED),
                                       LerpColorScaleInterval(self.node, 1, Globals.COLOR_WHITE))
        
        self.accept(PlayerHealthEvent.EventName, self.OnPlayerHealthEvent)
        
    def OnPlayerHealthEvent(self, event):
        health = event.GetHealth()
        self.healthText.setText(str(health))
        if(health < 16):
            #self.node.setColor(Globals.COLOR_RED)
            self.dieingColorSeq.loop()
        elif(health == 100):
            self.dieingColorSeq.finish()
        else:
            self.healthColorSeq.start()        
        
    def Destroy(self):
        self.ignoreAll()
        self.health.removeNode()
        self.healthText.removeNode()
        self.node.removeNode()
Esempio n. 6
0
class FPSCounter(DirectObject):
    
    def __init__(self):
        
        self.node = base.a2dTopLeft.attachNewNode('Debug Info')
        self.node.setPos(0.03, 0, -0.15)
        
        self.fpsText =  OnscreenText(text = '', pos = (0, 0), scale = 0.06, fg = (1, 1, 1, 1), align = TextNode.ALeft, mayChange = True)
        self.fpsText.reparentTo(self.node)
        self.fps = 60
        self.lastTextUpdateTime = 0
        
        self.chunkText =  OnscreenText(text = '', pos = (0, -0.07), scale = 0.05, fg = (1, 1, 1, 1), align = TextNode.ALeft, mayChange = True)
        self.chunkText.reparentTo(self.node)
        
        self.bandwidthText = OnscreenText(text = '', pos = (0, -0.14), scale = 0.05, fg = (1, 1, 1, 1), align = TextNode.ALeft, mayChange = True)
        self.bandwidthText.reparentTo(self.node)
        
        self.accept(ChunkTimeEvent.EventName, self.UpdateChunkTime)
        self.accept(BandwidthInfoEvent.EventName, self.UpdateBandwidth)
        
    def Update(self):
        if(GameTime.deltaTime == 0):
            return
        
        self.fps += 0.1 * ((1.0 / GameTime.deltaTime) - self.fps) 
        
        if(GameTime.time - self.lastTextUpdateTime > 0.5):
            self.fpsText.setText('FPS: %s' % (str(int(self.fps))))
            self.lastTextUpdateTime = GameTime.time
            
    def UpdateChunkTime(self, event):
        self.chunkText.setText('Chunk: %s' % (str(event.GetTime())))
        
    def UpdateBandwidth(self, event):
        self.bandwidthText.setText('In: %s\nOut: %s' % (event.GetIncoming(), event.GetOutgoing()))
        
    def Destroy(self):  
        self.fpsText.removeNode()
        del self.fpsText
        self.chunkText.removeNode()
        del self.chunkText
        self.bandwidthText.removeNode()
        del self.bandwidthText
        self.ignoreAll()
class Credits:
    def __init__(self, name, description, image, side = 'left', number = 1, name2 = None, description2 = None, image2 = None, special = None):
        self.sceneRoot = None
        self.twoSlides = None
        self.toonName = name
        self.toonDescription = description
        self.toonImage = image
        self.side = side
        self.special = special # For special types of slides, like the final one
        if number > 1:
            self.toon2Name = name2
            self.toon2Description = description2
            self.toon2Image = image2
            self.twoSlides = True

    def load(self):
        self.sceneRoot = NodePath(self.toonName.replace(' ', '').replace('',''))
        base.setBackgroundColor(0, 0, 0, 1)

        if self.twoSlides:
            if self.side == 'left':
                # Left Top
                titlePos = (0.1, 0.5, 0.0)
                descriptionPos = (0.2, 0.4, 0.0)
                imagePos = (-0.55, 0.0, 0.4)
                textAlignment = TextNode.ALeft
                # Right Bottom
                title2Pos = (-0.1, -0.35, 0.0)
                description2Pos = (-0.1, -0.45, 0.0)
                image2Pos = (0.55, 0.0, -0.4)
                text2Alignment = TextNode.ARight
            else:
                # Right Top
                titlePos = (-0.1, 0.5, 0.0)
                descriptionPos = (-0.1, 0.4, 0.0)
                imagePos = (0.55, 0.0, 0.4)
                textAlignment = TextNode.ARight
                # Left Bottom
                title2Pos = (0.1, -0.35, 0.0)
                description2Pos = (0.25, -0.45, 0.0)
                image2Pos = (-0.55, 0.0, -0.4)
                text2Alignment = TextNode.ALeft
        elif self.side == 'left':
            # Left Middle
            titlePos = (0.1, 0.15, 0.0)
            descriptionPos = (0.2, 0.05, 0.0)
            imagePos = (-0.5, 0.0, 0.0)
            textAlignment = TextNode.ALeft
        else: 
            # Right Middle
            titlePos = (-0.1, 0.1, 0.0)
            descriptionPos = (-0.11, 0.0, 0.0)
            imagePos = (0.5, 0.0, 0.0)
            textAlignment = TextNode.ARight

        self.title = OnscreenText(text=self.toonName, pos=titlePos, scale=(0.15), fg=(1, 1, 1, 1), font=ToontownGlobals.getSignFont(), align=textAlignment)
        self.description = OnscreenText(text=self.toonDescription, pos=descriptionPos, scale=(0.06), fg=(1, 1, 1, 1), font=ToontownGlobals.getMinnieFont(), align=textAlignment)
        self.image = OnscreenImage(image='phase_4/maps/news/%s' % self.toonImage, pos=imagePos, scale=(0.5, 0.30, 0.30))
        self.elements = [self.title, self.description, self.image]

        if self.twoSlides:
            self.title2 = OnscreenText(text=self.toon2Name, pos=title2Pos, scale=(0.15), fg=(1, 1, 1, 1), font=ToontownGlobals.getSignFont(), align=text2Alignment)
            self.description2 = OnscreenText(text=self.toon2Description, pos=description2Pos, scale=(0.06), fg=(1, 1, 1, 1), font=ToontownGlobals.getMinnieFont(), align=text2Alignment)
            self.image2 = OnscreenImage(image='phase_4/maps/news/%s' % self.toon2Image, pos=image2Pos, scale=(0.5, 0.30, 0.30))
            self.elements.extend([self.title2, self.description2, self.image2])

        for node in self.elements:
            node.setTransparency(1)
            node.setColorScale(1, 1, 1, 0)

    def makeInterval(self):
        if self.special == 'final':
            # Hide the last slide, rather than fade out
            return Sequence(
                ParentInterval(self.sceneRoot, render),
                Func(doFade, 'in', self.elements),
                Wait(3),
                Func(doFade, 'hide', self.elements),
                ParentInterval(self.sceneRoot, hidden)
                )
        else:
            # Just a normal slide
            return Sequence(
                ParentInterval(self.sceneRoot, render),
                Func(doFade, 'in', self.elements),
                Wait(3.5),
                Func(doFade, 'out', self.elements),
                Wait(0.5),
                ParentInterval(self.sceneRoot, hidden)
                )

    def unload(self):
        self.sceneRoot.removeNode()
        self.title.removeNode()
        self.description.removeNode()
        self.image.removeNode()
        self.elements = None
        self.toonName = None
        self.toonDescription = None
        self.toonImage = None
        self.side = None
Esempio n. 8
0
File: game.py Progetto: Ahumm/GD1P3
class World(DirectObject): #subclassing here is necessary to accept events
    def __init__(self):
        # Marc's stuff
        #turn off mouse control, otherwise camera is not repositionable
        base.disableMouse()
        #camera.setPosHpr(0, -15, 7, 0, -15, 0)
        #self.update()
        self.setupLights()
        render.setShaderAuto() #you probably want to use this
        ##self.cfont = loader.loadFont('Coalition_v2.ttf')
        self.wave_size = 3
        self.max_enemies = 6
        self.score = 0
        self.wave = 0
        self.background_music = loader.loadSfx("sounds/bgm.wav")
        self.shotgun_fire = loader.loadSfx("sounds/shotgun_fire.wav")
        self.smg_fire = loader.loadSfx("sounds/smg_fire.wav")
        self.mortar_fire = loader.loadSfx("sounds/mortar_fire.wav")
        self.explosion_1 = loader.loadSfx("sounds/explosion_1.wav")
        self.explosion_2 = loader.loadSfx("sounds/explosion_2.wav")
        self.hit = loader.loadSfx("sounds/bullet_hit.wav")
        self.shotgun_load = loader.loadSfx("sounds/shotgun_load.wav")
        self.smg_load = loader.loadSfx("sounds/smg_load.wav")
        self.mortar_load = loader.loadSfx("sounds/mortar_load.wav")
        self.background_music.setLoop(True)
        
        
        # Mapping some keys
        self.keyMap = {"left":0, "right":0, "forward":0, "back":0, "shoot":0, "rot_left":0, "rot_right":0}
        self.accept("escape", self.pause)
        self.accept("space", self.setKey, ["shoot", 1])
        self.accept("space-up",self.setKey, ["shoot", 0])
        self.accept("e", self.create_explosion)
        self.accept("r", self.reload)
        self.accept("l", self.toggle_light)
        self.accept("1", self.setSMG)
        self.accept("2", self.setShotgun)
        self.accept("3", self.setMortar)
        self.accept("w", self.setKey, ["forward", 1])
        self.accept("d", self.setKey, ["right", 1])
        self.accept("a", self.setKey, ["left", 1])
        self.accept("s", self.setKey, ["back",1])
        self.accept("arrow_left", self.setKey, ["rot_left",1])
        self.accept("arrow_left-up", self.setKey, ["rot_left",0])
        self.accept("arrow_right", self.setKey, ["rot_right",1])
        self.accept("arrow_right-up", self.setKey, ["rot_right", 0])
        self.accept("mouse1", self.setKey, ["fire", True])
        self.accept("w-up", self.setKey, ["forward", 0])
        self.accept("d-up", self.setKey, ["right", 0])
        self.accept("a-up", self.setKey, ["left", 0])
        self.accept("s-up", self.setKey, ["back", 0])
        self.accept("mouse1-up", self.setKey, ["fire", False])


        # Empty lists to track stuff
        self.enemies = []
        self.bullets = []
        self.mortars = []
        
        
        
        
        # Find the start position
        self.player_start = (0,0,20)
        # Make a player object
        self.player = player.Player(self)
        self.count = 0
        
        
        #Load Environment
        self.environ = loader.loadModel("models/terrain")      
        self.environ.reparentTo(render)
        self.environ.setScale(0.66)
        self.environ.setPos(0,0,0)
        
        # Setup the collision detection rays
        self.cTrav = CollisionTraverser()
        
        
        # Player Rays
        self.player_cgray = CollisionRay()
        self.player_cgray.setOrigin(0,0,100)
        self.player_cgray.setDirection(0,0,-1)
        self.player_cgcol = CollisionNode("player_gray")
        self.player_cgcol.addSolid(self.player_cgray)
        self.player_cgcol.setFromCollideMask(BitMask32.bit(0))
        self.player_cgcol.setIntoCollideMask(BitMask32.allOff())
        self.player_cgcolnp = self.player.actor.attachNewNode(self.player_cgcol)
        self.player_cghandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.player_cgcolnp, self.player_cghandler)
        
        # Ground Rays
        self.cgray=CollisionRay()
        self.cgray.setOrigin(0,0,100)
        self.cgray.setDirection(0,0,-1)
        self.cgcol = CollisionNode("cgray")
        self.cgcol.addSolid(self.cgray)
        self.cgcol.setFromCollideMask(BitMask32.bit(0))
        self.cgcol.setIntoCollideMask(BitMask32.allOff())
        self.cgcolnp = camera.attachNewNode(self.cgcol)
        self.cghandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.cgcolnp, self.cghandler)
        

        
   
        self.paused = False
        self.setAI()

        
        
        self.hud_weapon = OnscreenText(text = "WEAPON: "+ str(self.player.selected_weapon), pos = (0.75, -0.8), scale = 0.07, fg=(180,180,180,1), shadow = (0,0,0,1))
        self.hud_health = OnscreenText(text = "HEALTH: "+ str(self.player.health), pos= (-0.9, -0.8), scale = 0.07, fg=(180,180,180,1), shadow=(0,0,0,1)) 
        self.hud_ammo = OnscreenText(text = "AMMO: ", pos=(0.75, -0.9), scale=0.07, fg=(180,180,180,1), shadow=(0,0,0,1))
        self.hud_wave = OnscreenText(text = "WAVE: "+str(self.wave), pos= (-0.9, -0.9), scale = 0.07, fg=(180,180,180,1), shadow=(0,0,0,1))
        self.hud_score = OnscreenText(text = "SCORE: "+str(self.score),pos= (0, -0.9), scale = 0.07, fg=(180,180,180,1), shadow=(0,0,0,1))
        
        # Set the enemy spawn points and frequenct of spawns
        self.wavetimer = 30
        self.spawnlocs = [(-1,-30,0),(3,30,0),(-13,2,0),(13,0,0)]#
        
        self.spawnTask = taskMgr.doMethodLater(2,self.spawnEnemies,'spawnTask')
        
        #self.explosions_handler = explosions.Explosions_Manager()
        self.explosions_handler = explosions.Explosions_Manager()
        
        taskMgr.add(self.update, "update")
        taskMgr.add(self.player_shoot, "Shoot")
        self.background_music.setVolume(0.4)
        self.background_music.play()
        
    def create_explosion(self):
        self.explosions_handler.Small_Explosion(VBase3(0,0,3))
        
    def setKey(self, key, value):
        self.keyMap[key] = value
        
    def setSMG(self):
        self.player.set_weapon("SMG")
    
    def setShotgun(self):
        self.player.set_weapon("SHOTGUN")
        
    def setMortar(self):
        self.player.set_weapon("MORTAR")
        
    def reload(self):
        self.player.reload(self)
        
        
    def toggle_light(self):
        self.player.toggle_light()
        
    def player_shoot(self, task):
        if not self.paused:
            if self.keyMap["shoot"]:
                self.player.fire(self)
        return Task.cont
        
    def setupLights(self):
        #ambient light
        self.ambientLight = AmbientLight("ambientLight")
        #four values, RGBA (alpha is largely irrelevent), value range is 0:1
        self.ambientLight.setColor((.5, .5, .4, 1))
        self.ambientLightNP = render.attachNewNode(self.ambientLight)
        #the nodepath that calls setLight is what gets illuminated by the light
        render.setLight(self.ambientLightNP)
        #call clearLight() to turn it off
        
        self.keyLight = DirectionalLight("keyLight")
        self.keyLight.setColor((.6,.6,.6, 1))
        self.keyLightNP = render.attachNewNode(self.keyLight)
        self.keyLightNP.setHpr(0, -26, 0)
        render.setLight(self.keyLightNP)
        """
        self.fillLight = DirectionalLight("fillLight")
        self.fillLight.setColor((.4,.4,.4, 1))
        self.fillLightNP = render.attachNewNode(self.fillLight)
        self.fillLightNP.setHpr(30, 0, 0)
        render.setLight(self.fillLightNP)    
        """
    def pause(self):
        if not self.paused:
            self.paused = True
            self.pause_text = OnscreenText(text = "PAUSED", pos = (0, 0.5), scale = 0.1, fg=(180,180,180,1), shadow = (0,0,0,1))
            self.resume_button = DirectButton(text = ("RESUME"), scale = 0.2, command = self.resume_game, pos=(0, 0, 0.0))
            self.exit_button = DirectButton(text = ("EXIT"), scale = 0.2, command = self.exit_game, pos=(0, 0,-0.4))
    
    def setAI(self):
        """ Set up The AI world"""
        # Create the world
        self.AIworld = AIWorld(render)

        # Add the AIworld updater
        taskMgr.add(self.AIUpdate, "AIUpdate")
    
    def spawnEnemies(self,task):
        print "Spawning Wave!"
        task.delayTime = self.wavetimer
        if not self.paused:
            if len(self.enemies) + self.wave_size <= self.max_enemies:
                self.wave += 1
                random.seed()
                for i in range(self.wave_size):
                    x = math.floor(random.uniform(0,6))
                    if x < 1:
                        self.newEnemy = enemies.Enemy2(self,random.choice(self.spawnlocs),"Enemy-%d-%d"%(self.wave,i))   
                    elif x < 4:
                        self.newEnemy = enemies.Enemy1(self,random.choice(self.spawnlocs),"Enemy-%d-%d"%(self.wave,i))    
                    else:
                        self.newEnemy = enemies.Enemy3(self,random.choice(self.spawnlocs),"Enemy-%d-%d"%(self.wave,i))    
                    self.enemies.append(self.newEnemy)
                    self.AIworld.addAiChar(self.newEnemy.setupAI(self.player.actor))
        return task.again
    
    def AIUpdate(self,task):
        """ Update the AIWorld """
        if not self.paused:
            self.AIworld.update()
            for e in self.enemies:
                if e.health <= 0:
                    e.die(self)
                    self.enemies.remove(e)
                else:
                    e.updateHeight(self)
        return Task.cont
    
    def resume_game(self):
        self.remove_pause_menu()
        self.paused = False
        
    def exit_game(self):
        self.remove_pause_menu()
        sys.exit()
        
        
    def remove_pause_menu(self):
        if self.pause_text:
            self.pause_text.removeNode()
        if self.resume_button:
            self.resume_button.removeNode()
        if self.exit_button:
            self.exit_button.removeNode()
            
    def update(self, task):
        self.hud_health.setText("HEALTH: " + str(self.player.health))
        if str(self.player.selected_weapon) == "SMG":
            self.hud_weapon.setText("WEAPON: MAIN GUN")
        else:
            self.hud_weapon.setText("WEAPON: " + str(self.player.selected_weapon))
        self.hud_wave.setText("WAVE: " + str(self.wave))
        self.hud_score.setText("SCORE: " + str(self.score))
        if self.player.health <= 25:
            self.hud_health.setFg((180,0,0,1))
        else: 
            self.hud_health.setFg((180,180,180,1))
        if self.player.selected_weapon == "SMG":
            self.hud_ammo.setText("AMMO: " + str(self.player.smg_mag))
            if self.player.smg_mag == 0 or self.player.smg_reloading:
                self.hud_ammo.setFg((180,0,0,1))
            else:
                self.hud_ammo.setFg((180,180,180,1))
        elif self.player.selected_weapon == "SHOTGUN":
            self.hud_weapon.setText("WEAPON: " + self.player.selected_weapon)
            if self.player.shotgun_mag == 0 or self.player.shotgun_reloading:
                self.hud_ammo.setFg((180,0,0,1))
            else:
                self.hud_ammo.setFg((180,180,180,1))
            self.hud_ammo.setText("AMMO: " + str(self.player.shotgun_mag))
        else:
            self.hud_ammo.setText("LOADED")
            if self.player.mortar_loaded == False:
                self.hud_ammo.setFg((180,0,0,1))
            else:
                self.hud_ammo.setFg((180,180,180,1))
        if self.pause == True:
            print "PAUSED"
        if self.player.health <=0:
            self.game_end = True
        return task.cont
Esempio n. 9
0
class TeamActivityGui:
    COUNTDOWN_TASK_NAME = 'updateCountdownTask'
    timer = None
    statusText = None
    countdownText = None
    exitButton = None
    switchButton = None

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def _handleTimerExpired(self):
        self.activity.handleGameTimerExpired()
Esempio n. 10
0
class KeyCodesGui(DirectObject):
    __module__ = __name__
    notify = directNotify.newCategory('KeyCodesGui')
    TIMEOUT_TASK = 'KeyCodeGui_TIMEOUT_TASK'

    def __init__(self, keyCodes, yOffset = 0.55, keyToIndex = KEY_TO_INDEX):
        self._keyCodes = keyCodes
        self._keyToIndex = keyToIndex
        self._arrowWidth = 0.18
        self._arrowSpaceInBetween = 0.05
        self._yOffset = yOffset
        self._danceMoveLabel = None
        self._arrowNodes = []
        self.timeoutTask = None
        return

    def load(self):
        matchingGameGui = loader.loadModel('phase_3.5/models/gui/matching_game_gui')
        minnieArrow = matchingGameGui.find('**/minnieArrow')
        minnieArrow.setScale(0.6)
        minnieArrow.setZ(self._yOffset + 0.2)
        maxLength = self._keyCodes.getLargestPatternLength()
        for i in range(maxLength):
            arrow = minnieArrow.copyTo(hidden)
            self._arrowNodes.append(arrow)

        matchingGameGui.removeNode()
        self._danceMoveLabel = OnscreenText(parent=aspect2d, text='', pos=(0, self._yOffset), scale=0.15, align=TextNode.ACenter, font=ToontownGlobals.getSignFont(), fg=Vec4(1, 1, 1, 1), mayChange=True)
        self._danceMoveLabel.hide()
        self.enable()

    def unload(self):
        self.disable()
        for arrow in self._arrowNodes:
            arrow.removeNode()
            arrow = None

        self._arrowNodes = []
        if self._danceMoveLabel is not None:
            self._danceMoveLabel.removeNode()
            self._danceMoveLabel = None
        return

    def enable(self):
        self.notify.debug('KeyCodeGui enabled.')
        self.accept(KeyCodes.KEY_DOWN_EVENT, self.__handleKeyDown)
        self.accept(KeyCodes.CLEAR_CODE_EVENT, self.hideAll)

    def disable(self):
        self.notify.debug('KeyCodeGui disabled.')
        self.__stopTimeout()
        self.ignoreAll()

    def hideArrows(self, startIndex = 0):
        length = len(self._arrowNodes)
        if startIndex < length:
            for i in range(startIndex, length):
                self._arrowNodes[i].reparentTo(hidden)

    def hideAll(self, startIndex = 0):
        self.hideArrows(startIndex)
        if self._danceMoveLabel:
            self._danceMoveLabel.hide()

    def showArrow(self, index, key):
        self._arrowNodes[index].setR(-(90 - 90 * self._keyToIndex[key]))
        self._arrowNodes[index].setColor(1, 1, 1, 1)
        self.__centerArrows()
        self._arrowNodes[index].reparentTo(aspect2d)
        self.hideAll(index + 1)
        self.__startTimeout()

    def showText(self, text = ''):
        self.notify.debug('"Showing text "%s"' % text)
        self._danceMoveLabel['text'] = text
        self._danceMoveLabel.show()

    def setColor(self, r, g, b):
        for arrow in self._arrowNodes:
            arrow.setColor(r, g, b)

        self._danceMoveLabel.setColorScale(r, g, b, 1)

    def __startTimeout(self):
        self.__stopTimeout()
        self.timeoutTask = taskMgr.doMethodLater(KEYCODE_TIMEOUT_SECONDS, self.__handleTimeoutTask, KeyCodesGui.TIMEOUT_TASK)

    def __stopTimeout(self):
        if self.timeoutTask is not None:
            taskMgr.remove(self.timeoutTask)
            self.timeoutTask = None
        return

    def __handleTimeoutTask(self, task):
        self.hideAll()
        return Task.done

    def __centerArrows(self):
        length = self._keyCodes.getCurrentInputLength()
        for i in range(length):
            x = -(length * self._arrowWidth * 0.5) + self._arrowWidth * (i + 0.5)
            self._arrowNodes[i].setX(x)

    def __handleKeyDown(self, key, index):
        if index >= 0:
            self.showArrow(index, key)
Esempio n. 11
0
class Player(GameObject):
    def __init__(self):
        GameObject.__init__(
            self, Vec3(0, 0, 0), "Models/PandaChan/act_p3d_chan", {
                "stand": "Models/PandaChan/a_p3d_chan_idle",
                "walk": "Models/PandaChan/a_p3d_chan_run"
            }, 5, 10, "player")
        self.actor.getChild(0).setH(180)

        mask = BitMask32()
        mask.setBit(1)

        self.collider.node().setIntoCollideMask(mask)

        mask = BitMask32()
        mask.setBit(1)

        self.collider.node().setFromCollideMask(mask)

        base.pusher.addCollider(self.collider, self.actor)
        base.cTrav.addCollider(self.collider, base.pusher)

        self.lastMousePos = Vec2(0, 0)

        self.groundPlane = Plane(Vec3(0, 0, 1), Vec3(0, 0, 0))

        self.ray = CollisionRay(0, 0, 0, 0, 1, 0)

        rayNode = CollisionNode("playerRay")
        rayNode.addSolid(self.ray)

        mask = BitMask32()

        mask.setBit(2)
        rayNode.setFromCollideMask(mask)

        mask = BitMask32()
        rayNode.setIntoCollideMask(mask)

        self.rayNodePath = render.attachNewNode(rayNode)
        self.rayQueue = CollisionHandlerQueue()

        base.cTrav.addCollider(self.rayNodePath, self.rayQueue)

        self.beamModel = loader.loadModel("Models/Misc/bambooLaser")
        self.beamModel.reparentTo(self.actor)
        self.beamModel.setZ(1.5)
        self.beamModel.setLightOff()
        self.beamModel.hide()

        self.beamHitModel = loader.loadModel("Models/Misc/bambooLaserHit")
        self.beamHitModel.reparentTo(render)
        self.beamHitModel.setZ(1.5)
        self.beamHitModel.setLightOff()
        self.beamHitModel.hide()

        self.beamHitPulseRate = 0.15
        self.beamHitTimer = 0

        self.damagePerSecond = -5.0

        self.score = 0

        self.scoreUI = OnscreenText(text="0",
                                    pos=(-1.3, 0.825),
                                    mayChange=True,
                                    align=TextNode.ALeft)

        self.healthIcons = []
        for i in range(self.maxHealth):
            icon = OnscreenImage(image="UI/health.png",
                                 pos=(-1.275 + i * 0.075, 0, 0.95),
                                 scale=0.04)
            icon.setTransparency(True)
            self.healthIcons.append(icon)

        self.damageTakenModel = loader.loadModel("Models/Misc/playerHit")
        self.damageTakenModel.setLightOff()
        self.damageTakenModel.setZ(1.0)
        self.damageTakenModel.reparentTo(self.actor)
        self.damageTakenModel.hide()

        self.damageTakenModelTimer = 0
        self.damageTakenModelDuration = 0.15

        self.laserSoundNoHit = loader.loadSfx("Sounds/laserNoHit.ogg")
        self.laserSoundNoHit.setLoop(True)
        self.laserSoundHit = loader.loadSfx("Sounds/laserHit.ogg")
        self.laserSoundHit.setLoop(True)

        self.beamHitLight = PointLight("beamHitLight")
        self.beamHitLight.setColor(Vec4(0.1, 1.0, 0.2, 1))
        self.beamHitLight.setAttenuation((1.0, 0.1, 0.5))
        self.beamHitLightNodePath = render.attachNewNode(self.beamHitLight)

        self.hurtSound = loader.loadSfx("Sounds/FemaleDmgNoise.ogg")

        self.yVector = Vec2(0, 1)

        self.actor.loop("stand")

    def update(self, keys, dt):
        GameObject.update(self, dt)

        self.walking = False

        if keys["up"]:
            self.walking = True
            self.velocity.addY(self.acceleration * dt)
        if keys["down"]:
            self.walking = True
            self.velocity.addY(-self.acceleration * dt)
        if keys["left"]:
            self.walking = True
            self.velocity.addX(-self.acceleration * dt)
        if keys["right"]:
            self.walking = True
            self.velocity.addX(self.acceleration * dt)

        if self.walking:
            standControl = self.actor.getAnimControl("stand")
            if standControl.isPlaying():
                standControl.stop()

            walkControl = self.actor.getAnimControl("walk")
            if not walkControl.isPlaying():
                self.actor.loop("walk")
        else:
            standControl = self.actor.getAnimControl("stand")
            if not standControl.isPlaying():
                self.actor.stop("walk")
                self.actor.loop("stand")

        mouseWatcher = base.mouseWatcherNode
        if mouseWatcher.hasMouse():
            mousePos = mouseWatcher.getMouse()
        else:
            mousePos = self.lastMousePos

        mousePos3D = Point3()
        nearPoint = Point3()
        farPoint = Point3()

        base.camLens.extrude(mousePos, nearPoint, farPoint)
        self.groundPlane.intersectsLine(
            mousePos3D, render.getRelativePoint(base.camera, nearPoint),
            render.getRelativePoint(base.camera, farPoint))

        firingVector = Vec3(mousePos3D - self.actor.getPos())
        firingVector2D = firingVector.getXy()
        firingVector2D.normalize()
        firingVector.normalize()

        heading = self.yVector.signedAngleDeg(firingVector2D)

        self.actor.setH(heading)

        self.beamHitTimer -= dt
        if self.beamHitTimer <= 0:
            self.beamHitTimer = self.beamHitPulseRate
            self.beamHitModel.setH(random.uniform(0.0, 360.0))
        self.beamHitModel.setScale(
            math.sin(self.beamHitTimer * 3.142 / self.beamHitPulseRate) * 0.4 +
            0.9)

        if keys["shoot"]:
            if self.rayQueue.getNumEntries() > 0:
                scoredHit = False

                self.rayQueue.sortEntries()
                rayHit = self.rayQueue.getEntry(0)
                hitPos = rayHit.getSurfacePoint(render)

                hitNodePath = rayHit.getIntoNodePath()
                if hitNodePath.hasPythonTag("owner"):
                    hitObject = hitNodePath.getPythonTag("owner")
                    if not isinstance(hitObject, TrapEnemy):
                        hitObject.alterHealth(self.damagePerSecond * dt)
                        scoredHit = True

                beamLength = (hitPos - self.actor.getPos()).length()
                self.beamModel.setSy(beamLength)

                self.beamModel.show()

                if scoredHit:
                    if self.laserSoundNoHit.status() == AudioSound.PLAYING:
                        self.laserSoundNoHit.stop()
                    if self.laserSoundHit.status() != AudioSound.PLAYING:
                        self.laserSoundHit.play()

                    self.beamHitModel.show()

                    self.beamHitModel.setPos(hitPos)
                    self.beamHitLightNodePath.setPos(hitPos + Vec3(0, 0, 0.5))

                    if not render.hasLight(self.beamHitLightNodePath):
                        render.setLight(self.beamHitLightNodePath)
                else:
                    if self.laserSoundHit.status() == AudioSound.PLAYING:
                        self.laserSoundHit.stop()
                    if self.laserSoundNoHit.status() != AudioSound.PLAYING:
                        self.laserSoundNoHit.play()

                    if render.hasLight(self.beamHitLightNodePath):
                        render.clearLight(self.beamHitLightNodePath)

                    self.beamHitModel.hide()
        else:
            if render.hasLight(self.beamHitLightNodePath):
                render.clearLight(self.beamHitLightNodePath)

            self.beamModel.hide()
            self.beamHitModel.hide()

            if self.laserSoundNoHit.status() == AudioSound.PLAYING:
                self.laserSoundNoHit.stop()
            if self.laserSoundHit.status() == AudioSound.PLAYING:
                self.laserSoundHit.stop()

        if firingVector.length() > 0.001:
            self.ray.setOrigin(self.actor.getPos())
            self.ray.setDirection(firingVector)

        self.lastMousePos = mousePos

        if self.damageTakenModelTimer > 0:
            self.damageTakenModelTimer -= dt
            self.damageTakenModel.setScale(2.0 - self.damageTakenModelTimer /
                                           self.damageTakenModelDuration)
            if self.damageTakenModelTimer <= 0:
                self.damageTakenModel.hide()

    def updateScore(self):
        self.scoreUI.setText(str(self.score))

    def alterHealth(self, dHealth):
        GameObject.alterHealth(self, dHealth)

        self.updateHealthUI()

        self.damageTakenModel.show()
        self.damageTakenModel.setH(random.uniform(0.0, 360.0))
        self.damageTakenModelTimer = self.damageTakenModelDuration

        self.hurtSound.play()

    def updateHealthUI(self):
        for index, icon in enumerate(self.healthIcons):
            if index < self.health:
                icon.show()
            else:
                icon.hide()

    def cleanup(self):
        self.scoreUI.removeNode()

        for icon in self.healthIcons:
            icon.removeNode()

        self.beamHitModel.removeNode()

        base.cTrav.removeCollider(self.rayNodePath)

        self.laserSoundHit.stop()
        self.laserSoundNoHit.stop()

        render.clearLight(self.beamHitLightNodePath)
        self.beamHitLightNodePath.removeNode()

        GameObject.cleanup(self)
Esempio n. 12
0
class MyApp(ShowBase):
    """Test class for the all the uses cases for the EasingMgr class."""

    def __init__(self):
        ShowBase.__init__(self)

        base.disableMouse()
        base.setBackgroundColor(.2, .2, .2)

        camera.setPos(0, 0, 45)
        camera.setHpr(0, -90, 0)

        self.curr_ease = [(easeClass[8], easeType[1]),
                          (easeClass[8], easeType[1]),
                          (easeClass[8], easeType[1])]
        self.curr_param = easeParam[2]

        self._labs = []

        self.param_lab = OnscreenText(text=self.curr_param,
                                      pos=(-1.3, .9),
                                      scale=0.07,
                                      fg=(0.8, 0.8, 0.8, 1),
                                      align=TextNode.ALeft,
                                      mayChange=1)

        self.controls = OnscreenText(text='Controls: \n' +
          '   [p] Change paramter. \n' +
          '   [q, a, z] Change ease mode (x, y, z).\n' +
          '   [w, s, x] Change ease type (x,y, z).\n' +
          '   [spacebar] Start the transition.\n' +
          '   [esc] Quit.',
                                     pos=(-1.3, -.7),
                                     scale=0.055,
                                     fg=(0.8, 0.8, 0.8, 1),
                                     align=TextNode.ALeft)

        for i in range(3):
            row = []
            row.append(OnscreenText(text=axis[i],
                                    pos=(-.9, .9 - (i*.1)),
                                    scale=0.07,
                                    fg=(0.8, 0.8, 0.8, 1),
                                    align=TextNode.ALeft,
                                    mayChange=1))
            row.append(OnscreenText(text=self.curr_ease[i][0],
                                    pos=(-.8, .9 - (i*.1)),
                                    scale=0.07,
                                    fg=(0.8, 0.8, 0.8, 1),
                                    align=TextNode.ALeft,
                                    mayChange=1))

            row.append(OnscreenText(text=self.curr_ease[i][1],
                                    pos=(-.6, .9 - (i*.1)),
                                    scale=0.07,
                                    fg=(0.8, 0.8, 0.8, 1),
                                    align=TextNode.ALeft,
                                    mayChange=1))
            self._labs.append(row)

        self._node = None

        self._ease_values = {'position3D': [(-8.0, -3.0, 10.0),
                                            (15.0, 3.0, -20.0)],
                             'position2D': [(-.7, -.3), (.7, .3)],
                             'scale1D': [[.08], [.20]],
                             'scale3D': [(1.0, 1.0, 1.0), (4.0, 4.0, 4.0)]}

        self.end_time = 1.0

        self.accept('escape', sys.exit, [0])
        self.input_setup(True)

        self.__easingMgr = EasingMgr()
        self.__curr_tr = None

        self.__change_param(0)

    def input_setup(self, activate):
        if activate:
            self.accept('q-up', self.__change_class, extraArgs=[0, 1])
            self.accept('a-up', self.__change_class, extraArgs=[1, 1])
            self.accept('z-up', self.__change_class, extraArgs=[2, 1])
            self.accept('w-up', self.__change_type, extraArgs=[0, 1])
            self.accept('s-up', self.__change_type, extraArgs=[1, 1])
            self.accept('x-up', self.__change_type, extraArgs=[2, 1])

            self.accept('p-up', self.__change_param, extraArgs=[1])
            self.accept('space-up', self.start_ease)
            self.accept('escape', sys.exit, [0])
        else:
            self.ignoreAll()

    def start_ease(self):
        self.input_setup(False)
        self.__easingMgr.start_transition(self.__curr_tr)

    def check_finished(self):
        if not self.__curr_tr.is_updating:
            self.input_setup(True)

    def __change_class(self, row, incr):
        self.curr_ease[row] = (easeClass[
            (easeClass.index(self.curr_ease[row][0]) + incr) % len(easeClass)],
            self.curr_ease[row][1])
        self._labs[row][1].setText(self.curr_ease[row][0])
        self.change_transition()

    def __change_type(self, row, incr):
        self.curr_ease[row] = (self.curr_ease[row][0], easeType[
            (easeType.index(self.curr_ease[row][1]) + incr) % len(easeType)])
        self._labs[row][2].setText(self.curr_ease[row][1])
        self.change_transition()

    def __change_param(self, incr):
        self.curr_param = easeParam[
            (easeParam.index(self.curr_param) + incr) % len(easeParam)]
        self.param_lab.setText(self.curr_param)
        self.release_nodes()
        if self.curr_param in ['position2D', 'scale1D']:
            self.load_text()
        if self.curr_param in ['position3D', 'scale3D']:
            self.load_sphere()
        if '1D' in self.curr_param:
            for i, row in enumerate(self._labs):
                if i < 1:
                    for lab in row:
                        lab.show()
                else:
                    for lab in row:
                        lab.hide()

        if '2D' in self.curr_param:
            for i, row in enumerate(self._labs):
                if i < 2:
                    for lab in row:
                        lab.show()
                else:
                    for lab in row:
                        lab.hide()
        if '3D' in self.curr_param:
            for i, row in enumerate(self._labs):
                for lab in row:
                    lab.show()
        self.change_transition()

    def change_transition(self):
        if self.__curr_tr:
            self.__easingMgr.remove_transition(self.__curr_tr)

        values = self._ease_values[self.curr_param]
        self.__curr_tr = self.__easingMgr.add_transition(self._node,
                                                         self.curr_param,
                                                         self.curr_ease,
                                                         self.end_time,
                                                         values,
                                                         self.check_finished)

    def load_text(self):
        self._node = OnscreenText(text='Fantastic text',
                                  pos=(self._ease_values['position2D'][0]),
                                  scale=self._ease_values['scale1D'][0][0])

    def load_sphere(self):
        self._node = loader.loadModel("assets/planet_sphere")
        self._node.reparentTo(render)
        self._node.setScale(self._ease_values['scale3D'][0][0],
                            self._ease_values['scale3D'][0][1],
                            self._ease_values['scale3D'][0][2])
        self._node.setPos(self._ease_values['position3D'][0][0],
                          self._ease_values['position3D'][0][1],
                          self._ease_values['position3D'][0][2])
        self._node_tex = loader.loadTexture("assets/earth.jpg")
        self._node.setTexture(self._node_tex, 1)

    def release_nodes(self):
        if self._node:
            self._node.removeNode()
            self._node = None
Esempio n. 13
0
class FsmStateMatchmakingFirstStep(ScreenState):
    def __init__(self, process_find_player, start_game_by_pairing, render_fsm):
        ScreenState.__init__(self)

        self.render_fsm_ref = render_fsm
        self.start_game_by_pairing = start_game_by_pairing
        self.screen_atributes.buttons["but:Back"] = ButtonFsm(
            "Back", (-0., 0, -0.8))
        self.screen_atributes.buttons["but:Create"] = ButtonFsm(
            "Create game", (-0., 0, -0.5))
        self.screen_atributes.buttons["but:Refresh"] = ButtonFsm(
            "Refresh", (0.3, 0, -0.1), None, None, (-1.6, 1.6, -0.3, 0.9),
            (2.1, 0.9, 0.8), 0.1)

        self.refresh_command = render_fsm.refresh_matchmaking_pairlist

        self.screen_atributes.screen_texts["scrtext:info"] = ScreenTextFsm(
            "Quick game:\nGame time (minutes), adding time (seconds)",
            (-0.85, 0.9))
        self.text_todo_later_delete = OnscreenText(
            text="Connect to:\nLogin, rate, game time, adding time",
            pos=(0.8, 0.73),
            bg=(1, 1, 1, 1))

        self.screen_atributes.buttons["but:preset1"] = ButtonFsm(
            "10, 0", (-1.25, 0, 0.6), None, None, (-1.5, 1.5, -0.3, 0.9),
            (1.8, 0.8, 0.8))
        self.screen_atributes.buttons["but:preset2"] = ButtonFsm(
            "30,0", (-0.5, 0, 0.6), None, None, (-1.5, 1.5, -0.3, 0.9),
            (1.8, 0.8, 0.8))
        self.screen_atributes.buttons["but:preset3"] = ButtonFsm(
            "5, 3", (-1.25, 0, 0.4), None, None, (-1.5, 1.5, -0.3, 0.9),
            (1.8, 0.8, 0.8))
        self.screen_atributes.buttons["but:preset4"] = ButtonFsm(
            "3, 2", (-0.5, 0, 0.4), None, None, (-1.5, 1.5, -0.3, 0.9),
            (1.8, 0.8, 0.8))
        self.screen_atributes.buttons["but:preset5"] = ButtonFsm(
            "1, 0", (-0.9, 0, 0.2), None, None, (-1.5, 1.5, -0.3, 0.9),
            (1.8, 0.8, 0.8))

        self.screen_atributes.screen_texts["scrtext:My rate"] = ScreenTextFsm(
            "Your's rate: {}".format(render_fsm.get_loacal_player_rating()),
            (-1.25, -0.2))

        self.pairs_buts = []
        self.my_scrolled_list = None
        self.initialize_button_links()

        self.pairing_list = None

        self.process_matchmaking = process_find_player

        self.render_fsm_ref.message = "Finding player..."
        self.set_pairing_list([])

    def initialize_button_links(self):
        self.screen_atributes.buttons["but:Create"].add_link("fsm:Matchmaking")
        self.screen_atributes.buttons["but:Back"].add_link("fsm:MainMenu")

        self.screen_atributes.buttons["but:preset1"].add_command(
            self.confirm_preset1)
        self.screen_atributes.buttons["but:preset2"].add_command(
            self.confirm_preset2)
        self.screen_atributes.buttons["but:preset3"].add_command(
            self.confirm_preset3)
        self.screen_atributes.buttons["but:preset4"].add_command(
            self.confirm_preset4)
        self.screen_atributes.buttons["but:preset5"].add_command(
            self.confirm_preset5)

        self.screen_atributes.buttons["but:Refresh"].add_command(
            self.proc_refresh)

        self.screen_atributes.buttons["but:preset1"].add_link("fsm:Message")
        self.screen_atributes.buttons["but:preset2"].add_link("fsm:Message")
        self.screen_atributes.buttons["but:preset3"].add_link("fsm:Message")
        self.screen_atributes.buttons["but:preset4"].add_link("fsm:Message")
        self.screen_atributes.buttons["but:preset5"].add_link("fsm:Message")

    def proc_refresh(self):
        self.refresh_command()

    def confirm_preset1(self):
        process_matchmaking_arg = {
            "MatchTime": 30,
            "AddTime": 0,
            "MinRate": 0,
            "MaxRate": 3000
        }
        self.process_matchmaking(process_matchmaking_arg)

    def confirm_preset2(self):
        process_matchmaking_arg = {
            "MatchTime": 10,
            "AddTime": 0,
            "MinRate": 0,
            "MaxRate": 3000
        }
        self.process_matchmaking(process_matchmaking_arg)

    def confirm_preset3(self):
        process_matchmaking_arg = {
            "MatchTime": 5,
            "AddTime": 3,
            "MinRate": 0,
            "MaxRate": 3000
        }
        self.process_matchmaking(process_matchmaking_arg)

    def confirm_preset4(self):
        process_matchmaking_arg = {
            "MatchTime": 3,
            "AddTime": 2,
            "MinRate": 0,
            "MaxRate": 3000
        }
        self.process_matchmaking(process_matchmaking_arg)

    def confirm_preset5(self):
        process_matchmaking_arg = {
            "MatchTime": 1,
            "AddTime": 0,
            "MinRate": 0,
            "MaxRate": 3000
        }
        self.process_matchmaking(process_matchmaking_arg)

    def set_pairing_list(self, pairing_list):
        for but in self.pairs_buts:
            but.removeNode()
        if self.my_scrolled_list is not None:
            self.my_scrolled_list.removeNode()

        self.pairing_list = pairing_list
        self.pairs_buts = []
        for pair in pairing_list:
            print(str(pair))
            self.pairs_buts.append(
                DirectButton(text=str(pair[1]) + ', ' + str(pair[2]) + ', ' +
                             str(pair[3]) + ', ' + str(pair[4]),
                             scale=0.1,
                             command=self.start_game_by_pairing,
                             extraArgs=[pair[0]],
                             frameColor=((0.8, 0.8, 0.8, 0.8), (0.4, 0.4, 0.4,
                                                                0.8),
                                         (0.4, 0.4, 0.8, 0.8), (0.1, 0.1, 0.1,
                                                                0.8)),
                             frameSize=(-6.5, 6.5, -0.4, 0.8)))

        self.my_scrolled_list = DirectScrolledList(
            decButton_pos=(0.35, -0, 0.87),
            decButton_text="up",
            decButton_text_scale=0.08,
            decButton_borderWidth=(0.005, 0.005),
            decButton_frameSize=(-0.25, 0.25, -0.05, 0.1),
            incButton_pos=(0.35, 0, -0.08),
            incButton_text="down",
            incButton_text_scale=0.08,
            incButton_borderWidth=(0.005, 0.005),
            incButton_frameSize=(-0.25, 0.25, -0.05, 0.1),

            # frameSize=(-0.7, 1.7, 0.8, 0),
            # frameColor=(1.3, 0.3, 1, 0.5),
            pos=(0.5, 0, 0),
            items=self.pairs_buts,
            numItemsVisible=5,
            forceHeight=0.11,
            itemFrame_frameSize=(-0.8, 0.8, -0.52, 0.26),
            itemFrame_pos=(0.35, 0, 0.55),
        )

        if self.text_todo_later_delete is not None:
            self.text_todo_later_delete.removeNode()

        self.text_todo_later_delete = OnscreenText(
            text="Connect to:\nLogin, rate, game time, adding time",
            pos=(0.8, 0.73),
            bg=(1, 1, 1, 1))

    def clear_state(self):
        self.render_fsm_ref.is_clearing = True
        self.my_scrolled_list.removeNode()
        for but in self.pairs_buts:
            but.removeNode()
        #for but in self.pairs_buts:
        #but.remove_node()
        self.render_fsm_ref.is_clearing = False
        self.text_todo_later_delete.removeNode()
Esempio n. 14
0
class Credits:
    def __init__(self,
                 name,
                 description,
                 image,
                 side='left',
                 number=1,
                 name2=None,
                 description2=None,
                 image2=None,
                 special=None):
        self.sceneRoot = None
        self.twoSlides = None
        self.toonName = name
        self.toonDescription = description
        self.toonImage = image
        self.side = side
        self.special = special  # For special types of slides, like the final one
        if number > 1:
            self.toon2Name = name2
            self.toon2Description = description2
            self.toon2Image = image2
            self.twoSlides = True

    def load(self):
        self.sceneRoot = NodePath(
            self.toonName.replace(' ', '').replace('', ''))
        base.setBackgroundColor(0, 0, 0, 1)

        if self.twoSlides:
            if self.side == 'left':
                # Left Top
                titlePos = (0.1, 0.5, 0.0)
                descriptionPos = (0.2, 0.4, 0.0)
                imagePos = (-0.55, 0.0, 0.4)
                textAlignment = TextNode.ALeft
                # Right Bottom
                title2Pos = (-0.1, -0.35, 0.0)
                description2Pos = (-0.1, -0.45, 0.0)
                image2Pos = (0.55, 0.0, -0.4)
                text2Alignment = TextNode.ARight
            else:
                # Right Top
                titlePos = (-0.1, 0.5, 0.0)
                descriptionPos = (-0.1, 0.4, 0.0)
                imagePos = (0.55, 0.0, 0.4)
                textAlignment = TextNode.ARight
                # Left Bottom
                title2Pos = (0.1, -0.35, 0.0)
                description2Pos = (0.25, -0.45, 0.0)
                image2Pos = (-0.55, 0.0, -0.4)
                text2Alignment = TextNode.ALeft
        elif self.side == 'left':
            # Left Middle
            titlePos = (0.1, 0.15, 0.0)
            descriptionPos = (0.2, 0.05, 0.0)
            imagePos = (-0.5, 0.0, 0.0)
            textAlignment = TextNode.ALeft
        else:
            # Right Middle
            titlePos = (-0.1, 0.1, 0.0)
            descriptionPos = (-0.11, 0.0, 0.0)
            imagePos = (0.5, 0.0, 0.0)
            textAlignment = TextNode.ARight

        self.title = OnscreenText(text=self.toonName,
                                  pos=titlePos,
                                  scale=(0.15),
                                  fg=(1, 1, 1, 1),
                                  font=ToontownGlobals.getSignFont(),
                                  align=textAlignment)
        self.description = OnscreenText(text=self.toonDescription,
                                        pos=descriptionPos,
                                        scale=(0.06),
                                        fg=(1, 1, 1, 1),
                                        font=ToontownGlobals.getMinnieFont(),
                                        align=textAlignment)
        self.image = OnscreenImage(image='phase_4/maps/news/%s' %
                                   self.toonImage,
                                   pos=imagePos,
                                   scale=(0.5, 0.30, 0.30))
        self.elements = [self.title, self.description, self.image]

        if self.twoSlides:
            self.title2 = OnscreenText(text=self.toon2Name,
                                       pos=title2Pos,
                                       scale=(0.15),
                                       fg=(1, 1, 1, 1),
                                       font=ToontownGlobals.getSignFont(),
                                       align=text2Alignment)
            self.description2 = OnscreenText(
                text=self.toon2Description,
                pos=description2Pos,
                scale=(0.06),
                fg=(1, 1, 1, 1),
                font=ToontownGlobals.getMinnieFont(),
                align=text2Alignment)
            self.image2 = OnscreenImage(image='phase_4/maps/news/%s' %
                                        self.toon2Image,
                                        pos=image2Pos,
                                        scale=(0.5, 0.30, 0.30))
            self.elements.extend([self.title2, self.description2, self.image2])

        for node in self.elements:
            node.setTransparency(1)
            node.setColorScale(1, 1, 1, 0)

    def makeInterval(self):
        if self.special == 'final':
            # Hide the last slide, rather than fade out
            return Sequence(ParentInterval(self.sceneRoot, render),
                            Func(doFade, 'in', self.elements), Wait(3),
                            Func(doFade, 'hide', self.elements),
                            ParentInterval(self.sceneRoot, hidden))
        else:
            # Just a normal slide
            return Sequence(ParentInterval(self.sceneRoot, render),
                            Func(doFade, 'in', self.elements), Wait(3.5),
                            Func(doFade, 'out', self.elements), Wait(0.5),
                            ParentInterval(self.sceneRoot, hidden))

    def unload(self):
        self.sceneRoot.removeNode()
        self.title.removeNode()
        self.description.removeNode()
        self.image.removeNode()
        self.elements = None
        self.toonName = None
        self.toonDescription = None
        self.toonImage = None
        self.side = None
Esempio n. 15
0
class KeyCodesGui(DirectObject):
    __module__ = __name__
    notify = directNotify.newCategory('KeyCodesGui')
    TIMEOUT_TASK = 'KeyCodeGui_TIMEOUT_TASK'

    def __init__(self, keyCodes, yOffset=0.55, keyToIndex=KEY_TO_INDEX):
        self._keyCodes = keyCodes
        self._keyToIndex = keyToIndex
        self._arrowWidth = 0.18
        self._arrowSpaceInBetween = 0.05
        self._yOffset = yOffset
        self._danceMoveLabel = None
        self._arrowNodes = []
        self.timeoutTask = None
        return

    def load(self):
        matchingGameGui = loader.loadModel(
            'phase_3.5/models/gui/matching_game_gui')
        minnieArrow = matchingGameGui.find('**/minnieArrow')
        minnieArrow.setScale(0.6)
        minnieArrow.setZ(self._yOffset + 0.2)
        maxLength = self._keyCodes.getLargestPatternLength()
        for i in range(maxLength):
            arrow = minnieArrow.copyTo(hidden)
            self._arrowNodes.append(arrow)

        matchingGameGui.removeNode()
        self._danceMoveLabel = OnscreenText(parent=aspect2d,
                                            text='',
                                            pos=(0, self._yOffset),
                                            scale=0.15,
                                            align=TextNode.ACenter,
                                            font=ToontownGlobals.getSignFont(),
                                            fg=Vec4(1, 1, 1, 1),
                                            mayChange=True)
        self._danceMoveLabel.hide()
        self.enable()

    def unload(self):
        self.disable()
        for arrow in self._arrowNodes:
            arrow.removeNode()
            arrow = None

        self._arrowNodes = []
        if self._danceMoveLabel is not None:
            self._danceMoveLabel.removeNode()
            self._danceMoveLabel = None
        return

    def enable(self):
        self.notify.debug('KeyCodeGui enabled.')
        self.accept(KeyCodes.KEY_DOWN_EVENT, self.__handleKeyDown)
        self.accept(KeyCodes.CLEAR_CODE_EVENT, self.hideAll)

    def disable(self):
        self.notify.debug('KeyCodeGui disabled.')
        self.__stopTimeout()
        self.ignoreAll()

    def hideArrows(self, startIndex=0):
        length = len(self._arrowNodes)
        if startIndex < length:
            for i in range(startIndex, length):
                self._arrowNodes[i].reparentTo(hidden)

    def hideAll(self, startIndex=0):
        self.hideArrows(startIndex)
        if self._danceMoveLabel:
            self._danceMoveLabel.hide()

    def showArrow(self, index, key):
        self._arrowNodes[index].setR(-(90 - 90 * self._keyToIndex[key]))
        self._arrowNodes[index].setColor(1, 1, 1, 1)
        self.__centerArrows()
        self._arrowNodes[index].reparentTo(aspect2d)
        self.hideAll(index + 1)
        self.__startTimeout()

    def showText(self, text=''):
        self.notify.debug('"Showing text "%s"' % text)
        self._danceMoveLabel['text'] = text
        self._danceMoveLabel.show()

    def setColor(self, r, g, b):
        for arrow in self._arrowNodes:
            arrow.setColor(r, g, b)

        self._danceMoveLabel.setColorScale(r, g, b, 1)

    def __startTimeout(self):
        self.__stopTimeout()
        self.timeoutTask = taskMgr.doMethodLater(KEYCODE_TIMEOUT_SECONDS,
                                                 self.__handleTimeoutTask,
                                                 KeyCodesGui.TIMEOUT_TASK)

    def __stopTimeout(self):
        if self.timeoutTask is not None:
            taskMgr.remove(self.timeoutTask)
            self.timeoutTask = None
        return

    def __handleTimeoutTask(self, task):
        self.hideAll()
        return Task.done

    def __centerArrows(self):
        length = self._keyCodes.getCurrentInputLength()
        for i in range(length):
            x = -(length * self._arrowWidth * 0.5) + self._arrowWidth * (i +
                                                                         0.5)
            self._arrowNodes[i].setX(x)

    def __handleKeyDown(self, key, index):
        if index >= 0:
            self.showArrow(index, key)
Esempio n. 16
0
class TeamActivityGui:
    COUNTDOWN_TASK_NAME = 'updateCountdownTask'
    timer = None
    statusText = None
    countdownText = None
    exitButton = None
    switchButton = None

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def _handleTimerExpired(self):
        self.activity.handleGameTimerExpired()
Esempio n. 17
0
class TeamActivityGui:
    COUNTDOWN_TASK_NAME = "updateCountdownTask"

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

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

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

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

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

        buttonModels.removeNode()

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

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

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

    def unload(self):
        self.hideWaitToStartCountdown()

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

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

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

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

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

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

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

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

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

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

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

        self.exitButton.hide()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        seconds = str(countdownTime)

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

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

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

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

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

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

    def _handleTimerExpired(self):
        assert (self.activity.notify.debug("Timer Expired!"))
        self.activity.handleGameTimerExpired()
Esempio n. 18
0
class KeyCodesGui(DirectObject):
    notify = directNotify.newCategory("KeyCodesGui")

    TIMEOUT_TASK = "KeyCodeGui_TIMEOUT_TASK"

    def __init__(self, keyCodes, yOffset=.55, keyToIndex=KEY_TO_INDEX):
        self._keyCodes = keyCodes # KeyCodes instance reference
        self._keyToIndex = keyToIndex

        self._arrowWidth = .18
        self._arrowSpaceInBetween = .05
        self._yOffset = yOffset

        self._danceMoveLabel = None
        self._arrowNodes = []

        self.timeoutTask = None

    def load(self):
        """
        Loads an initializes arrow nodes and dance move label.
        """
        matchingGameGui = loader.loadModel("phase_3.5/models/gui/matching_game_gui")
        minnieArrow = matchingGameGui.find("**/minnieArrow")
        minnieArrow.setScale(0.6)
        minnieArrow.setZ(self._yOffset + 0.2)

        maxLength = self._keyCodes.getLargestPatternLength()
        for i in range(maxLength):
            arrow = minnieArrow.copyTo(hidden)
            self._arrowNodes.append(arrow)

        matchingGameGui.removeNode()

        self._danceMoveLabel = OnscreenText(parent = aspect2d,
                                            text = "",
                                            pos = (0, self._yOffset),
                                            scale = 0.15,
                                            align = TextNode.ACenter,
                                            font = ToontownGlobals.getSignFont(),
                                            fg = Vec4(1, 1, 1, 1),
                                            #shadow = Vec4(0, 0, 0, 1),
                                            mayChange = True,
                                            )
        self._danceMoveLabel.hide()

        self.enable()

    def unload(self):
        self.disable()

        for arrow in self._arrowNodes:
            arrow.removeNode()
            arrow = None
        self._arrowNodes = []

        if self._danceMoveLabel is not None:
            self._danceMoveLabel.removeNode()
            self._danceMoveLabel = None

    def enable(self):
        self.notify.debug("KeyCodeGui enabled.")
        self.accept(KeyCodes.KEY_DOWN_EVENT, self.__handleKeyDown)
        self.accept(KeyCodes.CLEAR_CODE_EVENT, self.hideAll)

    def disable(self):
        self.notify.debug("KeyCodeGui disabled.")
        self.__stopTimeout()
        self.ignoreAll()

#===============================================================================
# Functions
#===============================================================================

    def hideArrows(self, startIndex=0):
        """
        Hides arrows.

        Parameters:
            startIndex (optional): sets from what index start hiding the arrows.
        """
        length = len(self._arrowNodes)
        if startIndex < length:
            for i in range(startIndex, length):
                self._arrowNodes[i].reparentTo(hidden)

    def hideAll(self, startIndex=0):
        self.hideArrows(startIndex)
        if self._danceMoveLabel:
            self._danceMoveLabel.hide()

    def showArrow(self, index, key):
        """
        Shows arrow at a specific index, and hides all of the arrows after that index.
        """
        # set rotation to the right rotation
        self._arrowNodes[index].setR(-(90 - 90 * self._keyToIndex[key]))
        self._arrowNodes[index].setColor(1, 1, 1, 1)
        self.__centerArrows()
        self._arrowNodes[index].reparentTo(aspect2d)
        self.hideAll(index + 1)

        self.__startTimeout()

    def showText(self, text=""):
        """
        Shows label text.
        """
        self.notify.debug('"Showing text "%s"' % text)
        self._danceMoveLabel["text"] = text
        self._danceMoveLabel.show()

    def setColor(self, r, g, b):
        """
        Changes text and arrow color to a particular rgb value.
        """
        for arrow in self._arrowNodes:
            arrow.setColor(r, g, b)
        self._danceMoveLabel.setColorScale(r, g, b, 1)

#===============================================================================
# Helpers
#===============================================================================

    def __startTimeout(self):
        """
        Starts timeout task to hide the gui elements.
        """
        self.__stopTimeout()
        self.timeoutTask = taskMgr.doMethodLater(KEYCODE_TIMEOUT_SECONDS,
                                                 self.__handleTimeoutTask,
                                                 KeyCodesGui.TIMEOUT_TASK)

    def __stopTimeout(self):
        """
        Stops a previously-set timeout from expiring.
        """
        if self.timeoutTask is not None:
            taskMgr.remove(self.timeoutTask)
            self.timeoutTask = None

    def __handleTimeoutTask(self, task):
        """
        Called after timing out. Hides all the keys and text label.
        """
        self.hideAll()
        return Task.done

    def __centerArrows(self):
        """
        Centers horizontally all visible arrows
        """
        length = self._keyCodes.getCurrentInputLength()
        for i in range(length):
            x = -(length * self._arrowWidth * 0.5) + (self._arrowWidth * (i + 0.5))
            self._arrowNodes[i].setX(x)

    def __handleKeyDown(self, key, index):
        """
        Shows arrow when a keycode key is pressed down.
        """
        if index >= 0:
            self.showArrow(index, key)
Esempio n. 19
0
class Player(DirectObject):
    def __init__(self, game):
        # Set ALL the variables!
        self.continue_on_screen = False
        self.health = 100
        ##self.cfont = loader.loadFont('Coalition_v2.ttf')
        self.shotgun_mag = 8
        self.shotgun_can_fire = True
        self.shotgun_fire_rate = 20
        self.shotgun_fire_counter = 0
        self.shotgun_reloading = False
        self.shotgun_reload_time = 120
        self.shotgun_reload_counter = 0
        self.mortar_loaded = True
        self.mortar_load_time = 180
        self.mortar_load_counter = 0
        self.smg_mag = 15
        self.smg_reload_time = 90
        self.smg_reload_counter = 0
        self.smg_burst_count = 1
        self.smg_fire_rate = 30
        self.smg_fire_counter = 0
        self.smg_reloading = False
        self.smg_can_fire = True
        self.rotate_counter = 0
        self.rotate_timer = 10
        self.actor = Actor("models/player")
        self.actor.reparentTo(render)
        self.actor.setScale(0.2)
        self.actor.setH(-90)
        self.actor.setPos(0,0,4)
        self.max_velocity = 45
        self.max_negative_velocity = -45
        self.x_vel = 0
        self.y_vel = 0
        self.min_velocity = 0
        self.acceleration = 1
        self.drift = 0.5
        self.min_expo = 50
        self.max_expo= 100
        self.expo = 75
        self.expo_increasing = True
        self.min_bob = -0.1
        self.max_bob = 0.1
        self.bob = 0
        self.bob_rate = 0.005
        self.bob_up = False
        camera.reparentTo(self.actor)
        camera.setPosHpr(20,10,4,0,0,0)
        self.last_shot_fired = 0.0
        self.dt = globalClock.getDt()
        
        # Collision for bullets
        self.cTrav = CollisionTraverser()
        self.cHandler = CollisionHandlerQueue()
        self.cSphere = CollisionSphere(0,0,0,7)
        self.cNode = CollisionNode("Player")
        self.cNode.addSolid(self.cSphere)
        self.cNodePath = self.actor.attachNewNode(self.cNode)

        self.cTrav.addCollider(self.cNodePath, self.cHandler)

        self.selected_weapon = "SMG"
        
        # Add headlights
        self.left_light = Spotlight('left')
        self.right_light = Spotlight('right')
        self.left_light.setColor(VBase4(1,1,1,1))
        self.right_light.setColor(VBase4(1,1,1,1))
        self.lens = PerspectiveLens()
        self.lens.setFov(16,10)
        self.left_light.setLens(self.lens)
        self.left_light_node = self.actor.attachNewNode(self.left_light)
        self.left_light_node.node().setAttenuation(Vec3(0.5,0.0,0.0))
        self.left_light_node.setPosHpr(0,3,-1,-90,-10,0)
        self.right_light.setLens(self.lens)
        self.right_light_node = self.actor.attachNewNode(self.right_light)
        self.right_light_node.node().setAttenuation(Vec3(0.5,0.0,0.0))
        self.right_light_node.setPosHpr(0,-3,-1,-90,-10,0)
        
        # Some hover lights
        self.left_hover = Spotlight('left_hover')
        self.left_hover.setColor(VBase4(0,0.1,1,1))
        self.hover_lens = PerspectiveLens()
        self.hover_lens.setFov(36,36)
        self.left_hover_node = self.actor.attachNewNode(self.left_hover)
        self.left_hover_node.node().setAttenuation(Vec3(0.75,0.0,0.0))
        self.left_hover_node.node().setExponent(100)
        self.left_hover.setSpecularColor(VBase4(0.2,0.2,0,1))
        self.left_hover_node.setPosHpr(1,4,-2,-90,-95,0)
        self.right_hover = Spotlight('right_r_hover')
        self.right_hover.setColor(VBase4(0,0,1,1))
        self.right_hover_node = self.actor.attachNewNode(self.right_hover)
        self.right_hover_node.node().setAttenuation(Vec3(0.75,0.0,0.0))
        self.right_hover_node.node().setExponent(100)
        self.right_hover.setSpecularColor(VBase4(0.2,0.2,0,1))
        self.right_hover_node.setPosHpr(1,-4,-2,-90,-95,0)
        render.setLight(self.left_hover_node)
        render.setLight(self.right_hover_node)

        # Add Movement Task
        taskMgr.add(self.move, "PlayerMove", extraArgs= [game])
        
        # Add Rotate Task
        taskMgr.add(self.rotate, "PlayerRotate", extraArgs=[game])
        
        
        # Hover Task
        taskMgr.add(self.hover, "PlayerHover", extraArgs=[game])
        
        # Hit Task
        taskMgr.add(self.hit_check, "PlayerHit", extraArgs=[game])
        
        # Add Logic Update Task
        taskMgr.add(self.update_counters, "PlayerUpdate", extraArgs=[game])
        
    def take_damage(self, damage, game):
        
        self.health -= damage
        if self.health <= 0:
            self.health = 0
            print "DEAD"
            self.die(game)
            
    def set_weapon(self, weapon):
        self.selected_weapon = weapon
        
    def hit_check(self, game):
        if not game.paused:
            for i in range(self.cHandler.getNumEntries()):
                entry = self.cHandler.getEntry(i)
                if entry.getIntoNode().getName() == "ball":
                    game.hit.setVolume(0.6)
                    game.hit.play()
                    self.take_damage(10,game)
        return Task.cont
                


    def fire(self, game):
        if not game.paused:
            if self.selected_weapon == "SMG":
                if self.smg_can_fire:
                    if self.smg_mag >= 1:
                        self.smg_mag -= 1
                        self.smg_fire_counter += self.smg_fire_rate
                        self.smg_can_fire = False
                        game.smg_fire.setVolume(0.8)
                        game.smg_fire.play()
                        b1 = bullets.Bullet(self, game)
                    if self.smg_mag == 0:
                        self.smg_reload_counter +=self.smg_reload_time
                        self.smg_reloading = True
            elif self.selected_weapon == "SHOTGUN":
                if self.shotgun_can_fire:
                    if self.shotgun_mag > 0:
                        self.shotgun_mag -= 1
                        self.shotgun_fire_counter += self.shotgun_fire_rate
                        self.shotgun_can_fire = False
                        game.shotgun_fire.setVolume(0.6)
                        game.shotgun_fire.play()
                        b1 = bullets.Bullet(self,game, True)
                        b2 = bullets.Bullet(self,game, True)
                        b3 = bullets.Bullet(self, game,True)
                        b4 = bullets.Bullet(self, game,True)
                        b5 = bullets.Bullet(self,game, True)
                        b6 = bullets.Bullet(self, game,True)
                        #print "Shotgun fired, " + str(self.shotgun_mag)+" rounds remaining"
                    if self.shotgun_mag == 0:
                        self.shotgun_reload_counter += self.shotgun_reload_time
                        self.shotgun_reloading = True
                        #print "Shotgun reloading"
            elif self.selected_weapon == "MORTAR":
                if self.mortar_loaded:
                    game.mortar_fire.setVolume(0.7)
                    game.mortar_fire.play()
                    self.mortar_loaded = False
                    self.mortar_load_counter += self.mortar_load_time
                    m = mortar.Mortar(self, game)
                    #print "Mortar launched"
                    
    def reload(self, game):
        if not game.paused:
            if self.selected_weapon == "SMG":
                if not self.smg_reloading and self.smg_mag < 15:
                    self.smg_can_fire = False
                    self.smg_reloading = True
                    self.smg_reload_counter += self.smg_reload_time
            elif self.selected_weapon == "SHOTGUN":
                if not self.shotgun_reloading and self.shotgun_mag < 8:
                    self.shotgun_can_fire = False
                    self.shotgun_reloading = True
                    self.shotgun_reload_counter += self.shotgun_reload_time
    
    def update_counters(self, game):
        if not game.paused:
            if self.selected_weapon == "SMG":
                if not self.smg_can_fire and not self.smg_reloading:
                    if self.smg_fire_counter > 0:
                        self.smg_fire_counter -= 1
                    if self.smg_fire_counter == 0:
                        self.smg_can_fire = True
                if self.smg_reloading:
                    if self.smg_reload_counter > 0:
                        self.smg_reload_counter -= 1
                    if self.smg_reload_counter == 0:
                        self.smg_mag = 15
                        self.smg_reloading = False
                        game.smg_load.setVolume(0.7)
                        game.smg_load.play()
                        self.smg_can_fire = True
                        #print "SMG reloaded"
        
            elif self.selected_weapon =="SHOTGUN":
                if not self.shotgun_can_fire and not self.shotgun_reloading:
                    if self.shotgun_fire_counter > 0:
                        self.shotgun_fire_counter -=1
                    if self.shotgun_fire_counter == 0:
                        self.shotgun_can_fire = True
                if self.shotgun_reloading:
                    if self.shotgun_reload_counter > 0:
                        self.shotgun_reload_counter -= 1
                    if self.shotgun_reload_counter == 0:
                        self.shotgun_mag = 8
                        game.shotgun_load.setVolume(0.7)
                        game.shotgun_load.play()
                        self.shotgun_reloading = False
                        self.shotgun_can_fire = True
                        #print "Shotgun reloaded"
                        
            elif self.selected_weapon == "MORTAR":
                if not self.mortar_loaded:
                    if self.mortar_load_counter > 0:
                        self.mortar_load_counter -= 1
                    if self.mortar_load_counter == 0:
                        game.mortar_load.setVolume(0.7)
                        game.mortar_load.play()
                        self.mortar_loaded = True
                        #print "Mortar loaded"
            
        return Task.cont
            
    def move(self, game):
        if not game.paused:
            self.moving = False
            self.player_start_pos = self.actor.getPos()
            if game.keyMap["left"]:
                self.moving = True
                self.y_vel += self.acceleration
                if self.y_vel > self.max_velocity:
                    self.y_vel = self.max_velocity
          
            if game.keyMap["right"]:
                self.moving = True
                self.y_vel -= self.acceleration
                if self.y_vel < self.max_negative_velocity:
                    self.y_vel = self.max_negative_velocity
               
            if game.keyMap["forward"]:
                self.moving = True
                self.x_vel += self.acceleration
                if self.x_vel > self.max_velocity:
                    self.x_vel = self.max_velocity
                
            if game.keyMap["back"]:
                self.moving = True
                self.x_vel -= self.acceleration
                if self.x_vel < self.max_negative_velocity:
                    self.x_vel = self.max_negative_velocity
               
            if self.moving:
                self.bob = 0
            if  not self.moving:
                if self.x_vel > self.min_velocity:
                    self.x_vel -= self.drift
                    if self.x_vel < self.min_velocity:
                        self.x_vel = self.min_velocity
                elif self.x_vel < self.min_velocity:
                    self.x_vel += self.drift
                    if self.x_vel > self.min_velocity:
                        self.x_vel = self.min_velocity
                if self.y_vel > self.min_velocity:
                    self.y_vel -= self.drift
                    if self.y_vel < self.min_velocity:
                        self.y_vel = self.min_velocity
                elif self.y_vel < self.min_velocity:
                    self.y_vel += self.drift
                    if self.y_vel > self.min_velocity:
                        self.y_vel = self.min_velocity
            
            self.actor.setY(self.actor, self.y_vel * globalClock.getDt())
            self.actor.setX(self.actor, self.x_vel * globalClock.getDt())
            # Check for terrain collisions
            game.cTrav.traverse(render)
            self.cTrav.traverse(render)
            
            # Now update the player's Z coordinate, or don't move at all
            entries = []
            for i in range(game.player_cghandler.getNumEntries()):
                entry = game.player_cghandler.getEntry(i)
                if entry.getIntoNode().getName() != "Player":
                    entries.append(entry)
            entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ()))
            if (len(entries)>0) and (entries[0].getIntoNode().getName() == "terrain"):
                self.actor.setZ(entries[0].getSurfacePoint(render).getZ()+2)
            else:
                self.actor.setPos(self.player_start_pos)
                
            # Check boundaries
            b_entries = []
            for i in range(self.cHandler.getNumEntries()):
                entry = self.cHandler.getEntry(i)
                if entry.getIntoNode().getName() == "fence_c" or "debris":
                    self.actor.setPos(self.player_start_pos)

            
            # Bobbing when still
            
            if self.x_vel == 0 and self.y_vel == 0:
                if not self.bob_up :
                    self.bob -= self.bob_rate
                    if self.bob < self.min_bob:
                        self.bob = self.min_bob
                        self.bob_up = True
                else:
                    self.bob+=self.bob_rate
                    if self.bob > self.max_bob:
                        self.bob=self.max_bob
                        self.bob_up = False
                        
                self.actor.setZ(self.actor.getZ()+self.bob)
            
            camera.setPosHpr(-60,0,13,-90,-10,0)
            if (len(entries)>0):
                if camera.getZ() <= entries[0].getSurfacePoint(render).getZ()+2:
                    camera.setZ(entries[0].getSurfacePoint(render).getZ()+10)
            
            
            
            camera.lookAt(self.actor)
        return Task.cont
        
        
    def toggle_light(self):
        if render.hasLight(self.left_light_node):
            render.clearLight(self.left_light_node)
        else:
            render.setLight(self.left_light_node)
            
        if render.hasLight(self.right_light_node):
            render.clearLight(self.right_light_node)
        else:
            render.setLight(self.right_light_node)
    
    def rotate(self, game):
        if not game.paused:
            if game.keyMap["rot_left"]:
                self.actor.setH(self.actor.getH() +  1)
            if game.keyMap["rot_right"]:
                self.actor.setH(self.actor.getH() - 1)
                   

        return Task.cont
    
    def hover(self,game):
        if not game.paused: 
            self.left_hover_node.node().setExponent(self.expo)
            self.right_hover_node.node().setExponent(self.expo)

            if self.expo_increasing:
                self.expo += 1
                if self.expo > self.max_expo:
                    self.expo = self.max_expo
                    self.expo_increasing = False
            else:
                self.expo -= 1
                if self.expo < self.min_expo:
                    self.expo = self.min_expo
                    self.expo_increasing = True
                    
        return Task.cont
    
    def die(self, game):
        game.paused = True
        if not self.continue_on_screen:
            self.you_lose = OnscreenText(text = "CONTINUE?", pos = (0, 0), scale = 0.16, fg=(180,180,180,1), shadow = (0,0,0,1))
            self.restart_button = DirectButton(text = "CONTINUE", scale = .12, text_fg = ((0,0,0,1)), command = self.restart_game, extraArgs=[game],pos=(0, 0, 0.5))
            self.exit_button = DirectButton(text = "EXIT", scale = 0.12, command = self.exit_game, pos=(0, 0, -0.5))
            self.continue_on_screen = True
        
    def remove_menu(self):
        if self.you_lose:
            self.you_lose.removeNode()
        if self.restart_button:
            self.restart_button.removeNode()
        if self.exit_button:
            self.exit_button.removeNode()
    
    def restart_game(self,game):
        game.paused = False
        self.continue_on_screen = False
        game.score += 1
        self.remove_menu()
        self.health = 100
            
    def exit_game(self):
        self.remove_menu()
        sys.exit()