Пример #1
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
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()
Пример #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))
Пример #5
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()