Example #1
0
class LoadingScreen():
    def __init__(self):
        # a fill panel so the player doesn't see how everything
        # gets loaded in the background
        self.frameMain = DirectFrame(
            # size of the frame
            frameSize = (base.a2dLeft, base.a2dRight,
                         base.a2dTop, base.a2dBottom),
			image = "Logo.png",
			image_scale = (0.612/2.0, 1, 0.495/2.0),
			image_pos = (0, 0, 0.7),
            # tramsparent bg color
            frameColor = (0, 0, 0, 1))
        self.frameMain.setTransparency(1)

        # the text Loading... on top
        self.lblLoading = DirectLabel(
            scale = 0.25,
            pos = (0, 0, 0),
            frameColor = (0, 0, 0, 0),
            text = _("Loading..."),
            text_align = TextNode.ACenter,
            text_fg = (1,1,1,1))
        self.lblLoading.reparentTo(self.frameMain)

        # the waitbar on the bottom
        self.wbLoading = DirectWaitBar(
            text = "0%",
            text_fg = (1,1,1,1),
            value = 0,
            pos = (0, 0, -0.5),
            barColor = (0.5, 0.4, 0.1, 1),
            frameColor = (0.1, 0.1, 0.1, 1))
        self.wbLoading.reparentTo(self.frameMain)

    def show(self):
        self.frameMain.show()
        # and render two frames so the loading screen
        # is realy shown on screen
        base.graphicsEngine.renderFrame()
        base.graphicsEngine.renderFrame()

    def hide(self):
        self.frameMain.hide()

    def setLoadingValue(self, value):
        """Set the waitbar value to the given value, where
        value has to be a integer from 0 to 100"""
        if value > 100: value = 100
        if value < 0: value = 0
        self.wbLoading["value"] = value
        self.wbLoading["text"] = "{0}%".format(value)
        base.graphicsEngine.renderFrame()
        base.graphicsEngine.renderFrame()
Example #2
0
class GyroApp(ShowBase):

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

        self.graphics = Graphics()
        self.environment = Environment()
        self.physics = Physics()

        #self.level = testlevels.SimpleBridge()
        #self.level = testlevels.ObstacleWall()
        self.level = testlevels.Staircase()
        self.level.enable_physics(self.physics)

        self.player = Player(self.level)
        self.player.model.setPos(-10, 0, 1)
        self.player.enable_physics(self.physics)

        self.graphics.camera_target = self.player
        self.environment.spotlight_target = self.player.model

        self.health_bar = DirectWaitBar(pos = (0, 0, -0.9), scale = 0.5,
                                        frameColor = Vec4(0.3, 0.3, 0.3, 0.8),
                                        relief = 5, borderWidth = (0.05,0.05))
        self.health_bar.reparentTo(aspect2d)
        self.max_health = self.player.health
        taskMgr.add(self.update_health, "UpdateHealthTask")

        self.accept("escape", self.reset)

    def update_health(self, task):
        value = self.player.health / self.max_health
        self.health_bar['value'] = 100 * value
        self.health_bar['barColor'] = Vec4(1 - value, value, 0, 0.8)
        return task.cont

    def reset(self):
        self.player.reset()
        self.level.reset()
class RemoteDodgeballAvatar(RemoteAvatar):
    """A wrapper around a remote DistributedToon for use in the Dodgeball minigame (client side)"""

    notify = directNotify.newCategory("RemoteDodgeballAvatar")

    def __init__(self, mg, cr, avId):
        RemoteAvatar.__init__(self, mg, cr, avId)
        self.health = 100
        self.retrieveAvatar()
        if game.process == 'client':
            self.healthBar = DirectWaitBar(value=100)
            self.healthBar.setBillboardAxis()
            self.healthBar.reparentTo(self.avatar)
            self.healthBar.setZ(self.avatar.nametag3d.getZ(self.avatar) + 1)
            print "generated health bar"

    def setHealth(self, hp):
        self.avatar.announceHealth(0, self.health - hp)
        self.health = hp
        self.healthBar['value'] = hp
        print self.healthBar['value']
        ToontownIntervals.start(
            ToontownIntervals.getPulseSmallerIval(
                self.healthBar,
                self.mg.uniqueName('RemoteDodgeballAvatar-PulseHPBar')))

    def setTeam(self, team):
        print "set team {0}".format(team)
        RemoteAvatar.setTeam(self, team)
        self.healthBar['barColor'] = TEAM_COLOR_BY_ID[team]
        self.teamText.node().setText("")
        self.teamText.node().setTextColor(TEAM_COLOR_BY_ID[team])

    def cleanup(self):
        self.healthBar.destroy()
        self.healthbar = None
        self.health = None
        RemoteAvatar.cleanup(self)
Example #4
0
    def __init__(self):
        #create Queue to hold the incoming chat
        #request the heartbeat so that the caht interface is being refreshed in order to get the message from other player

        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "cam-left": 0,
            "cam-right": 0,
            "charge": 0
        }
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        self.cManager = ConnectionManager()
        self.cManager.startConnection()
        #------------------------------
        #Chat
        Chat(self.cManager)

        #send dummy login info of the particular client
        #send first chat info
        #---------------------------------------
        self.userName = username
        dummy_login = {
            'user_id': self.userName,
            'factionId': faction,
            'password': '******'
        }
        self.cManager.sendRequest(Constants.RAND_STRING, dummy_login)

        chat = {
            'userName': self.userName,  #username
            'message': '-------Login------'
        }
        self.cManager.sendRequest(Constants.CMSG_CHAT, chat)

        #--------------------------------------
        #self.minimap = OnscreenImage(image="images/minimap.png", scale=(0.2,1,0.2), pos=(-1.1,0,0.8))

        #frame = DirectFrame(text="Resource Bar", scale=0.001)

        resource_bar = DirectWaitBar(text="",
                                     value=35,
                                     range=100,
                                     pos=(0, 0, 0.9),
                                     barColor=(255, 255, 0, 1),
                                     frameSize=(-0.3, 0.3, 0, 0.03))
        cp_bar = DirectWaitBar(text="",
                               value=70,
                               range=100,
                               pos=(1.0, 0, 0.9),
                               barColor=(0, 0, 255, 1),
                               frameSize=(-0.3, 0.3, 0, 0.03),
                               frameColor=(255, 0, 0, 1))

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        self.environ = loader.loadModel("models/world")
        self.environ.reparentTo(render)
        self.environ.setPos(0, 0, 0)

        # Create the main character, Ralph

        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph", {
            "run": "models/ralph-run",
            "walk": "models/ralph-walk"
        })
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos)

        nameplate = TextNode('textNode username_' + str(self.userName))
        nameplate.setText(self.userName)
        npNodePath = self.ralph.attachNewNode(nameplate)
        npNodePath.setScale(0.8)
        npNodePath.setBillboardPointEye()
        #npNodePath.setPos(1.0,0,6.0)
        npNodePath.setZ(6.5)

        bar = DirectWaitBar(value=100, scale=1.0)
        bar.setColor(255, 0, 0)
        #bar.setBarRelief()
        bar.setZ(6.0)
        bar.setBillboardPointEye()
        bar.reparentTo(self.ralph)

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_right", self.setKey, ["right", 1])
        self.accept("arrow_up", self.setKey, ["forward", 1])
        self.accept("a", self.setKey, ["cam-left", 1])
        self.accept("s", self.setKey, ["cam-right", 1])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right-up", self.setKey, ["right", 0])
        self.accept("arrow_up-up", self.setKey, ["forward", 0])
        self.accept("a-up", self.setKey, ["cam-left", 0])
        self.accept("s-up", self.setKey, ["cam-right", 0])
        self.accept("c", self.setKey, ["charge", 1])
        self.accept("c-up", self.setKey, ["charge", 0])

        taskMgr.add(self.move, "moveTask")

        # Game state variables
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2)

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 1000)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0, 0, 1000)
        self.camGroundRay.setDirection(0, 0, -1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
class DistributedCannonDefenseShip(DistributedNPCSimpleShip):
    __module__ = __name__
    specialHitSfx = {}
    coldShotHitSfx = None
    sharkChompSfx = {}

    def __init__(self, cr):
        DistributedNPCSimpleShip.__init__(self, cr)
        self.goldStolenlbl = None
        self.hasGoldlbl = None
        self.hasBNote = None
        self.textureCard = None
        self.goldIcon = None
        self.flameEffects = []
        self.isSinkingWhileOnFire = False
        self.healthModifier = 0
        self.modifierSet = False
        self.shipStatsSet = False
        self.shipStatIndex = None
        self.initHealthBar()
        self.initIndicatorIcons()
        self.sinkTimeScale = CannonDefenseGlobals.SHIP_SINK_DURATION_SCALE
        self.sharkActor = Actor(
            'models/char/pir_r_gam_fsh_lgComTshark.bam',
            {'attack': 'models/char/pir_a_gam_fsh_lgComTshark_attack.bam'})
        self.sharkParallel = None
        self.fader = None
        if not self.coldShotHitSfx:
            DistributedCannonDefenseShip.specialHitSfx = {
                InventoryType.DefenseCannonMineInWater:
                loadSfx(SoundGlobals.SFX_MINIGAME_CANNON_MINE_HIT),
                InventoryType.DefenseCannonBomb:
                loadSfx(SoundGlobals.SFX_MINIGAME_CANNON_BOMB_HIT),
                InventoryType.DefenseCannonHotShot:
                loadSfx(SoundGlobals.SFX_MINIGAME_CANNON_HOTSHOT_HIT),
                InventoryType.DefenseCannonFireStorm:
                loadSfx(SoundGlobals.SFX_MINIGAME_CANNON_FIRESTORM_HIT),
                InventoryType.DefenseCannonChumShot:
                loadSfx(SoundGlobals.SFX_MINIGAME_CANNON_SHARK)
            }
            DistributedCannonDefenseShip.coldShotHitSfx = loadSfx(
                SoundGlobals.SFX_MINIGAME_CANNON_ICE_HIT)
            DistributedCannonDefenseShip.sharkChompSfxs = [
                loadSfx(SoundGlobals.SFX_MONSTER_SMASH_01),
                loadSfx(SoundGlobals.SFX_MONSTER_SMASH_02),
                loadSfx(SoundGlobals.SFX_MONSTER_SMASH_03)
            ]
        return

    def buildShip(self):
        DistributedNPCSimpleShip.buildShip(self)
        self.model.sfxAlternativeStyle = True

    def setupLocalStats(self):
        DistributedNPCSimpleShip.setupLocalStats(self)

    def setShipStatIndex(self, statIndex):
        self.shipStatsSet = True
        self.shipStatIndex = statIndex
        self.maxHp = CannonDefenseGlobals.shipStats[
            self.shipStatIndex]['shipHp']
        self.maxMastHealth = CannonDefenseGlobals.shipStats[
            self.shipStatIndex]['mastHp']
        self.healthBar.setPos(
            0.0, 0.0, CannonDefenseGlobals.shipStats[self.shipStatIndex]
            ['healthBarHeight'])
        if self.modifierSet:
            self.calcModifiedHealth()

    def setHealthModifier(self, modifier):
        self.modifierSet = True
        self.healthModifier = modifier
        if self.shipStatsSet:
            self.calcModifiedHealth()

    def calcModifiedHealth(self):
        if self.healthModifier == 0:
            return
        self.maxHp += self.healthModifier * (
            self.maxHp * CannonDefenseGlobals.ENEMY_DIFFICULTY_INCREASE)
        mastList = CannonDefenseGlobals.shipStats[self.shipStatIndex]['mastHp']
        mastFinalHp = []
        for mastHealth in mastList:
            hp = mastHealth
            hp += self.healthModifier * (
                mastHealth * CannonDefenseGlobals.ENEMY_DIFFICULTY_INCREASE)
            mastFinalHp.append(hp)

        self.maxMastHealth = mastFinalHp

    def setLogo(self, logo):
        self.logo = logo

    def setStyle(self, style):
        self.style = style

    def announceGenerate(self):
        DistributedNPCSimpleShip.announceGenerate(self)
        rad = (self.model.dimensions / 2.0).length()
        cn = NodePath(CollisionNode('c'))
        cs = CollisionSphere(0, 0, 0, rad)
        cn.node().addSolid(cs)
        cn.reparentTo(self.model.modelCollisions)
        cn.setTransform(self.model.center.getTransform(self))
        cn.node().setIntoCollideMask(PiratesGlobals.GenericShipBitmask)
        self.model.defendSphere = cn
        self.model.modelRoot.setScale(CannonDefenseGlobals.SHIP_SCALE)
        self.fadeIn(CannonDefenseGlobals.SHIP_FADEIN)
        self.smoother.setExpectedBroadcastPeriod(0.3)
        self.smoother.setDelay(2)
        self.healthBar.reparentTo(self.model.modelRoot)

    def initHealthBar(self):
        self.healthBar = DirectWaitBar(frameSize=(-0.35, 0.35, -0.04, 0.04),
                                       relief=DGG.FLAT,
                                       frameColor=(0.0, 0.0, 0.0, 0.0),
                                       borderWidth=(0.0, 0.0),
                                       barColor=(0.0, 1.0, 0.0, 1.0),
                                       scale=100)
        self.healthBar.setBillboardPointEye()
        self.healthBar['value'] = 100
        self.healthBar.hide(OTPRender.ReflectionCameraBitmask)
        self.healthBar.setLightOff()

    def initIndicatorIcons(self):
        self.textureCard = loader.loadModel(
            'models/textureCards/pir_m_gam_can_ship_icons')
        if self.textureCard:
            self.goldIcon = self.textureCard.find('**/pir_t_shp_can_gold*')
        self.goldStolenlbl = DirectLabel(
            parent=self.healthBar,
            relief=None,
            pos=(0, 0, 0.2),
            text_align=TextNode.ACenter,
            text_scale=0.5,
            textMayChange=0,
            text='!',
            text_fg=PiratesGuiGlobals.TextFG23,
            text_shadow=PiratesGuiGlobals.TextShadow,
            text_font=PiratesGlobals.getPirateBoldOutlineFont(),
            sortOrder=2)
        self.goldStolenlbl.setTransparency(1)
        self.goldStolenlbl.hide()
        self.hasGoldlbl = DirectLabel(parent=self.healthBar,
                                      relief=None,
                                      pos=(0, 0, 0.35),
                                      image=self.goldIcon,
                                      image_scale=0.5,
                                      image_pos=(0, 0, 0),
                                      sortOrder=2)
        self.hasGoldlbl.setTransparency(1)
        self.hasGoldlbl.hide()
        self.hasBNote = self.healthBar.attachNewNode('noteIndicator')
        self.bnoteBack = loader.loadModel(
            'models/textureCards/skillIcons').find(
                '**/pir_t_gui_can_moneyIcon').copyTo(self.hasBNote)
        self.hasBNote.setZ(0.35)
        self.hasBNote.setScale(0.6)
        self.hasBNote.hide()
        return

    def getHealthBarColor(self, health):
        return CannonDefenseGlobals.SHIP_HEALTH_COLORS[int(
            health / 100.0 *
            (len(CannonDefenseGlobals.SHIP_HEALTH_COLORS) - 1))]

    def setHealthState(self, health):
        DistributedNPCSimpleShip.setHealthState(self, health)
        self.healthBar['value'] = health
        self.healthBar['barColor'] = self.getHealthBarColor(health)

    def setCurrentState(self, state):
        if state == CannonDefenseGlobals.SHIP_STATE_STEALING:
            self.goldStolenlbl.show()
        else:
            if state == CannonDefenseGlobals.SHIP_STATE_HASTREASURE:
                self.hasGoldlbl.show()
                self.goldStolenlbl.hide()
            else:
                if state == CannonDefenseGlobals.SHIP_STATE_HASBNOTES:
                    self.hasBNote.show()
                    self.goldStolenlbl.hide()
                else:
                    self.hasGoldlbl.hide()
                    self.hasBNote.hide()
                    self.goldStolenlbl.hide()
        rad = (self.model.dimensions / 2.0).length()
        cn = NodePath(CollisionNode('c'))
        cs = CollisionSphere(0, 0, 0, rad)
        cn.node().addSolid(cs)
        cn.reparentTo(self.model.modelCollisions)
        cn.setTransform(self.model.center.getTransform(self))
        cn.node().setIntoCollideMask(PiratesGlobals.GenericShipBitmask)
        self.model.defendSphere = cn
        self.model.modelRoot.setScale(CannonDefenseGlobals.SHIP_SCALE)
        self.fadeIn(CannonDefenseGlobals.SHIP_FADEIN)
        self.smoother.setExpectedBroadcastPeriod(0.3)
        self.smoother.setDelay(2)
        self.healthBar.reparentTo(self.model.modelRoot)

    def initHealthBar(self):
        self.healthBar = DirectWaitBar(frameSize=(-0.35, 0.35, -0.04, 0.04),
                                       relief=DGG.FLAT,
                                       frameColor=(0.0, 0.0, 0.0, 0.0),
                                       borderWidth=(0.0, 0.0),
                                       barColor=(0.0, 1.0, 0.0, 1.0),
                                       scale=100)
        self.healthBar.setBillboardPointEye()
        self.healthBar['value'] = 100
        self.healthBar.hide(OTPRender.ReflectionCameraBitmask)
        self.healthBar.setLightOff()

    def initIndicatorIcons(self):
        self.textureCard = loader.loadModel(
            'models/textureCards/pir_m_gam_can_ship_icons')
        if self.textureCard:
            self.goldIcon = self.textureCard.find('**/pir_t_shp_can_gold*')
        self.goldStolenlbl = DirectLabel(
            parent=self.healthBar,
            relief=None,
            pos=(0, 0, 0.2),
            text_align=TextNode.ACenter,
            text_scale=0.5,
            textMayChange=0,
            text='!',
            text_fg=PiratesGuiGlobals.TextFG23,
            text_shadow=PiratesGuiGlobals.TextShadow,
            text_font=PiratesGlobals.getPirateBoldOutlineFont(),
            sortOrder=2)
        self.goldStolenlbl.setTransparency(1)
        self.goldStolenlbl.hide()
        self.hasGoldlbl = DirectLabel(parent=self.healthBar,
                                      relief=None,
                                      pos=(0, 0, 0.35),
                                      image=self.goldIcon,
                                      image_scale=0.5,
                                      image_pos=(0, 0, 0),
                                      sortOrder=2)
        self.hasGoldlbl.setTransparency(1)
        self.hasGoldlbl.hide()
        self.hasBNote = self.healthBar.attachNewNode('noteIndicator')
        self.bnoteBack = loader.loadModel(
            'models/textureCards/skillIcons').find(
                '**/pir_t_gui_can_moneyIcon').copyTo(self.hasBNote)
        self.hasBNote.setZ(0.35)
        self.hasBNote.setScale(0.6)
        self.hasBNote.hide()
        return

    def getHealthBarColor(self, health):
        return CannonDefenseGlobals.SHIP_HEALTH_COLORS[int(
            health / 100.0 *
            (len(CannonDefenseGlobals.SHIP_HEALTH_COLORS) - 1))]

    def setHealthState(self, health):
        DistributedNPCSimpleShip.setHealthState(self, health)
        self.healthBar['value'] = health
        self.healthBar['barColor'] = self.getHealthBarColor(health)

    def setCurrentState(self, state):
        if state == CannonDefenseGlobals.SHIP_STATE_STEALING:
            self.goldStolenlbl.show()
        else:
            if state == CannonDefenseGlobals.SHIP_STATE_HASTREASURE:
                self.hasGoldlbl.show()
                self.goldStolenlbl.hide()
            else:
                if state == CannonDefenseGlobals.SHIP_STATE_HASBNOTES:
                    self.hasBNote.show()
                    self.goldStolenlbl.hide()
                else:
                    self.hasGoldlbl.hide()
                    self.hasBNote.hide()
                    self.goldStolenlbl.hide()

    def calculateLook(self):
        pass

    def playProjectileHitSfx(self, ammoSkillId, hitSail):
        if ammoSkillId in [
                InventoryType.DefenseCannonColdShotInWater,
                InventoryType.DefenseCannonSmokePowder
        ]:
            return
        if ammoSkillId in self.specialHitSfx:
            sfx = self.specialHitSfx[ammoSkillId]
            base.playSfx(sfx, node=self, cutoff=2000)
            return
        DistributedNPCSimpleShip.playProjectileHitSfx(self, ammoSkillId,
                                                      hitSail)

    def projectileWeaponHit(self,
                            skillId,
                            ammoSkillId,
                            skillResult,
                            targetEffects,
                            pos,
                            normal,
                            codes,
                            attacker,
                            itemEffects=[]):
        DistributedNPCSimpleShip.projectileWeaponHit(self, skillId,
                                                     ammoSkillId, skillResult,
                                                     targetEffects, pos,
                                                     normal, codes, attacker,
                                                     itemEffects)

    def sinkingBegin(self):
        self.healthBar.reparentTo(hidden)
        if len(self.flameEffects) > 0:
            self.isSinkingWhileOnFire = True
        DistributedNPCSimpleShip.sinkingBegin(self)

    def sinkingEnd(self):
        while len(self.flameEffects) > 0:
            effect = self.flameEffects.pop()
            effect.stopLoop()

        DistributedNPCSimpleShip.sinkingEnd(self)

    def addStatusEffect(self,
                        effectId,
                        attackerId,
                        duration=0,
                        timeLeft=0,
                        timestamp=0,
                        buffData=[0]):
        if effectId == WeaponGlobals.C_CANNON_DEFENSE_FIRE:
            self.addFireEffect(self.getModelRoot().getPos())
        if effectId == WeaponGlobals.C_CANNON_DEFENSE_ICE:
            base.playSfx(self.coldShotHitSfx, node=self, cutoff=2000)
        DistributedNPCSimpleShip.addStatusEffect(self, effectId, attackerId,
                                                 duration, timeLeft, timestamp,
                                                 buffData)

    def removeStatusEffect(self, effectId, attackerId):
        DistributedNPCSimpleShip.removeStatusEffect(self, effectId, attackerId)
        if effectId == WeaponGlobals.C_CANNON_DEFENSE_FIRE:
            if not self.isSinkingWhileOnFire:
                while len(self.flameEffects) > 0:
                    effect = self.flameEffects.pop()
                    effect.stopLoop()

    def addFireEffect(self, pos):
        fireEffect = ShipFire.getEffect()
        if fireEffect:
            fireEffect.reparentTo(self.getModelRoot())
            fireEffect.setPos(pos)
            fireEffect.setHpr(90, -15, 0)
            fireEffect.startLoop()
            fireEffect.setEffectScale(20.0)
            self.flameEffects.append(fireEffect)

    def playSharkAttack(self, pos):
        if self.sharkActor.getCurrentAnim() == None:
            self.sharkActor.wrtReparentTo(self.getModelRoot())
            self.sharkActor.setPos(self, pos)
            self.sharkActor.setScale(20)
            self.sharkActor.play('attack')
            sharkAttackEffect = None
            if base.options.getSpecialEffectsSetting(
            ) >= base.options.SpecialEffectsLow:
                effect = CannonSplash.getEffect()
                if effect:
                    effect.reparentTo(base.effectsRoot)
                    effect.setPos(self, pos)
                    effect.setZ(1)
                    effect.play()
                sharkAttackEffect = Func(self.playAttackEffect, pos)
            hprIvalShip = LerpHprInterval(self.getModelRoot(),
                                          duration=3,
                                          hpr=(0, 0, -180))
            s1 = Sequence(Wait(0.75), hprIvalShip,
                          Func(self.getModelRoot().stash))
            s2 = Sequence(Wait(0.75), sharkAttackEffect, Wait(0.5),
                          sharkAttackEffect)
            self.sharkParallel = Parallel(s1, s2)
            self.sharkParallel.start()
            taskMgr.doMethodLater(self.sharkActor.getDuration('attack'),
                                  self.detachShark,
                                  self.uniqueName('playSharkAttack'),
                                  extraArgs=[])
        return

    def playAttackEffect(self, pos):
        effect = BulletEffect.getEffect()
        if effect:
            effect.reparentTo(base.effectsRoot)
            effect.setPos(self, pos)
            effect.loadObjects(6)
            effect.play()
        sfx = random.choice(self.sharkChompSfxs)
        base.playSfx(sfx, node=self.getModelRoot(), cutoff=2000)

    def detachShark(self):
        self.sharkActor.detachNode()

    def delete(self):
        if self.fader:
            self.fader.pause()
            self.fader = None
        DistributedNPCSimpleShip.delete(self)
        return

    def destroy(self):
        if self.goldStolenlbl:
            self.goldStolenlbl.destroy()
            self.goldStolenlbl = None
        if self.hasGoldlbl:
            self.hasGoldlbl.destroy()
            self.hasGoldlbl = None
        if self.textureCard:
            self.textureCard.removeNode()
            self.textureCard = None
            self.goldIcon = None
        if self.healthBar:
            self.healthBar.destroy()
        if self.sharkActor:
            self.sharkActor.cleanUp()
            self.sharkActor.removeNode()
        if self.sharkParallel:
            self.sharkParallel.pause()
            self.sharkParallel = None
        DistributedNPCSimpleShip.destroy(self)
        return

    def fadeIn(self, length):
        if self.fader:
            self.fader.finish()
            self.fader = None
        self.setTransparency(1)
        self.fader = Sequence(
            self.colorScaleInterval(length, Vec4(1, 1, 1, 1), Vec4(1, 1, 1,
                                                                   0)),
            Func(self.clearTransparency))
        self.fader.start()
        return

    def fadeOut(self, length):
        if self.fader:
            self.fader.finish()
            self.fader = None
        self.setTransparency(1)
        self.fader = Sequence(
            self.colorScaleInterval(length, Vec4(1, 1, 1, 0), Vec4(1, 1, 1,
                                                                   1)),
            Func(self.hide), Func(self.clearTransparency))
        self.fader.start()
        return
Example #6
0
    def __init__(self):
        #create Queue to hold the incoming chat
        #request the heartbeat so that the caht interface is being refreshed in order to get the message from other player
        
        self.keyMap = {"left":0, "right":0, "forward":0, "cam-left":0, "cam-right":0, "charge":0}
        base.win.setClearColor(Vec4(0,0,0,1))

        self.cManager = ConnectionManager()
        self.cManager.startConnection()
        #------------------------------
        #Chat
        Chat(self.cManager)
        
        
        #send dummy login info of the particular client
        #send first chat info 
        #---------------------------------------
        self.userName = username
        dummy_login ={'user_id' : self.userName, 'factionId': faction, 'password': '******'}
        self.cManager.sendRequest(Constants.RAND_STRING, dummy_login)
        
        
        chat = { 'userName' : self.userName,     #username
                 'message'    : '-------Login------' }
        self.cManager.sendRequest(Constants.CMSG_CHAT, chat)

        #--------------------------------------
        #self.minimap = OnscreenImage(image="images/minimap.png", scale=(0.2,1,0.2), pos=(-1.1,0,0.8))

        #frame = DirectFrame(text="Resource Bar", scale=0.001)

        resource_bar = DirectWaitBar(text="",
            value=35, range=100, pos=(0,0,0.9), barColor=(255,255,0,1),
            frameSize=(-0.3,0.3,0,0.03))
        cp_bar = DirectWaitBar(text="",
            value=70, range=100, pos=(1.0,0,0.9), barColor=(0,0,255,1),
            frameSize=(-0.3,0.3,0,0.03), frameColor=(255,0,0,1))

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.  

        

        self.environ = loader.loadModel("models/world")      
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        
        # Create the main character, Ralph

        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph",
                                 {"run":"models/ralph-run",
                                  "walk":"models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos)

        nameplate = TextNode('textNode username_' + str(self.userName))
        nameplate.setText(self.userName)
        npNodePath = self.ralph.attachNewNode(nameplate)
        npNodePath.setScale(0.8)
        npNodePath.setBillboardPointEye()
        #npNodePath.setPos(1.0,0,6.0)
        npNodePath.setZ(6.5)

        bar = DirectWaitBar(value=100, scale=1.0)
        bar.setColor(255,0,0)
        #bar.setBarRelief()
        bar.setZ(6.0)
        bar.setBillboardPointEye()
        bar.reparentTo(self.ralph)

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.
        
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left",1])
        self.accept("arrow_right", self.setKey, ["right",1])
        self.accept("arrow_up", self.setKey, ["forward",1])
        self.accept("a", self.setKey, ["cam-left",1])
        self.accept("s", self.setKey, ["cam-right",1])
        self.accept("arrow_left-up", self.setKey, ["left",0])
        self.accept("arrow_right-up", self.setKey, ["right",0])
        self.accept("arrow_up-up", self.setKey, ["forward",0])
        self.accept("a-up", self.setKey, ["cam-left",0])
        self.accept("s-up", self.setKey, ["cam-right",0])
        self.accept("c", self.setKey, ["charge",1])
        self.accept("c-up", self.setKey, ["charge",0])

        taskMgr.add(self.move,"moveTask")

        # Game state variables
        self.isMoving = False

        # Set up the camera
        
        base.disableMouse()
        base.camera.setPos(self.ralph.getX(),self.ralph.getY()+10,2)
        
        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0,0,1000)
        self.ralphGroundRay.setDirection(0,0,-1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0,0,1000)
        self.camGroundRay.setDirection(0,0,-1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()
       
        # Uncomment this line to show a visual representation of the 
        # collisions occuring
        #self.cTrav.showCollisions(render)
        
        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
class CIProgressScreen:

    Color = (118 / 255.0, 121 / 255.0, 127 / 255.0, 1.0)
    BarColor = (152 / 255.0, 129 / 255.0, 64 / 255.0, 1.0)

    def __init__(self):
        self.defaultLogoScale = 1
        self.defaultLogoZ = 0.65
        self.bgm = loader.loadModel(
            "phase_3/models/gui/progress-background.bam")
        self.bgm.find('**/logo').stash()
        self.barShadow = OnscreenImage(image=self.bgm.find("**/bar_shadow"),
                                       parent=hidden)
        self.bgm.find("**/bar_shadow").removeNode()
        self.bg = self.bgm.find('**/bg')
        self.defaultBgTexture = self.bg.findTexture('*')

        self.logoNode, self.logoImg = CIGlobals.getLogoImage(
            hidden, self.defaultLogoScale, (0, 0, self.defaultLogoZ))

        self.bg_img = OnscreenImage(image=self.bg, parent=hidden)
        self.bg_img.setSx(1.35)
        self.bg_img.hide()
        self.progress_bar = DirectWaitBar(value=0,
                                          pos=(0, 0, -0.85),
                                          parent=hidden,
                                          text_pos=(0, 0, 0.2))
        self.progress_bar.setSx(1.064)
        self.progress_bar.setSz(0.38)
        toontipgui = loader.loadModel(
            'phase_3.5/models/gui/stickerbook_gui.bam')
        poster = toontipgui.find('**/questCard')
        self.toontipFrame = DirectFrame(image=poster,
                                        image_scale=(1.4, 1, 1),
                                        parent=hidden,
                                        relief=None,
                                        pos=(0, 0, -0.1),
                                        scale=0.85)
        self.toontipLbl = OnscreenText(text="",
                                       parent=self.toontipFrame,
                                       fg=(89.0 / 255, 95.0 / 255, 98.0 / 255,
                                           1),
                                       font=CIGlobals.getToonFont(),
                                       wordwrap=13,
                                       pos=(-0.59, 0.25),
                                       align=TextNode.ALeft,
                                       scale=0.08)
        self.loading_lbl = DirectLabel(text="",
                                       relief=None,
                                       scale=0.08,
                                       pos=(-1.0725, 0, -0.79),
                                       text_align=TextNode.ALeft,
                                       sortOrder=100,
                                       text_fg=(1, 1, 1, 1),
                                       text_font=CIGlobals.getMinnieLogoFont(),
                                       parent=hidden,
                                       text_shadow=(0, 0, 0, 0))

        # This is useful when the user has chosen to hide aspect2d before the loading screen.
        # However, we want to show the loading screen all the time, so we need to restore the
        # previous state after the loading screen ends.
        self.mustRestoreHiddenAspect2d = False

    def begin(self, hood, range, wantGui):
        render.hide()
        NametagGlobals.setWant2dNametags(False)

        if base.aspect2d.isHidden():
            base.aspect2d.show()
            self.mustRestoreHiddenAspect2d = True

        self.renderFrames()
        base.setBackgroundColor(0, 0, 0)
        if hood == "localAvatarEnterGame":
            self.loading_lbl['text'] = "Entering..."
        elif hood == "init":
            self.loading_lbl['text'] = "Loading..."
        else:
            self.loading_lbl['text'] = "Heading to %s..." % hood
        self.progress_bar['barColor'] = self.BarColor
        self.progress_bar['range'] = range
        self.bgm.reparentTo(aspect2d)

        ZoneUtil.Hood2ZoneId.keys()

        # We only want to show special loading screens for actual in-game locations.
        if hood in ZoneUtil.Hood2ZoneId.keys():
            abbr = ZoneUtil.ZoneId2HoodAbbr.get(
                ZoneUtil.Hood2ZoneId.get(hood)).lower()
            bgTexture = loader.loadTexture(
                'phase_14/maps/{0}_loading.png'.format(abbr), okMissing=True)

            if bgTexture:
                self.bg.setTexture(bgTexture, 1)

        self.barShadow.reparentTo(aspect2d)
        self.bg.reparentTo(render2d)
        self.bg_img.reparentTo(hidden)
        self.loading_lbl.reparentTo(aspect2d)
        self.logoNode.reparentTo(aspect2d)
        self.progress_bar.reparentTo(aspect2d)
        tip = random.choice(CIGlobals.ToonTips)
        self.toontipLbl.setText("TOON TIP:\n" + tip)
        self.toontipFrame.reparentTo(aspect2d)
        self.__count = 0
        self.__expectedCount = range
        self.progress_bar.update(self.__count)

    def renderFramesTask(self, task):
        self.renderFrames()
        return task.cont

    def end(self):
        base.setBackgroundColor(CIGlobals.DefaultBackgroundColor)
        taskMgr.remove("renderFrames")
        render.show()

        if self.mustRestoreHiddenAspect2d:
            base.aspect2d.hide()
            self.mustRestoreHiddenAspect2d = False

        self.progress_bar.finish()
        self.bg_img.reparentTo(hidden)
        self.logoNode.reparentTo(hidden)
        self.barShadow.reparentTo(hidden)
        self.bg.reparentTo(hidden)

        # Let's get rid of the extra texture stage.
        self.bg.setTexture(self.defaultBgTexture, 1)

        self.bgm.reparentTo(hidden)
        self.loading_lbl.reparentTo(hidden)
        self.progress_bar.reparentTo(hidden)
        self.toontipFrame.reparentTo(hidden)
        base.transitions.fadeScreen(1.0)
        NametagGlobals.setWant2dNametags(True)
        self.renderFrames()

    def destroy(self):
        self.bg.removeNode()
        del self.bg
        self.bgm.removeNode()
        del self.bgm
        self.bg_img.destroy()
        self.barShadow.destroy()
        del self.barShadow
        self.loading_lbl.destroy()
        self.progress_bar.destroy()
        self.bgm.destroy()
        self.mustRestoreHiddenAspect2d = False
        del self.bg_img
        del self.loading_lbl
        del self.progress_bar
        del self.bgm
        del self.defaultBgTexture
        del self.mustRestoreHiddenAspect2d

    def renderFrames(self):
        base.graphicsEngine.renderFrame()
        base.graphicsEngine.renderFrame()

    def tick(self):
        self.__count += 1
        self.progress_bar.update(self.__count)
Example #8
0
class CIProgressScreen:

    def __init__(self):
        self.bgm = loader.loadModel('phase_3/models/gui/progress-background.bam')
        self.bgm.find('**/logo').stash()
        self.bg = self.bgm.find('**/bg')
        self.logo = loader.loadTexture('phase_3/maps/CogInvasion_Logo.png')
        self.logoImg = OnscreenImage(image=self.logo, scale=(0.5, 0, 0.3), pos=(0, 0, 0), parent=hidden)
        self.logoImg.setTransparency(True)
        self.bg_img = OnscreenImage(image=self.bg, parent=hidden)
        self.bg_img.setSx(1.35)
        self.bg_img.hide()
        self.progress_bar = DirectWaitBar(value=0, pos=(0, 0, -0.85), parent=hidden, text_pos=(0, 0, 0.2))
        self.progress_bar.setSx(1.064)
        self.progress_bar.setSz(0.38)
        self.loading_lbl = DirectLabel(text='', relief=None, scale=0.08, pos=(-1.0725, 0, -0.79), text_align=TextNode.ALeft, sortOrder=100, text_fg=(0.343, 0.343, 0.343, 1.0), text_font=CIGlobals.getMinnieFont(), parent=hidden, text_shadow=(0, 0, 0, 1))
        return

    def begin(self, hood, range, wantGui):
        render.hide()
        self.renderFrames()
        base.setBackgroundColor(0, 0, 0)
        if hood == 'localAvatarEnterGame':
            self.loading_lbl['text'] = 'Entering...'
        elif hood == 'init':
            self.loading_lbl['text'] = 'Loading...'
        else:
            self.loading_lbl['text'] = 'Heading to %s...' % hood
        self.progress_bar['barColor'] = (0.343, 0.343, 0.343, 1.0)
        self.progress_bar['range'] = range
        self.bgm.reparentTo(aspect2d)
        self.bg.reparentTo(render2d)
        self.bg_img.reparentTo(hidden)
        self.loading_lbl.reparentTo(aspect2d)
        self.logoImg.reparentTo(aspect2d)
        self.progress_bar.reparentTo(aspect2d)
        self.__count = 0
        self.__expectedCount = range
        self.progress_bar.update(self.__count)

    def renderFramesTask(self, task):
        self.renderFrames()
        return task.cont

    def end(self):
        base.setBackgroundColor(CIGlobals.DefaultBackgroundColor)
        taskMgr.remove('renderFrames')
        render.show()
        self.progress_bar.finish()
        self.bg_img.reparentTo(hidden)
        self.logoImg.reparentTo(hidden)
        self.bg.reparentTo(hidden)
        self.bgm.reparentTo(hidden)
        self.loading_lbl.reparentTo(hidden)
        self.progress_bar.reparentTo(hidden)
        self.renderFrames()

    def destroy(self):
        self.bg.removeNode()
        del self.bg
        self.bgm.removeNode()
        del self.bgm
        self.bg_img.destroy()
        self.loading_lbl.destroy()
        self.progress_bar.destroy()
        self.bgm.destroy()
        del self.bg_img
        del self.loading_lbl
        del self.progress_bar
        del self.bgm

    def renderFrames(self):
        base.graphicsEngine.renderFrame()
        base.graphicsEngine.renderFrame()

    def tick(self):
        self.__count += 1
        self.progress_bar.update(self.__count)
Example #9
0
class CIProgressScreen:

    def __init__(self):
        self.defaultLogoScale = 0.85
        self.defaultLogoZ = 0.65
        self.bgm = loader.loadModel('phase_3/models/gui/progress-background.bam')
        self.bgm.find('**/logo').stash()
        self.bg = self.bgm.find('**/bg')
        self.logo = loader.loadTexture('phase_3/maps/CogInvasion_Logo.png')
        self.logoNode = hidden.attachNewNode('logoNode')
        self.logoNode.setScale(self.defaultLogoScale)
        self.logoNode.setPos(0, self.defaultLogoZ, 0)
        self.logoImg = OnscreenImage(image=self.logo, scale=(0.685, 0, 0.3), parent=self.logoNode)
        self.logoImg.setTransparency(True)
        self.bg_img = OnscreenImage(image=self.bg, parent=hidden)
        self.bg_img.setSx(1.35)
        self.bg_img.hide()
        self.progress_bar = DirectWaitBar(value=0, pos=(0, 0, -0.85), parent=hidden, text_pos=(0,
                                                                                               0,
                                                                                               0.2))
        self.progress_bar.setSx(1.064)
        self.progress_bar.setSz(0.38)
        toontipgui = loader.loadModel('phase_3.5/models/gui/stickerbook_gui.bam')
        poster = toontipgui.find('**/questCard')
        self.toontipFrame = DirectFrame(image=poster, image_scale=(1.4, 1, 1), parent=hidden, relief=None, pos=(0,
                                                                                                                0,
                                                                                                                -0.1), scale=0.85)
        self.toontipLbl = OnscreenText(text='', parent=self.toontipFrame, fg=(0.35,
                                                                              0.35,
                                                                              0.35,
                                                                              1), font=CIGlobals.getToonFont(), wordwrap=14.5, pos=(-0.59,
                                                                                                                                    0.25), align=TextNode.ALeft, scale=0.08)
        self.loading_lbl = DirectLabel(text='', relief=None, scale=0.08, pos=(-1.0725,
                                                                              0,
                                                                              -0.79), text_align=TextNode.ALeft, sortOrder=100, text_fg=(0.343,
                                                                                                                                         0.343,
                                                                                                                                         0.343,
                                                                                                                                         1.0), text_font=CIGlobals.getMinnieFont(), parent=hidden, text_shadow=(0,
                                                                                                                                                                                                                0,
                                                                                                                                                                                                                0,
                                                                                                                                                                                                                1))
        return

    def begin(self, hood, range, wantGui):
        render.hide()
        self.renderFrames()
        base.setBackgroundColor(0, 0, 0)
        if hood == 'localAvatarEnterGame':
            self.loading_lbl['text'] = 'Entering...'
        else:
            if hood == 'init':
                self.loading_lbl['text'] = 'Loading...'
            else:
                self.loading_lbl['text'] = 'Heading to %s...' % hood
        self.progress_bar['barColor'] = (0.343, 0.343, 0.343, 1.0)
        self.progress_bar['range'] = range
        self.bgm.reparentTo(aspect2d)
        self.bg.reparentTo(render2d)
        self.bg_img.reparentTo(hidden)
        self.loading_lbl.reparentTo(aspect2d)
        self.logoNode.reparentTo(aspect2d)
        self.progress_bar.reparentTo(aspect2d)
        tip = random.choice(CIGlobals.ToonTips)
        self.toontipLbl.setText('TOON TIP:\n' + tip)
        self.toontipFrame.reparentTo(aspect2d)
        self.__count = 0
        self.__expectedCount = range
        self.progress_bar.update(self.__count)

    def renderFramesTask(self, task):
        self.renderFrames()
        return task.cont

    def end(self):
        base.setBackgroundColor(CIGlobals.DefaultBackgroundColor)
        taskMgr.remove('renderFrames')
        render.show()
        self.progress_bar.finish()
        self.bg_img.reparentTo(hidden)
        self.logoNode.reparentTo(hidden)
        self.bg.reparentTo(hidden)
        self.bgm.reparentTo(hidden)
        self.loading_lbl.reparentTo(hidden)
        self.progress_bar.reparentTo(hidden)
        self.toontipFrame.reparentTo(hidden)
        self.renderFrames()

    def destroy(self):
        self.bg.removeNode()
        del self.bg
        self.bgm.removeNode()
        del self.bgm
        self.bg_img.destroy()
        self.loading_lbl.destroy()
        self.progress_bar.destroy()
        self.bgm.destroy()
        del self.bg_img
        del self.loading_lbl
        del self.progress_bar
        del self.bgm

    def renderFrames(self):
        base.graphicsEngine.renderFrame()
        base.graphicsEngine.renderFrame()

    def tick(self):
        self.__count += 1
        self.progress_bar.update(self.__count)
Example #10
0
class Enemy(DirectObject):
    def __init__(self, _main):
        self.main = _main
        self.strenght = self.main.enemyStrength
        self.id = id(self)
        self.model = loader.loadModel("Enemy")
        self.model.setP(-90)
        self.model.setH(180)
        self.model.hide()
        cs = CollisionSphere(0, 0, 0, 0.5)
        cnode = CollisionNode('colEnemy' + str(self.id))
        cnode.addSolid(cs)
        self.colNP = self.model.attachNewNode(cnode)
        #self.colNP.show()

        # Game state
        self.health = 100 + (100 * self.strenght)
        self.damageDone = 0.1 + (0.1 * self.strenght)
        self.lastShot = 0.0
        self.attackRate = 10.0


        self.statusHealth = DirectWaitBar(
            text = "",
            value = self.health,
            range = self.health,
            frameSize = (0.12, 0.8, -0.12, 0.0),
            pos = (-0.5, 0, -0.5),
            barColor = (1, 0, 0, 1))
        self.statusHealth.reparentTo(self.model)
        self.statusHealth.setDepthWrite(False)
        self.statusHealth.setBin('fixed', 0)
        self.statusHealth.setBillboardAxis()

    def start(self, startPos, enemyParent):
        self.model.show()
        self.model.reparentTo(enemyParent)
        self.model.setPos(startPos.x,
                          startPos.y,
                          0)
        self.accept("into-" + "colEnemy" + str(self.id), self.hit)
        self.accept("inRange-" + "colEnemy" + str(self.id), self.startAttack)
        self.statusHealth.update(self.health)

    def stop(self):
        self.model.remove_node()
        self.ignore("into-" + "colEnemy" + str(self.id))
        self.ignore("inRange-" + "colEnemy" + str(self.id))

    def hit(self, _dmg):
        if self.health == 0:
            base.messenger.send("killEnemy", [self.id])
        else:
            self.health -= _dmg
            self.statusHealth.update(self.health)

    def makeAi(self):
        # Make some ai character for each
        self.aiChar = AICharacter("Enemy" + str(self.id), self.model, -100, 0.05 + (0.05 * self.strenght), 6 + (1 * self.strenght))
        self.main.AiWorld.addAiChar(self.aiChar)
        self.AIbehaviors = self.aiChar.getAiBehaviors()

        self.AIbehaviors.pursue(self.main.player.model)
        return self.aiChar

    def startAttack(self, _inRange=False):

        if _inRange:
            self.isAttacking = True
            self.simpleAttack()
            #taskMgr.remove("StartAttack")
        #elif _inRange:
        #    pass
        #    taskMgr.add(self.attack, "StartAttack")

    def attack(self, task):
        dt = globalClock.getDt()
        self.lastShot += dt
        if self.lastShot >= self.attackRate:
            self.lastShot -= self.attackRate
            base.messenger.send("doDamageToPlayer", [self.damageDone])
        return task.again

    def simpleAttack(self):
        base.messenger.send("doDamageToPlayer", [self.damageDone])
class Enemy(DirectObject):
    def __init__(self, parent, startingBlock, map, model):
        self.map = map                      # The map itself - needed for finding the path
        self.startingBlock = startingBlock  # The block the enemy is traveling to
        self.direction = 0                  # The direction the enemy is traveling (Right = 0, Down = 1, Left = 2, Up = 3)
        self.maxHealth = self.health        # The starting health of the enemy
        self.maxMoveSpeed = 1               # How many seconds it takes the enemy to move from one block to another
        self.moveSpeed = self.maxMoveSpeed  # The current movespeed
        self.isActive = 1                   # Whether the enemy is alive and moving
        self.index = -1                     # The index of the enemy
        self.distanceTravelled = 0
        
        # Load and place the model
        self.eNode = parent.attachNewNode('enemyBaseNode')
        self.eNode.setPos( startingBlock.getPos() )
        
        self.model = loader.loadModel( 'models/' + model )
        self.model.reparentTo( self.eNode )
        
        # Setup the rest of what the enemy needs
        self.setupCollision()
        self.setupHealthBar()
        
    def move(self, task):
        dist = self.moveSpeed * globalClock.getDt()
        deltaPos = DIRECTION_TO_VECTOR[self.direction] * dist
        self.eNode.setPos( self.eNode.getPos() + deltaPos )
        
        self.distanceTravelled += dist
        if( self.distanceTravelled >= 1.0 ):
            self.moveToNextBlock( self.currentBlock )
            self.distanceTravelled = 0
            return task.done
        
        return task.cont
        
    # Tells the enemy to start moving along the path
    def moveToEnd(self):
        self.moveToNextBlock( self.startingBlock )
        
    def moveToNextBlock(self, currentBlock):
        # If we've reached the last block, don't move anymore;
        # otherwise, find the next block in the path and start moving
        if( currentBlock.isType(EndBlock) ): 
            taskMgr.doMethodLater( self.moveSpeed, self.remove, 'remove' )
        else:
            self.currentBlock = self.findNextBlock( currentBlock )
            
            # Start moving
            taskMgr.add( self.move, 'move' + str(self.index) )
        
    # Locates the next block on the path based upon the enemy's current location
    def findNextBlock(self, currentBlock):
        (row, ignore, col) = currentBlock.index.partition(' ')
        row = int(row)
        col = int(col)
        dir = self.direction
        nextBlock = 0
        
        if( dir > -1 ):
            dir = (dir - 1) % 4
            
            for i in range(4):
                if( dir == 0 ):
                    nextBlock = self.map[row][col + 1]
                elif( dir == 1 ):
                    nextBlock = self.map[row - 1][col]
                elif( dir == 2 ):
                    nextBlock = self.map[row][col - 1]
                else:
                    nextBlock = self.map[row + 1][col]
                
                if( nextBlock.isType(PathBlock) or nextBlock.isType(EndBlock) ):
                    self.direction = dir
                    break
                
                dir = (dir + 1) % 4
                nextBlock = 0
                
        return nextBlock
        
    # Finds the first path block after the start block
    def findFirstPathBlock(self, currentBlock):
        (row, ignore, col) = currentBlock.index.partition(' ')
        row = int(row)
        col = int(col)
        dir = 0
        
        for dir in range(4):
                if( dir == 0 ):
                    nextBlock = self.map[row][col + 1]
                elif( dir == 1 ):
                    nextBlock = self.map[row - 1][col]
                elif( dir == 2 ):
                    nextBlock = self.map[row][col - 1]
                else:
                    nextBlock = self.map[row + 1][col]
                
                if( nextBlock.isType(PathBlock) ):
                    self.direction = dir
                    break
                
                nextBlock = 0
        
        return nextBlock
    
    # Removes the enemy once it has died or reached the end block
    def remove(self, task = None):
        #self.moveLerp.finish()
        self.isActive = 0
        self.eNode.removeNode()
        self.sphere.removeNode()
        taskMgr.remove('move' + str(self.index))
        messenger.send('enemy_removed', [self])
        
    # Sets up collision geometry so towers can find the enemy
    def setupCollision(self):
        self.sphere = self.eNode.attachNewNode( CollisionNode('object') )
        self.sphere.node().addSolid( CollisionSphere(0, 0, 0, 0.1) )
        self.sphere.node().setFromCollideMask( BitMask32.allOff() )
        self.sphere.node().setIntoCollideMask( BitMask32(2) )
        
    def setIndex(self, index):
        self.sphere.setTag('index', str(index) )
        self.index = index
        
    # Creates the health bar above the enemy
    def setupHealthBar(self):
        self.hpBar = DirectWaitBar( text = "", value = 100.0, pos = (0, 0, 1.5), scale = 0.3, barColor = Vec4(1, 0, 0, 1) )
        self.hpBar.setBillboardPointEye() 
        self.hpBar.reparentTo(self.eNode)
        #self.hpBar.clearColor()
        
    # Decreases the health of the enemy by the damage it takes
    def takeDamage(self, damage):
        self.health -= damage
        self.hpBar['value'] = (1.0 * self.health) / self.maxHealth * 100
        if( self.health <= 0 ):
            self.remove()
            
    def slow(self, fraction, duration):
        self.moveSpeed = self.maxMoveSpeed * fraction
        self.model.setColor( SLOW_COLOR )
        
        taskMgr.remove( 'removeSlow' + str(self.index) )
        taskMgr.doMethodLater( duration, self.removeSlow, 'removeSlow' + str(self.index) )
        
    def removeSlow(self, task = None):
        self.moveSpeed = self.maxMoveSpeed
        self.model.clearColor()
        
    def stun(self, duration):
        self.moveSpeed = 0
        self.model.setColor( STUN_COLOR )
        
        taskMgr.remove( 'removeStun' + str(self.index) )
        taskMgr.doMethodLater( duration, self.removeStun, 'removeStun' + str(self.index) )
        
    def removeStun(self, task = None):
        self.moveSpeed = self.maxMoveSpeed
        self.model.clearColor()
Example #12
0
class Enemy(DirectObject):
    def __init__(self, parent, startingBlock, map, model):
        self.map = map  # The map itself - needed for finding the path
        self.startingBlock = startingBlock  # The block the enemy is traveling to
        self.direction = 0  # The direction the enemy is traveling (Right = 0, Down = 1, Left = 2, Up = 3)
        self.maxHealth = self.health  # The starting health of the enemy
        self.maxMoveSpeed = 1  # How many seconds it takes the enemy to move from one block to another
        self.moveSpeed = self.maxMoveSpeed  # The current movespeed
        self.isActive = 1  # Whether the enemy is alive and moving
        self.index = -1  # The index of the enemy
        self.distanceTravelled = 0

        # Load and place the model
        self.eNode = parent.attachNewNode('enemyBaseNode')
        self.eNode.setPos(startingBlock.getPos())

        self.model = loader.loadModel('models/' + model)
        self.model.reparentTo(self.eNode)

        # Setup the rest of what the enemy needs
        self.setupCollision()
        self.setupHealthBar()

    def move(self, task):
        dist = self.moveSpeed * globalClock.getDt()
        deltaPos = DIRECTION_TO_VECTOR[self.direction] * dist
        self.eNode.setPos(self.eNode.getPos() + deltaPos)

        self.distanceTravelled += dist
        if (self.distanceTravelled >= 1.0):
            self.moveToNextBlock(self.currentBlock)
            self.distanceTravelled = 0
            return task.done

        return task.cont

    # Tells the enemy to start moving along the path
    def moveToEnd(self):
        self.moveToNextBlock(self.startingBlock)

    def moveToNextBlock(self, currentBlock):
        # If we've reached the last block, don't move anymore;
        # otherwise, find the next block in the path and start moving
        if (currentBlock.isType(EndBlock)):
            taskMgr.doMethodLater(self.moveSpeed, self.remove, 'remove')
        else:
            self.currentBlock = self.findNextBlock(currentBlock)

            # Start moving
            taskMgr.add(self.move, 'move' + str(self.index))

    # Locates the next block on the path based upon the enemy's current location
    def findNextBlock(self, currentBlock):
        (row, ignore, col) = currentBlock.index.partition(' ')
        row = int(row)
        col = int(col)
        dir = self.direction
        nextBlock = 0

        if (dir > -1):
            dir = (dir - 1) % 4

            for i in range(4):
                if (dir == 0):
                    nextBlock = self.map[row][col + 1]
                elif (dir == 1):
                    nextBlock = self.map[row - 1][col]
                elif (dir == 2):
                    nextBlock = self.map[row][col - 1]
                else:
                    nextBlock = self.map[row + 1][col]

                if (nextBlock.isType(PathBlock) or nextBlock.isType(EndBlock)):
                    self.direction = dir
                    break

                dir = (dir + 1) % 4
                nextBlock = 0

        return nextBlock

    # Finds the first path block after the start block
    def findFirstPathBlock(self, currentBlock):
        (row, ignore, col) = currentBlock.index.partition(' ')
        row = int(row)
        col = int(col)
        dir = 0

        for dir in range(4):
            if (dir == 0):
                nextBlock = self.map[row][col + 1]
            elif (dir == 1):
                nextBlock = self.map[row - 1][col]
            elif (dir == 2):
                nextBlock = self.map[row][col - 1]
            else:
                nextBlock = self.map[row + 1][col]

            if (nextBlock.isType(PathBlock)):
                self.direction = dir
                break

            nextBlock = 0

        return nextBlock

    # Removes the enemy once it has died or reached the end block
    def remove(self, task=None):
        #self.moveLerp.finish()
        self.isActive = 0
        self.eNode.removeNode()
        self.sphere.removeNode()
        taskMgr.remove('move' + str(self.index))
        messenger.send('enemy_removed', [self])

    # Sets up collision geometry so towers can find the enemy
    def setupCollision(self):
        self.sphere = self.eNode.attachNewNode(CollisionNode('object'))
        self.sphere.node().addSolid(CollisionSphere(0, 0, 0, 0.1))
        self.sphere.node().setFromCollideMask(BitMask32.allOff())
        self.sphere.node().setIntoCollideMask(BitMask32(2))

    def setIndex(self, index):
        self.sphere.setTag('index', str(index))
        self.index = index

    # Creates the health bar above the enemy
    def setupHealthBar(self):
        self.hpBar = DirectWaitBar(text="",
                                   value=100.0,
                                   pos=(0, 0, 1.5),
                                   scale=0.3,
                                   barColor=Vec4(1, 0, 0, 1))
        self.hpBar.setBillboardPointEye()
        self.hpBar.reparentTo(self.eNode)
        #self.hpBar.clearColor()

    # Decreases the health of the enemy by the damage it takes
    def takeDamage(self, damage):
        self.health -= damage
        self.hpBar['value'] = (1.0 * self.health) / self.maxHealth * 100
        if (self.health <= 0):
            self.remove()

    def slow(self, fraction, duration):
        self.moveSpeed = self.maxMoveSpeed * fraction
        self.model.setColor(SLOW_COLOR)

        taskMgr.remove('removeSlow' + str(self.index))
        taskMgr.doMethodLater(duration, self.removeSlow,
                              'removeSlow' + str(self.index))

    def removeSlow(self, task=None):
        self.moveSpeed = self.maxMoveSpeed
        self.model.clearColor()

    def stun(self, duration):
        self.moveSpeed = 0
        self.model.setColor(STUN_COLOR)

        taskMgr.remove('removeStun' + str(self.index))
        taskMgr.doMethodLater(duration, self.removeStun,
                              'removeStun' + str(self.index))

    def removeStun(self, task=None):
        self.moveSpeed = self.maxMoveSpeed
        self.model.clearColor()
Example #13
0
class LoadingScreen():
    def __init__(self):
        self.defaultFont = loader.loadFont("gui/fonts/UbuntuBold.bam")

        # a fill panel so the player doesn't see how everything
        # gets loaded in the background
        self.frameMain = DirectFrame(
            # size of the frame
            frameSize = (base.a2dLeft, base.a2dRight,
                         base.a2dTop, base.a2dBottom),
            # position of the frame
            #pos = (0, 0, 0),
            # tramsparent bg color
            frameColor = (0.05, 0.1, 0.25, 1))

        # the text Loading... on top
        self.lblLoading = DirectLabel(
            scale = 0.25,
            pos = (0, 0, 0.5),
            frameColor = (0, 0, 0, 0),
            text = "Loading...",
            text_align = TextNode.ACenter,
            text_fg = (1,1,1,1),
            text_font = self.defaultFont)
        self.lblLoading.reparentTo(self.frameMain)

        # the waitbar on the bottom
        self.wbLoading = DirectWaitBar(
            text = "0%",
            text_fg = (1,1,1,1),
            text_font = self.defaultFont,
            value = 100,
            pos = (0, 0, -0.5),
            barColor = (0, 0, 1, 1))
        self.wbLoading.reparentTo(self.frameMain)

        self.setText()
        self.hide()

    def show(self):
        # make sure, the frame fill in the whole screen
        self.frameMain["frameSize"] = (
            base.a2dLeft, base.a2dRight,
            base.a2dTop, base.a2dBottom)
        # ensure the texts are translated
        self.setText()
        # now show the main frame
        self.frameMain.show()
        # and render two frames so the loading screen
        # is realy shown on screen
        base.graphicsEngine.renderFrame()
        base.graphicsEngine.renderFrame()

    def hide(self):
        self.frameMain.hide()

    def setLoadingValue(self, value):
        """Set the waitbar value to the given value, where
        value has to be a integer from 0 to 100"""
        if value > 100: value = 100
        if value < 0: value = 0
        self.wbLoading["value"] = value
        self.wbLoading["text"] = "{0}%".format(value)
        base.graphicsEngine.renderFrame()
        base.graphicsEngine.renderFrame()

    def setText(self):
        self.lblLoading["text"] = _("Loading...")