def initIntervals(self):
     self.baseSpinDuration = 1.0
     self.propellerSpinLerp = LerpFunctionInterval(self.propeller.setH, fromData=0.0, toData=360.0, duration=self.baseSpinDuration, name='%s.propellerSpinLerp-%s' % (self.__class__.__name__, self.toon.doId))
     singleBlinkTime = Globals.Gameplay.TargetedWarningSingleBlinkTime
     blinkTime = Globals.Gameplay.TargetedWarningBlinkTime
     self.blinkLoop = Sequence(Wait(singleBlinkTime / 2.0), Func(self.setBackpackTexture, Globals.Gameplay.BackpackStates.Attacked), Wait(singleBlinkTime / 2.0), Func(self.setBackpackTexture, Globals.Gameplay.BackpackStates.Targeted), name='%s.blinkLoop-%s' % (self.__class__.__name__, self.toon.doId))
     self.blinkWarningSeq = Sequence(Func(self.blinkLoop.loop), Wait(blinkTime), Func(self.blinkLoop.clearToInitial), name='%s.blinkWarningSeq-%s' % (self.__class__.__name__, self.toon.doId))
     dur = Globals.Gameplay.BackpackRefuelDuration
     self.refuelSeq = Sequence(Func(self.setPropellerSpinRate, Globals.Gameplay.RefuelPropSpeed), Wait(dur), Func(self.returnBackpackToLastStateFunc), name='%s.refuelSeq-%s' % (self.__class__.__name__, self.toon.doId))
     scale = self.redTapeRing.getScale()
     pulseTime = 1.0
     self.pulseBubbleSeq = Parallel(Sequence(LerpFunctionInterval(self.redTapeRing.setScale, fromData=scale, toData=scale * 1.1, duration=pulseTime / 2.0, blendType='easeInOut'), LerpFunctionInterval(self.redTapeRing.setScale, fromData=scale * 1.1, toData=scale, duration=pulseTime / 2.0, blendType='easeInOut')), LerpHprInterval(self.redTapeRing, pulseTime, Vec3(360, 0, 0), startHpr=Vec3(0, 0, 0)), name='%s.pulseBubbleSeq-%s' % (self.__class__.__name__, self.toon.doId))
     bouncePercent = 1.2
     scaleTime = 0.5
     scaleBounceTime = 0.25
     self.popUpBubbleLerp = LerpScaleInterval(self.redTapeRing, scaleTime, scale * bouncePercent, startScale=0.0, blendType='easeInOut')
     self.popUpBubbleSeq = Sequence(Func(self.updateLerpStartScale, self.popUpBubbleLerp, self.redTapeRing), Func(self.redTapeRing.show), self.popUpBubbleLerp, LerpScaleInterval(self.redTapeRing, scaleBounceTime, scale, startScale=scale * bouncePercent, blendType='easeInOut'), Func(self.pulseBubbleSeq.loop), name='%s.popUpBubbleSeq-%s' % (self.__class__.__name__, self.toon.doId))
     self.removeBubbleLerp = LerpScaleInterval(self.redTapeRing, scaleBounceTime, scale * bouncePercent, startScale=scale, blendType='easeInOut')
     self.removeBubbleSeq = Sequence(Func(self.pulseBubbleSeq.clearToInitial), Func(self.updateLerpStartScale, self.removeBubbleLerp, self.redTapeRing), self.removeBubbleLerp, LerpScaleInterval(self.redTapeRing, scaleTime, 0.0, startScale=scale * bouncePercent, blendType='easeInOut'), Func(self.redTapeRing.hide), name='%s.removeBubbleSeq-%s' % (self.__class__.__name__, self.toon.doId))
     self.redTapeRing.setScale(0.0)
     self.deathInterval = Sequence(Parallel(LerpHprInterval(self.toon, 1.0, Vec3(720, 0, 0)), LerpFunctionInterval(self.toon.setScale, fromData=1.0, toData=0.1, duration=1.0)), Func(self.toon.stash), name='%s.deathInterval-%s' % (self.__class__.__name__, self.toon.doId))
     self.spawnInterval = Sequence(Func(self.toon.stash), Func(self.resetToon), Wait(1.0), Func(self.toon.setAnimState, 'TeleportIn'), Func(self.toon.unstash), name='%s.spawnInterval-%s' % (self.__class__.__name__, self.toon.doId))
     singleBlinkTime = Globals.Gameplay.InvulSingleBlinkTime
     blinkTime = Globals.Gameplay.InvulBlinkTime
     invulBuffTime = Globals.Gameplay.InvulBuffTime
     self.blinkBubbleLoop = Sequence(LerpFunctionInterval(self.redTapeRing.setAlphaScale, fromData=1.0, toData=0.0, duration=singleBlinkTime / 2.0, blendType='easeInOut'), LerpFunctionInterval(self.redTapeRing.setAlphaScale, fromData=0.0, toData=1.0, duration=singleBlinkTime / 2.0, blendType='easeInOut'), name='%s.blinkBubbleLoop-%s' % (self.__class__.__name__, self.toon.doId))
     self.blinkBubbleSeq = Sequence(Wait(invulBuffTime - blinkTime), Func(self.blinkBubbleLoop.loop), Wait(blinkTime), Func(self.blinkBubbleLoop.finish), name='%s.blinkBubbleSeq-%s' % (self.__class__.__name__, self.toon.doId))
Beispiel #2
0
 def loadAttack(self):
     self.pen = loader.loadModel('phase_5/models/props/pen.bam')
     self.pen.reparentTo(self.suit.find('**/joint_Rhold'))
     self.sprayParticle = ParticleLoader.loadParticleEffect('phase_5/etc/penSpill.ptf')
     self.spray = loader.loadModel('phase_3.5/models/props/spray.bam')
     self.spray.setColor(VBase4(0, 0, 0, 1))
     self.splat = Actor('phase_3.5/models/props/splat-mod.bam', {'chan': 'phase_3.5/models/props/splat-chan.bam'})
     self.splat.setColor(VBase4(0, 0, 0, 1))
     self.sprayScaleIval = LerpScaleInterval(self.spray, duration=0.3, scale=(1, 20, 1), startScale=(1, 1, 1))
     sphere = CollisionSphere(0, 0, 0, 0.5)
     sphere.setTangible(0)
     if hasattr(self.suit, 'uniqueName'):
         collName = self.suit.uniqueName('fountainPenCollNode')
     else:
         collName = 'fountainPenCollNode'
     collNode = CollisionNode(collName)
     collNode.addSolid(sphere)
     collNode.setCollideMask(CIGlobals.WallBitmask)
     self.wsnp = self.spray.attachNewNode(collNode)
     self.wsnp.setY(1)
class CogdoFlyingPlayer(FSM):
    notify = DirectNotifyGlobal.directNotify.newCategory('CogdoFlyingPlayer')

    def __init__(self, toon):
        FSM.__init__(self, 'CogdoFlyingPlayer')
        self.toon = toon
        self.toon.reparentTo(render)
        self.legalEaglesTargeting = []
        self.activeBuffs = []
        self.initModels()
        self.initIntervals()
        self.netTimeSentToStartDeath = 0
        self.backpackState = -1
        self.lastBackpackState = -1
        self.lastPropellerSpinRate = Globals.Gameplay.NormalPropSpeed
        self.propellerSpinRate = Globals.Gameplay.NormalPropSpeed
        self.setFuelState(Globals.Gameplay.FuelStates.FuelNoPropeller)
        self.setOldFuelState(self.fuelState)
        CogdoFlyingPlayer.setBlades(self, Globals.Gameplay.FuelStates.FuelNoPropeller)
        self.setBackpackState(Globals.Gameplay.BackpackStates.Normal)

    def initModels(self):
        self.createPropeller()
        self.createRedTapeRing()

    def createPropeller(self):
        self.propellerSmoke = DustCloud.DustCloud(self.toon, wantSound=False)
        self.propellerSmoke.setBillboardPointEye()
        self.propellerSmoke.setBin('fixed', 5002)
        self.backpack = CogdoUtil.loadFlyingModel('propellerPack')
        self.backpack.setScale(1.3)
        self.backpack.setHpr(180.0, 0.0, 0.0)
        self.backpackInstances = []
        self.backpackTextureCard = CogdoUtil.loadFlyingModel('propellerPack_card')
        parts = self.toon.getTorsoParts()
        for part in parts:
            backpackInstance = part.attachNewNode('backpackInstance')
            animal = self.toon.style.getAnimal()
            bodyScale = ToontownGlobals.toonBodyScales[animal]
            backpackHeight = ToontownGlobals.torsoHeightDict[self.toon.style.torso] * bodyScale - 0.5
            backpackInstance.setPos(0.0, -0.325, backpackHeight)
            self.backpackInstances.append(backpackInstance)
            self.backpack.instanceTo(backpackInstance)

        self.propInstances = []
        self.propeller = CogdoUtil.loadFlyingModel('toonPropeller')
        for part in self.backpackInstances:
            propInstance = part.attachNewNode('propInstance')
            propInstance.setPos(0.0, -0.275, 0.0)
            propInstance.setHpr(0.0, 20.0, 0.0)
            propInstance.setScale(1.0, 1.0, 1.25)
            self.propInstances.append(propInstance)
            self.propeller.instanceTo(propInstance)

        self.blades = []
        self.activeBlades = []
        index = 1
        blade = self.propeller.find('**/propeller%d' % index)
        while not blade.isEmpty():
            self.blades.append(blade)
            index += 1
            blade = self.propeller.find('**/propeller%d' % index)

        for blade in self.blades:
            self.activeBlades.append(blade)

    def createRedTapeRing(self):
        self.redTapeRing = CogdoUtil.loadFlyingModel('redTapeRing')
        self.redTapeRing.setTwoSided(True)
        self.redTapeRing.reparentTo(self.toon)
        self.redTapeRing.hide()
        self.redTapeRing.setScale(1.25)
        self.redTapeRing.setZ(self.toon.getHeight() / 2.0)

    def initIntervals(self):
        self.baseSpinDuration = 1.0
        self.propellerSpinLerp = LerpFunctionInterval(self.propeller.setH, fromData=0.0, toData=360.0, duration=self.baseSpinDuration, name='%s.propellerSpinLerp-%s' % (self.__class__.__name__, self.toon.doId))
        singleBlinkTime = Globals.Gameplay.TargetedWarningSingleBlinkTime
        blinkTime = Globals.Gameplay.TargetedWarningBlinkTime
        self.blinkLoop = Sequence(Wait(singleBlinkTime / 2.0), Func(self.setBackpackTexture, Globals.Gameplay.BackpackStates.Attacked), Wait(singleBlinkTime / 2.0), Func(self.setBackpackTexture, Globals.Gameplay.BackpackStates.Targeted), name='%s.blinkLoop-%s' % (self.__class__.__name__, self.toon.doId))
        self.blinkWarningSeq = Sequence(Func(self.blinkLoop.loop), Wait(blinkTime), Func(self.blinkLoop.clearToInitial), name='%s.blinkWarningSeq-%s' % (self.__class__.__name__, self.toon.doId))
        dur = Globals.Gameplay.BackpackRefuelDuration
        self.refuelSeq = Sequence(Func(self.setPropellerSpinRate, Globals.Gameplay.RefuelPropSpeed), Wait(dur), Func(self.returnBackpackToLastStateFunc), name='%s.refuelSeq-%s' % (self.__class__.__name__, self.toon.doId))
        scale = self.redTapeRing.getScale()
        pulseTime = 1.0
        self.pulseBubbleSeq = Parallel(Sequence(LerpFunctionInterval(self.redTapeRing.setScale, fromData=scale, toData=scale * 1.1, duration=pulseTime / 2.0, blendType='easeInOut'), LerpFunctionInterval(self.redTapeRing.setScale, fromData=scale * 1.1, toData=scale, duration=pulseTime / 2.0, blendType='easeInOut')), LerpHprInterval(self.redTapeRing, pulseTime, Vec3(360, 0, 0), startHpr=Vec3(0, 0, 0)), name='%s.pulseBubbleSeq-%s' % (self.__class__.__name__, self.toon.doId))
        bouncePercent = 1.2
        scaleTime = 0.5
        scaleBounceTime = 0.25
        self.popUpBubbleLerp = LerpScaleInterval(self.redTapeRing, scaleTime, scale * bouncePercent, startScale=0.0, blendType='easeInOut')
        self.popUpBubbleSeq = Sequence(Func(self.updateLerpStartScale, self.popUpBubbleLerp, self.redTapeRing), Func(self.redTapeRing.show), self.popUpBubbleLerp, LerpScaleInterval(self.redTapeRing, scaleBounceTime, scale, startScale=scale * bouncePercent, blendType='easeInOut'), Func(self.pulseBubbleSeq.loop), name='%s.popUpBubbleSeq-%s' % (self.__class__.__name__, self.toon.doId))
        self.removeBubbleLerp = LerpScaleInterval(self.redTapeRing, scaleBounceTime, scale * bouncePercent, startScale=scale, blendType='easeInOut')
        self.removeBubbleSeq = Sequence(Func(self.pulseBubbleSeq.clearToInitial), Func(self.updateLerpStartScale, self.removeBubbleLerp, self.redTapeRing), self.removeBubbleLerp, LerpScaleInterval(self.redTapeRing, scaleTime, 0.0, startScale=scale * bouncePercent, blendType='easeInOut'), Func(self.redTapeRing.hide), name='%s.removeBubbleSeq-%s' % (self.__class__.__name__, self.toon.doId))
        self.redTapeRing.setScale(0.0)
        self.deathInterval = Sequence(Parallel(LerpHprInterval(self.toon, 1.0, Vec3(720, 0, 0)), LerpFunctionInterval(self.toon.setScale, fromData=1.0, toData=0.1, duration=1.0)), Func(self.toon.stash), name='%s.deathInterval-%s' % (self.__class__.__name__, self.toon.doId))
        self.spawnInterval = Sequence(Func(self.toon.stash), Func(self.resetToon), Wait(1.0), Func(self.toon.setAnimState, 'TeleportIn'), Func(self.toon.unstash), name='%s.spawnInterval-%s' % (self.__class__.__name__, self.toon.doId))
        singleBlinkTime = Globals.Gameplay.InvulSingleBlinkTime
        blinkTime = Globals.Gameplay.InvulBlinkTime
        invulBuffTime = Globals.Gameplay.InvulBuffTime
        self.blinkBubbleLoop = Sequence(LerpFunctionInterval(self.redTapeRing.setAlphaScale, fromData=1.0, toData=0.0, duration=singleBlinkTime / 2.0, blendType='easeInOut'), LerpFunctionInterval(self.redTapeRing.setAlphaScale, fromData=0.0, toData=1.0, duration=singleBlinkTime / 2.0, blendType='easeInOut'), name='%s.blinkBubbleLoop-%s' % (self.__class__.__name__, self.toon.doId))
        self.blinkBubbleSeq = Sequence(Wait(invulBuffTime - blinkTime), Func(self.blinkBubbleLoop.loop), Wait(blinkTime), Func(self.blinkBubbleLoop.finish), name='%s.blinkBubbleSeq-%s' % (self.__class__.__name__, self.toon.doId))

    def returnBackpackToLastStateFunc(self):
        if self.backpackState == Globals.Gameplay.BackpackStates.Refuel:
            self.returnBackpackToLastState()

    def setPropellerSpinRateFunc(self):
        if self.propellerSpinRate == Globals.Gameplay.RefuelPropSpeed:
            self.setPropellerSpinRate(self.lastPropellerSpinRate)

    def returnBackpackToLastState(self):
        self.setBackpackState(self.lastBackpackState)

    def setBackpackState(self, state):
        if state == self.backpackState:
            return
        self.lastBackpackState = self.backpackState
        self.backpackState = state
        self.blinkWarningSeq.clearToInitial()
        self.refuelSeq.clearToInitial()
        self.blinkLoop.clearToInitial()
        if self.lastBackpackState == Globals.Gameplay.BackpackStates.Refuel:
            self.setPropellerSpinRateFunc()
        if state in Globals.Gameplay.BackpackStates:
            if state == Globals.Gameplay.BackpackStates.Normal:
                pass
            elif state == Globals.Gameplay.BackpackStates.Targeted:
                pass
            elif state == Globals.Gameplay.BackpackStates.Refuel:
                self.refuelSeq.start()
            elif state == Globals.Gameplay.BackpackStates.Attacked:
                self.blinkWarningSeq.start()
            self.setBackpackTexture(state)

    def setBackpackTexture(self, state):
        texName = Globals.Gameplay.BackpackState2TextureName[state]
        tex = self.backpackTextureCard.findTexture(texName)
        self.backpack.setTexture(tex, 1)

    def updateLerpStartScale(self, lerp, nodepath):
        lerp.setStartScale(nodepath.getScale())

    def handleEnterGatherable(self, gatherable, elapsedTime):
        if gatherable.type == Globals.Level.GatherableTypes.InvulPowerup:
            self.blinkBubbleSeq.clearToInitial()
            self.blinkBubbleSeq.start(elapsedTime)
            self.removeBubbleSeq.clearToInitial()
            self.popUpBubbleSeq.start()
            if gatherable.type not in self.activeBuffs:
                self.activeBuffs.append(gatherable.type)
        elif gatherable.type == Globals.Level.GatherableTypes.Propeller:
            self.setBackpackState(Globals.Gameplay.BackpackStates.Refuel)

    def handleDebuffPowerup(self, pickupType, elapsedTime):
        if pickupType == Globals.Level.GatherableTypes.InvulPowerup:
            self.blinkBubbleSeq.finish()
            self.popUpBubbleSeq.clearToInitial()
            self.removeBubbleSeq.start()
            if pickupType in self.activeBuffs:
                self.activeBuffs.remove(pickupType)

    def isBuffActive(self, pickupType):
        if pickupType in self.activeBuffs:
            return True
        return False

    def isInvulnerable(self):
        if Globals.Level.GatherableTypes.InvulPowerup in self.activeBuffs:
            return True
        return False

    def setFuelState(self, fuelState):
        self.fuelState = fuelState

    def setOldFuelState(self, fuelState):
        self.oldFuelState = fuelState

    def hasFuelStateChanged(self):
        if self.fuelState != self.oldFuelState:
            return True
        else:
            return False

    def updatePropellerSmoke(self):
        if not self.hasFuelStateChanged():
            return
        if self.fuelState in [Globals.Gameplay.FuelStates.FuelNoPropeller, Globals.Gameplay.FuelStates.FuelNormal]:
            self.propellerSmoke.stop()
        elif self.fuelState in [Globals.Gameplay.FuelStates.FuelVeryLow, Globals.Gameplay.FuelStates.FuelEmpty]:
            self.propellerSmoke.stop()
            self.propellerSmoke.setScale(0.25)
            self.propellerSmoke.setZ(self.toon.getHeight() + 2.5)
            self.propellerSmoke.loop(rate=48)
        elif self.fuelState in [Globals.Gameplay.FuelStates.FuelLow]:
            self.propellerSmoke.stop()
            self.propellerSmoke.setScale(0.0825)
            self.propellerSmoke.setZ(self.toon.getHeight() + 2.0)
            self.propellerSmoke.loop(rate=24)

    def resetBlades(self):
        self.setBlades(len(self.blades))

    def setAsLegalEagleTarget(self, legalEagle):
        if legalEagle not in self.legalEaglesTargeting:
            self.legalEaglesTargeting.append(legalEagle)

    def removeAsLegalEagleTarget(self, legalEagle):
        if legalEagle in self.legalEaglesTargeting:
            self.legalEaglesTargeting.remove(legalEagle)

    def isLegalEagleTarget(self):
        if len(self.legalEaglesTargeting) > 0:
            return True
        else:
            return False

    def setBlades(self, fuelState):
        if fuelState not in Globals.Gameplay.FuelStates:
            return
        numBlades = fuelState - 1
        if len(self.activeBlades) != numBlades:
            for i in xrange(len(self.activeBlades)):
                blade = self.activeBlades.pop()
                blade.stash()

            if numBlades > len(self.blades):
                numBlades = len(self.blades)
            if numBlades > 0:
                for i in xrange(numBlades):
                    blade = self.blades[i]
                    self.activeBlades.append(blade)
                    blade.unstash()

            if fuelState == Globals.Gameplay.FuelStates.FuelNoPropeller:
                for prop in self.propInstances:
                    prop.hide()

            else:
                for prop in self.propInstances:
                    prop.show()

            self.setFuelState(fuelState)
            self.updatePropellerSmoke()
            self.setOldFuelState(self.fuelState)

    def bladeLost(self):
        if len(self.activeBlades) > 0:
            blade = self.activeBlades.pop()
            blade.stash()
            self.setFuelState(len(self.activeBlades) + 1)
            self.updatePropellerSmoke()
            self.setOldFuelState(self.fuelState)

    def setPropellerSpinRate(self, newRate):
        self.lastPropellerSpinRate = self.propellerSpinRate
        self.propellerSpinRate = newRate
        self.notify.debug('(%s) New propeller speed:%s, old propeller speed:%s' % (self.toon.doId, self.propellerSpinRate, self.lastPropellerSpinRate))
        self.propellerSpinLerp.setPlayRate(newRate)

    def died(self, elapsedTime):
        self.deathInterval.start(elapsedTime)
        self.propellerSmoke.stop()

    def spawn(self, elapsedTime):
        self.spawnInterval.start(elapsedTime)

    def resetToon(self):
        self.toon.setScale(1.0)

    def enable(self):
        self.toon.setAnimState('Happy', 1.0)
        self.toon.setForceJumpIdle(True)
        self.toon.setSpeed(0, 0)
        self.setPropellerSpinRate(Globals.Gameplay.NormalPropSpeed)
        self.propellerSpinLerp.loop()

    def disable(self):
        pass

    def unload(self):
        self.ignoreAll()
        if self.toon:
            self.toon.showName()
        self.backpackTextureCard.removeNode()
        del self.backpackTextureCard
        self.refuelSeq.clearToInitial()
        del self.refuelSeq
        self.pulseBubbleSeq.clearToInitial()
        del self.pulseBubbleSeq
        self.blinkBubbleLoop.clearToInitial()
        del self.blinkBubbleLoop
        self.blinkBubbleSeq.clearToInitial()
        del self.blinkBubbleSeq
        self.popUpBubbleLerp.clearToInitial()
        del self.popUpBubbleLerp
        self.popUpBubbleSeq.clearToInitial()
        del self.popUpBubbleSeq
        self.removeBubbleLerp.clearToInitial()
        del self.removeBubbleLerp
        self.removeBubbleSeq.clearToInitial()
        del self.removeBubbleSeq
        self.propellerSmoke.destroy()
        del self.propellerSmoke
        self.blinkWarningSeq.clearToInitial()
        del self.blinkWarningSeq
        self.blinkLoop.clearToInitial()
        del self.blinkLoop
        self.redTapeRing.removeNode()
        del self.redTapeRing
        self.propellerSpinLerp.clearToInitial()
        del self.propellerSpinLerp
        for prop in self.propInstances:
            prop.removeNode()

        del self.propInstances[:]
        self.propeller.removeNode()
        del self.propeller
        for backpack in self.backpackInstances:
            backpack.removeNode()

        del self.backpackInstances[:]
        self.backpack.removeNode()
        del self.backpack
        del self.activeBuffs[:]
        del self.legalEaglesTargeting[:]
        del self.toon
        self.toon = None
        if self.deathInterval:
            self.deathInterval.clearToInitial()
            self.deathInterval = None
        if self.spawnInterval:
            self.spawnInterval.clearToInitial()
            self.spawnInterval = None
        return

    def start(self):
        swapAvatarShadowPlacer(self.toon, self.toon.uniqueName('toonShadowPlacer'))
        self.toon.startSmooth()

    def exit(self):
        self.toon.setForceJumpIdle(False)
        self.propellerSmoke.reparentTo(hidden)
        self.propellerSmoke.stop()
        if self.toon:
            CogdoFlyingPlayer.resetToon(self)
            self.toon.setActiveShadow(0)
            self.toon.deleteDropShadow()
            self.toon.initializeDropShadow()
            self.toon.setActiveShadow(1)
        else:
            self.notify.warning("There's no toon in offstage, this is bad!")
Beispiel #4
0
    def showResults(self):
        if not self.gameIsEnding:
            self.gameIsEnding = True
            for barrel in self.barrels:
                barrel.wrtReparentTo(render)

            for key in self.cogInfo:
                thief = self.cogInfo[key]['suit']
                thief.suit.setPos(100, 0, 0)
                thief.suit.hide()

            self.__killRewardCountdown()
            self.stopGameWalk()
            numBarrelsSaved = len(self.barrels) - len(self.stolenBarrels)
            resultStr = ''
            if numBarrelsSaved == len(self.barrels):
                resultStr = TTLocalizer.CogThiefPerfect
            elif numBarrelsSaved > 1:
                resultStr = TTLocalizer.CogThiefBarrelsSaved % {
                    'num': numBarrelsSaved
                }
            elif numBarrelsSaved == 1:
                resultStr = TTLocalizer.CogThiefBarrelSaved % {
                    'num': numBarrelsSaved
                }
            else:
                resultStr = TTLocalizer.CogThiefNoBarrelsSaved
            perfectTextSubnode = hidden.attachNewNode(
                self.__genText(resultStr))
            perfectText = hidden.attachNewNode('perfectText')
            perfectTextSubnode.reparentTo(perfectText)
            frame = self.__textGen.getCardActual()
            offsetY = -abs(frame[2] + frame[3]) / 2.0
            perfectTextSubnode.setPos(0, 0, offsetY)
            perfectText.setColor(1, 0.1, 0.1, 1)

            def fadeFunc(t, text=perfectText):
                text.setColorScale(1, 1, 1, t)

            def destroyText(text=perfectText):
                text.removeNode()

            def safeGameOver(self=self):
                if not self.frameworkFSM.isInternalStateInFlux():
                    self.gameOver()

            textTrack = Sequence(
                Func(perfectText.reparentTo, aspect2d),
                Parallel(
                    LerpScaleInterval(perfectText,
                                      duration=0.5,
                                      scale=0.3,
                                      startScale=0.0),
                    LerpFunctionInterval(fadeFunc,
                                         fromData=0.0,
                                         toData=1.0,
                                         duration=0.5)), Wait(2.0),
                Parallel(
                    LerpScaleInterval(perfectText, duration=0.5, scale=1.0),
                    LerpFunctionInterval(fadeFunc,
                                         fromData=1.0,
                                         toData=0.0,
                                         duration=0.5,
                                         blendType='easeIn')),
                Func(destroyText), WaitInterval(0.5), Func(safeGameOver))
            if numBarrelsSaved == len(self.barrels):
                soundTrack = SoundInterval(self.sndPerfect)
            else:
                soundTrack = Sequence()
            self.resultIval = Parallel(textTrack, soundTrack)
            self.resultIval.start()
 def onActivate(self, entity, suit):
     ActivateTrapGag.onActivate(self, entity, suit)
     x, y, z = entity.getPos(render)
     sinkPos = Point3(x, y, z - 9.1)
     dropPos = Point3(x, y, z + 15)
     landPos = Point3(x, y, z)
     suit.d_disableMovement()
     suit.setPos(x, y, z)
     entTrack = Sequence(Wait(0.4), Func(entity.setColor, Vec4(0, 0, 0, 1)), Wait(0.4), LerpScaleInterval(entity, 0.8, GagGlobals.PNT3NEAR0))
     suitTrack = Sequence(
         self.getSplicedLerpAnimsTrack(suit, 'flail', 0.7, 0.25),
         Wait(0.2), 
         LerpPosInterval(suit, 0.4, sinkPos), 
         Func(suit.setPos, dropPos),
         Func(suit.hide),
         ActorInterval(suit, 'neutral', duration=0.5), 
         Wait(0.75), 
         Func(suit.show),
         Parallel(LerpPosInterval(suit, 0.3, landPos), Func(suit.play, 'slip-forward')),
         SoundInterval(self.activateSfx, node = suit), 
         Func(self.damageSuit, suit),
         Func(suit.d_enableMovement) 
     )
     soundTrack = Sequence(SoundInterval(self.hitSfx, node = suit), Wait(0.8))
     Parallel(entTrack, suitTrack, soundTrack).start()
Beispiel #6
0
class CogdoFlyingPlayer(FSM):
    notify = DirectNotifyGlobal.directNotify.newCategory('CogdoFlyingPlayer')

    def __init__(self, toon):
        FSM.__init__(self, 'CogdoFlyingPlayer')
        self.toon = toon
        self.toon.reparentTo(render)
        self.legalEaglesTargeting = []
        self.activeBuffs = []
        self.initModels()
        self.initIntervals()
        self.netTimeSentToStartDeath = 0
        self.backpackState = -1
        self.lastBackpackState = -1
        self.lastPropellerSpinRate = Globals.Gameplay.NormalPropSpeed
        self.propellerSpinRate = Globals.Gameplay.NormalPropSpeed
        self.setFuelState(Globals.Gameplay.FuelStates.FuelNoPropeller)
        self.setOldFuelState(self.fuelState)
        CogdoFlyingPlayer.setBlades(self, Globals.Gameplay.FuelStates.FuelNoPropeller)
        self.setBackpackState(Globals.Gameplay.BackpackStates.Normal)

    def initModels(self):
        self.createPropeller()
        self.createRedTapeRing()

    def createPropeller(self):
        self.propellerSmoke = DustCloud.DustCloud(self.toon, wantSound=False)
        self.propellerSmoke.setBillboardPointEye()
        self.propellerSmoke.setBin('fixed', 5002)
        self.backpack = CogdoUtil.loadFlyingModel('propellerPack')
        self.backpack.setScale(1.3)
        self.backpack.setHpr(180.0, 0.0, 0.0)
        self.backpackInstances = []
        self.backpackTextureCard = CogdoUtil.loadFlyingModel('propellerPack_card')
        parts = self.toon.getTorsoParts()
        for part in parts:
            backpackInstance = part.attachNewNode('backpackInstance')
            animal = self.toon.style.getAnimal()
            bodyScale = ToontownGlobals.toonBodyScales[animal]
            backpackHeight = ToontownGlobals.torsoHeightDict[self.toon.style.torso] * bodyScale - 0.5
            backpackInstance.setPos(0.0, -0.325, backpackHeight)
            self.backpackInstances.append(backpackInstance)
            self.backpack.instanceTo(backpackInstance)

        self.propInstances = []
        self.propeller = CogdoUtil.loadFlyingModel('toonPropeller')
        for part in self.backpackInstances:
            propInstance = part.attachNewNode('propInstance')
            propInstance.setPos(0.0, -0.275, 0.0)
            propInstance.setHpr(0.0, 20.0, 0.0)
            propInstance.setScale(1.0, 1.0, 1.25)
            self.propInstances.append(propInstance)
            self.propeller.instanceTo(propInstance)

        self.blades = []
        self.activeBlades = []
        index = 1
        blade = self.propeller.find('**/propeller%d' % index)
        while not blade.isEmpty():
            self.blades.append(blade)
            index += 1
            blade = self.propeller.find('**/propeller%d' % index)

        for blade in self.blades:
            self.activeBlades.append(blade)

    def createRedTapeRing(self):
        self.redTapeRing = CogdoUtil.loadFlyingModel('redTapeRing')
        self.redTapeRing.setTwoSided(True)
        self.redTapeRing.reparentTo(self.toon)
        self.redTapeRing.hide()
        self.redTapeRing.setScale(1.25)
        self.redTapeRing.setZ(self.toon.getHeight() / 2.0)

    def initIntervals(self):
        self.baseSpinDuration = 1.0
        self.propellerSpinLerp = LerpFunctionInterval(self.propeller.setH, fromData=0.0, toData=360.0, duration=self.baseSpinDuration, name='%s.propellerSpinLerp-%s' % (self.__class__.__name__, self.toon.doId))
        singleBlinkTime = Globals.Gameplay.TargetedWarningSingleBlinkTime
        blinkTime = Globals.Gameplay.TargetedWarningBlinkTime
        self.blinkLoop = Sequence(Wait(singleBlinkTime / 2.0), Func(self.setBackpackTexture, Globals.Gameplay.BackpackStates.Attacked), Wait(singleBlinkTime / 2.0), Func(self.setBackpackTexture, Globals.Gameplay.BackpackStates.Targeted), name='%s.blinkLoop-%s' % (self.__class__.__name__, self.toon.doId))
        self.blinkWarningSeq = Sequence(Func(self.blinkLoop.loop), Wait(blinkTime), Func(self.blinkLoop.clearToInitial), name='%s.blinkWarningSeq-%s' % (self.__class__.__name__, self.toon.doId))
        dur = Globals.Gameplay.BackpackRefuelDuration
        self.refuelSeq = Sequence(Func(self.setPropellerSpinRate, Globals.Gameplay.RefuelPropSpeed), Wait(dur), Func(self.returnBackpackToLastStateFunc), name='%s.refuelSeq-%s' % (self.__class__.__name__, self.toon.doId))
        scale = self.redTapeRing.getScale()
        pulseTime = 1.0
        self.pulseBubbleSeq = Parallel(Sequence(LerpFunctionInterval(self.redTapeRing.setScale, fromData=scale, toData=scale * 1.1, duration=pulseTime / 2.0, blendType='easeInOut'), LerpFunctionInterval(self.redTapeRing.setScale, fromData=scale * 1.1, toData=scale, duration=pulseTime / 2.0, blendType='easeInOut')), LerpHprInterval(self.redTapeRing, pulseTime, Vec3(360, 0, 0), startHpr=Vec3(0, 0, 0)), name='%s.pulseBubbleSeq-%s' % (self.__class__.__name__, self.toon.doId))
        bouncePercent = 1.2
        scaleTime = 0.5
        scaleBounceTime = 0.25
        self.popUpBubbleLerp = LerpScaleInterval(self.redTapeRing, scaleTime, scale * bouncePercent, startScale=0.0, blendType='easeInOut')
        self.popUpBubbleSeq = Sequence(Func(self.updateLerpStartScale, self.popUpBubbleLerp, self.redTapeRing), Func(self.redTapeRing.show), self.popUpBubbleLerp, LerpScaleInterval(self.redTapeRing, scaleBounceTime, scale, startScale=scale * bouncePercent, blendType='easeInOut'), Func(self.pulseBubbleSeq.loop), name='%s.popUpBubbleSeq-%s' % (self.__class__.__name__, self.toon.doId))
        self.removeBubbleLerp = LerpScaleInterval(self.redTapeRing, scaleBounceTime, scale * bouncePercent, startScale=scale, blendType='easeInOut')
        self.removeBubbleSeq = Sequence(Func(self.pulseBubbleSeq.clearToInitial), Func(self.updateLerpStartScale, self.removeBubbleLerp, self.redTapeRing), self.removeBubbleLerp, LerpScaleInterval(self.redTapeRing, scaleTime, 0.0, startScale=scale * bouncePercent, blendType='easeInOut'), Func(self.redTapeRing.hide), name='%s.removeBubbleSeq-%s' % (self.__class__.__name__, self.toon.doId))
        self.redTapeRing.setScale(0.0)
        self.deathInterval = Sequence(Parallel(LerpHprInterval(self.toon, 1.0, Vec3(720, 0, 0)), LerpFunctionInterval(self.toon.setScale, fromData=1.0, toData=0.1, duration=1.0)), Func(self.toon.stash), name='%s.deathInterval-%s' % (self.__class__.__name__, self.toon.doId))
        self.spawnInterval = Sequence(Func(self.toon.stash), Func(self.resetToon), Wait(1.0), Func(self.toon.setAnimState, 'TeleportIn'), Func(self.toon.unstash), name='%s.spawnInterval-%s' % (self.__class__.__name__, self.toon.doId))
        singleBlinkTime = Globals.Gameplay.InvulSingleBlinkTime
        blinkTime = Globals.Gameplay.InvulBlinkTime
        invulBuffTime = Globals.Gameplay.InvulBuffTime
        self.blinkBubbleLoop = Sequence(LerpFunctionInterval(self.redTapeRing.setAlphaScale, fromData=1.0, toData=0.0, duration=singleBlinkTime / 2.0, blendType='easeInOut'), LerpFunctionInterval(self.redTapeRing.setAlphaScale, fromData=0.0, toData=1.0, duration=singleBlinkTime / 2.0, blendType='easeInOut'), name='%s.blinkBubbleLoop-%s' % (self.__class__.__name__, self.toon.doId))
        self.blinkBubbleSeq = Sequence(Wait(invulBuffTime - blinkTime), Func(self.blinkBubbleLoop.loop), Wait(blinkTime), Func(self.blinkBubbleLoop.finish), name='%s.blinkBubbleSeq-%s' % (self.__class__.__name__, self.toon.doId))

    def returnBackpackToLastStateFunc(self):
        if self.backpackState == Globals.Gameplay.BackpackStates.Refuel:
            self.returnBackpackToLastState()

    def setPropellerSpinRateFunc(self):
        if self.propellerSpinRate == Globals.Gameplay.RefuelPropSpeed:
            self.setPropellerSpinRate(self.lastPropellerSpinRate)

    def returnBackpackToLastState(self):
        self.setBackpackState(self.lastBackpackState)

    def setBackpackState(self, state):
        if state == self.backpackState:
            return
        self.lastBackpackState = self.backpackState
        self.backpackState = state
        self.blinkWarningSeq.clearToInitial()
        self.refuelSeq.clearToInitial()
        self.blinkLoop.clearToInitial()
        if self.lastBackpackState == Globals.Gameplay.BackpackStates.Refuel:
            self.setPropellerSpinRateFunc()
        if state in Globals.Gameplay.BackpackStates:
            if state == Globals.Gameplay.BackpackStates.Normal:
                pass
            elif state == Globals.Gameplay.BackpackStates.Targeted:
                pass
            elif state == Globals.Gameplay.BackpackStates.Refuel:
                self.refuelSeq.start()
            elif state == Globals.Gameplay.BackpackStates.Attacked:
                self.blinkWarningSeq.start()
            self.setBackpackTexture(state)

    def setBackpackTexture(self, state):
        texName = Globals.Gameplay.BackpackState2TextureName[state]
        tex = self.backpackTextureCard.findTexture(texName)
        self.backpack.setTexture(tex, 1)

    def updateLerpStartScale(self, lerp, nodepath):
        lerp.setStartScale(nodepath.getScale())

    def handleEnterGatherable(self, gatherable, elapsedTime):
        if gatherable.type == Globals.Level.GatherableTypes.InvulPowerup:
            self.blinkBubbleSeq.clearToInitial()
            self.blinkBubbleSeq.start(elapsedTime)
            self.removeBubbleSeq.clearToInitial()
            self.popUpBubbleSeq.start()
            if gatherable.type not in self.activeBuffs:
                self.activeBuffs.append(gatherable.type)
        elif gatherable.type == Globals.Level.GatherableTypes.Propeller:
            self.setBackpackState(Globals.Gameplay.BackpackStates.Refuel)

    def handleDebuffPowerup(self, pickupType, elapsedTime):
        if pickupType == Globals.Level.GatherableTypes.InvulPowerup:
            self.blinkBubbleSeq.finish()
            self.popUpBubbleSeq.clearToInitial()
            self.removeBubbleSeq.start()
            if pickupType in self.activeBuffs:
                self.activeBuffs.remove(pickupType)

    def isBuffActive(self, pickupType):
        if pickupType in self.activeBuffs:
            return True
        return False

    def isInvulnerable(self):
        if Globals.Level.GatherableTypes.InvulPowerup in self.activeBuffs:
            return True
        return False

    def setFuelState(self, fuelState):
        self.fuelState = fuelState

    def setOldFuelState(self, fuelState):
        self.oldFuelState = fuelState

    def hasFuelStateChanged(self):
        if self.fuelState != self.oldFuelState:
            return True
        else:
            return False

    def updatePropellerSmoke(self):
        if not self.hasFuelStateChanged():
            return
        if self.fuelState in [Globals.Gameplay.FuelStates.FuelNoPropeller, Globals.Gameplay.FuelStates.FuelNormal]:
            self.propellerSmoke.stop()
        elif self.fuelState in [Globals.Gameplay.FuelStates.FuelVeryLow, Globals.Gameplay.FuelStates.FuelEmpty]:
            self.propellerSmoke.stop()
            self.propellerSmoke.setScale(0.25)
            self.propellerSmoke.setZ(self.toon.getHeight() + 2.5)
            self.propellerSmoke.loop(rate=48)
        elif self.fuelState in [Globals.Gameplay.FuelStates.FuelLow]:
            self.propellerSmoke.stop()
            self.propellerSmoke.setScale(0.0825)
            self.propellerSmoke.setZ(self.toon.getHeight() + 2.0)
            self.propellerSmoke.loop(rate=24)

    def resetBlades(self):
        self.setBlades(len(self.blades))

    def setAsLegalEagleTarget(self, legalEagle):
        if legalEagle not in self.legalEaglesTargeting:
            self.legalEaglesTargeting.append(legalEagle)

    def removeAsLegalEagleTarget(self, legalEagle):
        if legalEagle in self.legalEaglesTargeting:
            self.legalEaglesTargeting.remove(legalEagle)

    def isLegalEagleTarget(self):
        if len(self.legalEaglesTargeting) > 0:
            return True
        else:
            return False

    def setBlades(self, fuelState):
        if fuelState not in Globals.Gameplay.FuelStates:
            return
        numBlades = fuelState - 1
        if len(self.activeBlades) != numBlades:
            for i in range(len(self.activeBlades)):
                blade = self.activeBlades.pop()
                blade.stash()

            if numBlades > len(self.blades):
                numBlades = len(self.blades)
            if numBlades > 0:
                for i in range(numBlades):
                    blade = self.blades[i]
                    self.activeBlades.append(blade)
                    blade.unstash()

            if fuelState == Globals.Gameplay.FuelStates.FuelNoPropeller:
                for prop in self.propInstances:
                    prop.hide()

            else:
                for prop in self.propInstances:
                    prop.show()

            self.setFuelState(fuelState)
            self.updatePropellerSmoke()
            self.setOldFuelState(self.fuelState)

    def bladeLost(self):
        if len(self.activeBlades) > 0:
            blade = self.activeBlades.pop()
            blade.stash()
            self.setFuelState(len(self.activeBlades) + 1)
            self.updatePropellerSmoke()
            self.setOldFuelState(self.fuelState)

    def setPropellerSpinRate(self, newRate):
        self.lastPropellerSpinRate = self.propellerSpinRate
        self.propellerSpinRate = newRate
        self.notify.debug('(%s) New propeller speed:%s, old propeller speed:%s' % (self.toon.doId, self.propellerSpinRate, self.lastPropellerSpinRate))
        self.propellerSpinLerp.setPlayRate(newRate)

    def died(self, elapsedTime):
        self.deathInterval.start(elapsedTime)
        self.propellerSmoke.stop()

    def spawn(self, elapsedTime):
        self.spawnInterval.start(elapsedTime)

    def resetToon(self):
        self.toon.setScale(1.0)

    def enable(self):
        self.toon.setAnimState('Happy', 1.0)
        self.toon.setForceJumpIdle(True)
        self.toon.setSpeed(0, 0)
        self.setPropellerSpinRate(Globals.Gameplay.NormalPropSpeed)
        self.propellerSpinLerp.loop()

    def disable(self):
        pass

    def unload(self):
        self.ignoreAll()
        if self.toon:
            self.toon.showName()
        self.backpackTextureCard.removeNode()
        del self.backpackTextureCard
        self.refuelSeq.clearToInitial()
        del self.refuelSeq
        self.pulseBubbleSeq.clearToInitial()
        del self.pulseBubbleSeq
        self.blinkBubbleLoop.clearToInitial()
        del self.blinkBubbleLoop
        self.blinkBubbleSeq.clearToInitial()
        del self.blinkBubbleSeq
        self.popUpBubbleLerp.clearToInitial()
        del self.popUpBubbleLerp
        self.popUpBubbleSeq.clearToInitial()
        del self.popUpBubbleSeq
        self.removeBubbleLerp.clearToInitial()
        del self.removeBubbleLerp
        self.removeBubbleSeq.clearToInitial()
        del self.removeBubbleSeq
        self.propellerSmoke.destroy()
        del self.propellerSmoke
        self.blinkWarningSeq.clearToInitial()
        del self.blinkWarningSeq
        self.blinkLoop.clearToInitial()
        del self.blinkLoop
        self.redTapeRing.removeNode()
        del self.redTapeRing
        self.propellerSpinLerp.clearToInitial()
        del self.propellerSpinLerp
        for prop in self.propInstances:
            prop.removeNode()

        del self.propInstances[:]
        self.propeller.removeNode()
        del self.propeller
        for backpack in self.backpackInstances:
            backpack.removeNode()

        del self.backpackInstances[:]
        self.backpack.removeNode()
        del self.backpack
        del self.activeBuffs[:]
        del self.legalEaglesTargeting[:]
        del self.toon
        self.toon = None
        if self.deathInterval:
            self.deathInterval.clearToInitial()
            self.deathInterval = None
        if self.spawnInterval:
            self.spawnInterval.clearToInitial()
            self.spawnInterval = None
        return

    def start(self):
        swapAvatarShadowPlacer(self.toon, self.toon.uniqueName('toonShadowPlacer'))
        self.toon.startSmooth()

    def exit(self):
        self.toon.setForceJumpIdle(False)
        self.propellerSmoke.reparentTo(hidden)
        self.propellerSmoke.stop()
        if self.toon:
            CogdoFlyingPlayer.resetToon(self)
            self.toon.setActiveShadow(0)
            self.toon.deleteDropShadow()
            self.toon.initializeDropShadow()
            self.toon.setActiveShadow(1)
        else:
            self.notify.warning("There's no toon in offstage, this is bad!")
Beispiel #7
0
 def setHillType(self, type):
     if self.isUp and (self.hillType == MoleFieldBase.HILL_MOLE
                       and type == MoleFieldBase.HILL_BOMB
                       or self.hillType == MoleFieldBase.HILL_BOMB
                       and type == MoleFieldBase.HILL_MOLE):
         return
     self.hillType = type
     self.moleHead.remove()
     if type == MoleFieldBase.HILL_MOLE:
         self.moleHead = loader.loadModel(
             'phase_12/models/bossbotHQ/mole_norm')
         self.moleColNodePath.setScale(3.0)
         self.moleHead.setH(0)
         self.mole.setBillboardAxis(localAvatar, 0)
     if type == MoleFieldBase.HILL_BOMB or type == MoleFieldBase.HILL_COGWHACKED:
         self.moleHead = loader.loadModel(
             'phase_12/models/bossbotHQ/mole_cog')
         self.moleColNodePath.setScale(1.0)
         self.mole.setBillboardAxis(localAvatar, 0)
         if type == MoleFieldBase.HILL_COGWHACKED:
             self.doMoleDown()
             BattleParticles.loadParticles()
             singleGear = BattleParticles.createParticleEffect(
                 'GearExplosion', numParticles=1)
             smallGearExplosion = BattleParticles.createParticleEffect(
                 'GearExplosion', numParticles=10)
             bigGearExplosion = BattleParticles.createParticleEffect(
                 'BigGearExplosion', numParticles=30)
             gears2MTrack = Track((0.0,
                                   ParticleInterval(singleGear,
                                                    self.hill,
                                                    worldRelative=1,
                                                    duration=5.7,
                                                    cleanup=True)),
                                  (0.0,
                                   ParticleInterval(smallGearExplosion,
                                                    self.hill,
                                                    worldRelative=0,
                                                    duration=1.2,
                                                    cleanup=True)),
                                  (0.3,
                                   ParticleInterval(bigGearExplosion,
                                                    self.hill,
                                                    worldRelative=0,
                                                    duration=1.0,
                                                    cleanup=True)),
                                  name='gears2MTrack')
             gears2MTrack.start()
             self.popIval = Sequence(
                 Parallel(
                     Sequence(
                         LerpPosInterval(self.moleHead, 0.05,
                                         Point3(0.28, 0.0, 0.0)),
                         LerpPosInterval(self.moleHead, 0.05,
                                         Point3(0.0, -0.23, 0.0)),
                         LerpPosInterval(self.moleHead, 0.05,
                                         Point3(0.0, 0.0, 0.28)),
                         LerpPosInterval(self.moleHead, 0.05,
                                         Point3(-0.35, 0.0, 0.0)),
                         LerpPosInterval(self.moleHead, 0.05,
                                         Point3(0.0, 0.28, 0.0)),
                         LerpPosInterval(self.moleHead, 0.05,
                                         Point3(0.31, 0.0, 0.0)),
                         LerpPosInterval(self.moleHead, 0.05,
                                         Point3(0.0, -0.32, 0.0)),
                         LerpPosInterval(self.moleHead, 0.05,
                                         Point3(0.0, 0.0, 0.48)),
                         LerpPosInterval(self.moleHead, 0.05,
                                         Point3(-0.28, 0.0, 0.0)),
                         LerpPosInterval(self.moleHead, 0.05,
                                         Point3(0.0, 0.29, 0.0)))),
                 LerpPosInterval(self.mole, 0.5, Point3(0, 0, -2.5)),
                 Func(self.setHillType, MoleFieldBase.HILL_BOMB))
             self.popIval.start()
         else:
             self.moleHead.setH(0)
     if type == MoleFieldBase.HILL_WHACKED:
         self.moleHead = loader.loadModel(
             'phase_12/models/bossbotHQ/mole_hit')
         self.mole.setBillboardAxis(0)
         self.moleColNodePath.setScale(0.0)
         if self.popIval:
             self.popIval.finish()
         if self.downIval:
             self.downIval.finish()
         self.mole.setPos(0.0, 0.0, 0.0)
         self.popIval = Sequence(
             Parallel(
                 Sequence(
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(0.18, 0.0, 0.0)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(0.0, -0.13, 0.0)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(0.0, 0.0, 0.18)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(-0.15, 0.0, 0.0)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(0.0, 0.18, 0.0)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(0.11, 0.0, 0.0)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(0.0, -0.12, 0.0)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(0.0, 0.0, 0.18)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(-0.18, 0.0, 0.0)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(0.0, 0.13, 0.0)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(0.18, 0.0, 0.0)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(0.0, -0.15, 0.0)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(0.0, 0.0, 0.18)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(-0.16, 0.0, 0.0)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(0.0, 0.18, 0.0)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(0.11, 0.0, 0.0)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(0.0, -0.18, 0.0)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(0.0, 0.0, 0.17)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(-0.18, 0.0, 0.0)),
                     LerpPosInterval(self.moleHead, 0.05,
                                     Point3(0.0, 0.0, 0.0))),
                 Sequence(LerpScaleInterval(self.moleHead, 0.5, 3.5),
                          LerpScaleInterval(self.moleHead, 0.5, 1.0))),
             LerpPosInterval(self.mole, 0.5, Point3(0, 0, -2.5)),
             Func(self.setHillType, MoleFieldBase.HILL_MOLE))
         self.popIval.start()
     self.moleHead.reparentTo(self.mole)
    def enterFinalResults(self):
        lerpTrack = Parallel()
        lerpDur = 0.5
        tY = 0.6
        bY = -.05
        lX = -.5
        cX = 0
        rX = 0.5
        scorePanelLocs = (((cX, bY),),
         ((lX, bY), (rX, bY)),
         ((cX, tY), (lX, bY), (rX, bY)),
         ((lX, tY),
          (rX, tY),
          (lX, bY),
          (rX, bY)))
        scorePanelLocs = scorePanelLocs[self.numPlayers - 1]
        for i in xrange(self.numPlayers):
            panel = self.scorePanels[i]
            pos = scorePanelLocs[i]
            panel.wrtReparentTo(aspect2d)
            lerpTrack.append(Parallel(LerpPosInterval(panel, lerpDur, Point3(pos[0], 0, pos[1]), blendType='easeInOut'), LerpScaleInterval(panel, lerpDur, Vec3(panel.getScale()) * 2.0, blendType='easeInOut')))

        self.showScoreTrack = Parallel(lerpTrack, Sequence(Wait(IceGameGlobals.ShowScoresDuration), Func(self.gameOver)))
        self.showScoreTrack.start()
Beispiel #9
0
    def enterScoring(self):
        sortedByDistance = []
        for avId in self.avIdList:
            np = self.getTireNp(avId)
            pos = np.getPos()
            pos.setZ(0)
            sortedByDistance.append((avId, pos.length()))

        def compareDistance(x, y):
            if x[1] - y[1] > 0:
                return 1
            elif x[1] - y[1] < 0:
                return -1
            else:
                return 0

        sortedByDistance.sort(cmp=compareDistance)
        self.scoreMovie = Sequence()
        curScale = 0.01
        curTime = 0
        self.scoreCircle.setScale(0.01)
        self.scoreCircle.show()
        self.notify.debug('newScores = %s' % self.newScores)
        circleStartTime = 0
        for index in xrange(len(sortedByDistance)):
            distance = sortedByDistance[index][1]
            avId = sortedByDistance[index][0]
            scorePanelIndex = self.avIdList.index(avId)
            time = (distance - curScale) / IceGameGlobals.ExpandFeetPerSec
            if time < 0:
                time = 0.01
            scaleXY = distance + IceGameGlobals.TireRadius
            self.notify.debug('circleStartTime = %s' % circleStartTime)
            self.scoreMovie.append(
                Parallel(
                    LerpScaleInterval(self.scoreCircle, time,
                                      Point3(scaleXY, scaleXY, 1.0)),
                    SoundInterval(self.scoreCircleSound,
                                  duration=time,
                                  startTime=circleStartTime)))
            circleStartTime += time
            startScore = self.scorePanels[scorePanelIndex].getScore()
            destScore = self.newScores[scorePanelIndex]
            self.notify.debug('for avId %d, startScore=%d, newScores=%d' %
                              (avId, startScore, destScore))

            def increaseScores(t,
                               scorePanelIndex=scorePanelIndex,
                               startScore=startScore,
                               destScore=destScore):
                oldScore = self.scorePanels[scorePanelIndex].getScore()
                diff = destScore - startScore
                newScore = int(startScore + diff * t)
                if newScore > oldScore:
                    base.playSfx(self.countSound)
                self.scorePanels[scorePanelIndex].setScore(newScore)
                self.scores[scorePanelIndex] = newScore

            duration = (destScore -
                        startScore) * IceGameGlobals.ScoreCountUpRate
            tireNp = self.tireDict[avId]['tireNodePath']
            self.scoreMovie.append(
                Parallel(
                    LerpFunctionInterval(increaseScores, duration),
                    Sequence(
                        LerpColorScaleInterval(tireNp, duration / 6.0,
                                               VBase4(1, 0, 0, 1)),
                        LerpColorScaleInterval(tireNp, duration / 6.0,
                                               VBase4(1, 1, 1, 1)),
                        LerpColorScaleInterval(tireNp, duration / 6.0,
                                               VBase4(1, 0, 0, 1)),
                        LerpColorScaleInterval(tireNp, duration / 6.0,
                                               VBase4(1, 1, 1, 1)),
                        LerpColorScaleInterval(tireNp, duration / 6.0,
                                               VBase4(1, 0, 0, 1)),
                        LerpColorScaleInterval(tireNp, duration / 6.0,
                                               VBase4(1, 1, 1, 1)))))
            curScale += distance

        self.scoreMovie.append(
            Func(self.sendUpdate, 'reportScoringMovieDone', []))
        self.scoreMovie.start()
Beispiel #10
0
    def animToToon(self, timeStamp):
        self.stopTransition()
        if self.mode != 'suit':
            self.setToSuit()
        self.loadAnimToToonSfx()
        suitSoundPlayed = 0
        toonSoundPlayed = 0
        bldgNodes = self.getNodePaths()
        tracks = Parallel()
        for i in bldgNodes:
            name = i.getName()
            if name[0] == 's':
                hideTrack = Sequence(name=self.taskName('ToToonSuitFlatsTrack'))
                landmark = name.find('_landmark_') != -1
                if not suitSoundPlayed:
                    hideTrack.append(Func(base.playSfx, self.cogWeakenSound, 0, 1, None, 0.0))
                hideTrack.append(self.createBounceTrack(i, 3, 1.2, TO_TOON_BLDG_TIME * 0.05, slowInitBounce=0.0))
                hideTrack.append(self.createBounceTrack(i, 5, 0.8, TO_TOON_BLDG_TIME * 0.1, slowInitBounce=0.0))
                hideTrack.append(self.createBounceTrack(i, 7, 1.2, TO_TOON_BLDG_TIME * 0.17, slowInitBounce=0.0))
                hideTrack.append(self.createBounceTrack(i, 9, 1.2, TO_TOON_BLDG_TIME * 0.18, slowInitBounce=0.0))
                realScale = i.getScale()
                hideTrack.append(LerpScaleInterval(i, TO_TOON_BLDG_TIME * 0.1, Vec3(realScale[0], realScale[1], 0.01)))
                if landmark:
                    hideTrack.append(Func(i.removeNode))
                else:
                    hideTrack.append(Func(i.stash))
                    hideTrack.append(Func(i.setScale, Vec3(1)))
                if not suitSoundPlayed:
                    suitSoundPlayed = 1
                tracks.append(hideTrack)
            elif name[0] == 't':
                hideTrack = Sequence(name=self.taskName('ToToonFlatsTrack'))
                hideTrack.append(Wait(TO_TOON_BLDG_TIME * 0.5))
                if not toonSoundPlayed:
                    hideTrack.append(Func(base.playSfx, self.toonGrowSound, 0, 1, None, 0.0))
                hideTrack.append(Func(i.unstash))
                hideTrack.append(Func(i.setScale, Vec3(1, 1, 0.01)))
                if not toonSoundPlayed:
                    hideTrack.append(Func(base.playSfx, self.toonSettleSound, 0, 1, None, 0.0))
                hideTrack.append(self.createBounceTrack(i, 11, 1.2, TO_TOON_BLDG_TIME * 0.5, slowInitBounce=4.0))
                tracks.append(hideTrack)
                if not toonSoundPlayed:
                    toonSoundPlayed = 1

        self.stopTransition()
        bldgMTrack = tracks
        localToonIsVictor = self.localToonIsVictor()
        if localToonIsVictor:
            base.localAvatar.loop('neutral')
            camTrack = self.walkOutCameraTrack()
        victoryRunTrack, delayDeletes = self.getVictoryRunTrack()
        trackName = self.taskName('toToonTrack')
        self._deleteTransitionTrack()
        if localToonIsVictor:
            freedomTrack1 = Func(self.cr.playGame.getPlace().fsm.request, 'walk')
            freedomTrack2 = Func(base.localAvatar.d_setParent, CIGlobals.SPRender)
            self.transitionTrack = Parallel(camTrack, Sequence(victoryRunTrack, bldgMTrack, freedomTrack1, freedomTrack2), name=trackName)
        else:
            self.transitionTrack = Sequence(victoryRunTrack, bldgMTrack, name=trackName)
        self.transitionTrack.delayDeletes = delayDeletes
        if localToonIsVictor:
            self.transitionTrack.start(0)
        else:
            self.transitionTrack.start(timeStamp)
        return
Beispiel #11
0
    def getSprayTrack(self,
                      origin,
                      target,
                      scaleUp,
                      hold,
                      scaleDown,
                      horizScale=1.0,
                      vertScale=1.0):
        if self.sprayJoint.isEmpty():
            self.build()
            self.origin = self.getSprayStartPos()
        base.localAvatar.stop(self.toonAnim)
        self.lastFrame = self.avatar.getCurrentFrame(self.toonAnim)
        track = Sequence()
        sprayProp = loader.loadModel(GagGlobals.SPRAY_MDL)
        sprayProp.setTwoSided(1)
        sprayScale = hidden.attachNewNode('spray-parent')
        sprayRot = hidden.attachNewNode('spray-rotate')
        sprayRot.setColor(GagGlobals.WATER_SPRAY_COLOR)
        sprayRot.setTransparency(1)
        collNode = CollisionNode('Collision')
        spraySphere = CollisionSphere(0, 0, 0, 1)
        spraySphere.setTangible(0)
        collNode.addSolid(spraySphere)
        collNode.setCollideMask(CIGlobals.WallBitmask)
        sprayNP = sprayRot.attachNewNode(collNode)
        sprayNP.setY(1)
        self.sprayNP = sprayNP
        event = CollisionHandlerEvent()
        event.set_in_pattern('%fn-into')
        event.set_out_pattern('%fn-out')
        base.cTrav.add_collider(sprayNP, event)
        self.avatar.acceptOnce(sprayNP.node().getName() + '-into',
                               self.onCollision)

        def showSpray(sprayScale, sprayProp, origin, target):
            objects = [sprayRot, sprayScale, sprayProp]
            for item in objects:
                index = objects.index(item)
                if index == 0:
                    item.reparentTo(self.sprayJoint)
                    item.setPos(0, 0, 0)
                    item.setHpr(self.sprayRotation)
                    item.wrtReparentTo(render)
                else:
                    item.reparentTo(objects[index - 1])

        track.append(Func(showSpray, sprayScale, sprayProp, origin, target))
        self.spray = sprayRot

        def calcTargetScale():
            distance = Vec3(target - origin).length()
            yScale = distance / GagGlobals.SPRAY_LEN
            targetScale = Point3(yScale * horizScale, yScale,
                                 yScale * vertScale)
            return targetScale

        track.append(
            Parallel(
                LerpScaleInterval(sprayScale,
                                  scaleUp,
                                  calcTargetScale,
                                  startScale=GagGlobals.PNT3NEAR0),
                sprayNP.posInterval(
                    0.25,
                    self.spray.getPos(render) + Point3(0, 50, 0),
                    startPos=self.spray.getPos(render) + Point3(0, 5, 0))))
        track.append(Wait(hold))
        track.append(Func(self.handleMiss))
        track.append(LerpScaleInterval(sprayScale, 0.75, GagGlobals.PNT3NEAR0))

        def hideSpray():
            (lambda prop: prop.removeNode(), [sprayProp, sprayRot, sprayScale])

        track.append(Func(hideSpray))
        track.append(Func(self.completeSquirt))
        return track
class DistributedCameraShyGame(DistributedMinigame):
    notify = directNotify.newCategory("DistributedCameraShyGame")

    def __init__(self, cr):
        try:
            self.DistributedCameraShyGame_initialized
            return
        except:
            self.DistributedCameraShyGame_initialized = 1
        DistributedMinigame.__init__(self, cr)
        self.headPanels.delete()
        self.headPanels = CameraShyHeadPanels()
        self.fsm.addState(
            State('countdown', self.enterCountdown, self.exitCountdown,
                  ['play']))
        self.fsm.addState(
            State('announceGameOver', self.enterAnnounceGameOver,
                  self.exitAnnounceGameOver, ['showWinner']))
        self.fsm.addState(
            State('showWinner', self.enterShowWinner, self.exitShowWinner,
                  ['gameOver']))
        self.fsm.getStateNamed('waitForOthers').addTransition('countdown')
        self.fsm.getStateNamed('play').addTransition('announceGameOver')
        self.remoteAvatars = []
        self.myRemoteAvatar = None
        self.thisPlayerWinsLbl = None
        self.olc = None
        self.firstPerson = CameraShyFirstPerson(self)
        self.skyUtil = None
        self.pbpText = None

        self.levelLoader = CameraShyLevelLoader()
        self.spawnPoints = []

    def setLevel(self, level):
        self.levelLoader.setLevel(level)

    def generateOtherPlayerGui(self):
        self.headPanels.generateOtherPlayerGui()

    def updateOtherPlayerHead(self, avId, otherAvId, state):
        self.headPanels.updateOtherPlayerHead(avId, otherAvId, state)

    def getPlayByPlayText(self):
        return OnscreenText(text="",
                            fg=(1, 1, 1, 1),
                            shadow=(0, 0, 0, 1),
                            pos=(0, 0.75))

    def removePlayByPlay(self):
        if self.pbpText:
            taskMgr.remove('DCameraShyGame-removePlayByPlay')
            self.pbpText.destroy()
            self.pbpText = None

    def removePlayByPlayTask(self, task):
        self.removePlayByPlay()
        return Task.done

    def showPlayByPlay(self, situation, avId):
        self.removePlayByPlay()
        av = self.cr.doId2do.get(avId)
        name = av.getName()
        if situation == 0:
            self.pbpText = self.getPlayByPlayText()
            self.pbpText.setText("{0} took a picture of you!".format(name))
        taskMgr.doMethodLater(3.0, self.removePlayByPlayTask,
                              "DCameraShyGame-removePlayByPlay")

    def tookPictureOfMe(self, avId):
        self.headPanels.hideFrames()
        self.firstPerson.stopCameraFlash()
        base.transitions.setFadeColor(1, 1, 1)
        base.transitions.fadeOut(0.1)
        self.showPlayByPlay(0, avId)
        Sequence(Wait(1), Func(self.respawn)).start()

    def respawn(self):
        base.transitions.fadeIn()
        pos, hpr = self.pickSpawnPoint()
        base.localAvatar.setPos(pos)
        base.localAvatar.setHpr(hpr - (180, 0, 0))
        base.localAvatar.d_broadcastPositionNow()
        Sequence(Wait(0.6), Func(self.headPanels.showFrames),
                 Func(base.transitions.setFadeColor, 0, 0, 0)).start()

    def announceGameOver(self):
        self.fsm.request('announceGameOver')

    def showWinner(self, avId):
        base.transitions.fadeOut()
        Sequence(Wait(0.51), Func(self.fsm.request, 'showWinner',
                                  [avId])).start()
        #self.fsm.request('showWinner', [avId])

    def enterGameOver(self, winner, winnerDoId, allPrize):
        try:
            currentCamPos = base.camera.getPos(render)
            currentCamHpr = base.camera.getHpr(render)
            self.firstPerson.reallyEnd()
            base.camera.setPos(currentCamPos)
            base.camera.setHpr(currentCamHpr)
        except:
            pass
        DistributedMinigame.enterGameOver(self, winner, winnerDoId, allPrize)

    def enterShowWinner(self, winnerId):
        self.firstPerson.reallyEnd()
        avatar = self.getRemoteAvatar(winnerId)
        avatar.avatar.loop('neutral')
        avatar.detachCamera()
        self.thisPlayerWinsLbl = OnscreenText(text="{0} Wins!".format(
            avatar.avatar.getName()),
                                              fg=(1, 1, 1, 1),
                                              font=CIGlobals.getMinnieFont(),
                                              pos=(0, 0.8),
                                              scale=0.1)
        if winnerId == base.localAvatar.doId:
            self.thisPlayerWinsLbl.setText("You Win!")
        base.camera.reparentTo(avatar.avatar)
        base.camera.setPos(0, 7, 3)
        base.camera.setH(180)
        base.transitions.fadeIn()
        Sequence(Wait(0.5), Func(avatar.doWinDance)).start()

    def exitShowWinner(self):
        pass

    def enterAnnounceGameOver(self):
        whistle = base.loadSfx("phase_4/audio/sfx/AA_sound_whistle.ogg")
        base.playSfx(whistle)
        self.gameOverLbl = OnscreenText(text='Game Over!',
                                        fg=(1, 1, 1, 1),
                                        font=CIGlobals.getMinnieFont(),
                                        scale=0.1)
        self.gameOverScaleIval = LerpScaleInterval(self.gameOverLbl,
                                                   duration=1.0,
                                                   scale=0.1,
                                                   startScale=0.0,
                                                   blendType='easeOut')
        #self.gameOverScaleIval.start()

    def exitAnnounceGameOver(self):
        self.gameOverScaleIval.finish()
        del self.gameOverScaleIval
        self.gameOverLbl.destroy()
        del self.gameOverLbl

    def remoteAvatarTakePicture(self, avId):
        avatar = self.getRemoteAvatar(avId)
        if avatar:
            avatar.takePicture()

    def createRemoteAvatar(self, avId):
        if avId == base.localAvatar.doId:
            self.myRemoteAvatar = RemoteCameraShyAvatar(self, self.cr, avId)
            self.remoteAvatars.append(self.myRemoteAvatar)
        else:
            av = RemoteCameraShyAvatar(self, self.cr, avId)
            self.remoteAvatars.append(av)

    def getRemoteAvatar(self, avId):
        for avatar in self.remoteAvatars:
            if avatar.avId == avId:
                return avatar

    def allPlayersReady(self):
        self.fsm.request('countdown')

    def enterCountdown(self):
        base.localAvatar.chatInput.disableKeyboardShortcuts()
        base.localAvatar.disableChatInput()
        base.setBackgroundColor(CIGlobals.DefaultBackgroundColor)
        base.render.show()
        self.playMinigameMusic()
        self.countdownLbl = OnscreenText(text="",
                                         fg=(1, 1, 1, 1),
                                         font=CIGlobals.getMinnieFont(),
                                         scale=0.1)
        self.countdownTrack = Sequence(Func(self.countdownLbl.setText, "5"),
                                       Wait(1.0),
                                       Func(self.countdownLbl.setText, "4"),
                                       Wait(1.0),
                                       Func(self.countdownLbl.setText, "3"),
                                       Wait(1.0),
                                       Func(self.countdownLbl.setText, "2"),
                                       Wait(1.0),
                                       Func(self.countdownLbl.setText, "1"),
                                       Wait(1.0), Func(self.fsm.request,
                                                       "play"))
        self.countdownTrack.start()
        self.firstPerson.start()
        self.firstPerson.disableMouse()

    def exitCountdown(self):
        if hasattr(self, 'countdownTrack'):
            self.countdownTrack.pause()
            del self.countdownTrack
        if hasattr(self, 'countdownLbl'):
            self.countdownLbl.destroy()
            del self.countdownLbl

    def enterPlay(self):
        self.createTimer()
        self.firstPerson.reallyStart()

    def exitPlay(self):
        self.firstPerson.end()
        self.firstPerson.enableMouse()
        self.deleteTimer()
        DistributedMinigame.exitPlay(self)

    def createWorld(self):
        self.levelLoader.load()
        self.spawnPoints = self.levelLoader.getSpawnPoints()

    def pickSpawnPoint(self):
        return random.choice(self.spawnPoints)

    def setSpawnPoint(self, index):
        pos, hpr = self.spawnPoints[index]
        base.localAvatar.setPos(pos)
        base.localAvatar.setHpr(hpr)

    def load(self):
        self.createWorld()
        self.setMinigameMusic("phase_6/audio/bgm/GS_Race_SS.ogg")
        self.setDescription("Be the first to take 3 pictures of all the other Toons with your camera. " + \
            "Use WASD to move and the mouse to look around. Press the left mouse button to take a picture. " + \
            "Your camera takes some time to recharge after taking a picture. " + \
            "You know you have a good shot when the view finder is green!")
        self.setWinnerPrize(150)
        self.setLoserPrize(15)
        base.render.hide()
        base.setBackgroundColor(0, 0, 0)
        DistributedMinigame.load(self)

    def announceGenerate(self):
        base.camLens.setMinFov(CIGlobals.GunGameFOV / (4. / 3.))
        self.load()
        DistributedMinigame.announceGenerate(self)

    def disable(self):
        if self.thisPlayerWinsLbl:
            self.thisPlayerWinsLbl.destroy()
            self.thisPlayerWinsLbl = None
        base.camera.reparentTo(render)
        base.camera.setPos(0, 0, 0)
        base.camera.setHpr(0, 0, 0)
        if self.myRemoteAvatar:
            self.myRemoteAvatar.cleanup()
            del self.myRemoteAvatar
        self.firstPerson.cleanup()
        del self.firstPerson
        self.levelLoader.unload()
        self.levelLoader.cleanup()
        del self.levelLoader
        base.camLens.setMinFov(CIGlobals.DefaultCameraFov / (4. / 3.))
        DistributedMinigame.disable(self)
Beispiel #13
0
    def equip(self):
        if not BaseHitscan.equip(self):
            return False

        self.sprayParticleRoot = render.attachNewNode('sprayParticleRoot')
        self.sprayParticleRoot.setLightOff(1)
        self.sprayParticleRoot.hide(CIGlobals.ShadowCameraBitmask)

        if self.isLocal():
            self.released = True
            self.waterBar = WaterBar()
            self.__updateWaterBar()
            self.waterBar.reparentTo(base.a2dLeftCenter)
            self.waterBar.setScale(0.6)
            self.waterBar.setX(0.166)

        self.hydrant = loader.loadModel('phase_5/models/props/battle_hydrant.bam')
        self.model.reparentTo(self.hydrant)
        self.model.pose('chan', 2)
        self.hoseJoint = self.model.controlJoint(None, "modelRoot", "joint_x")

        self.hydrantNode = self.avatar.attachNewNode('hydrantNode')
        self.hydrantNode.clearTransform(self.avatar.getGeomNode().getChild(0))
        self.hydrantNode.setHpr(0, 0, 0)
        self.hydrantScale = self.hydrantNode.attachNewNode('hydrantScale')
        self.hydrant.reparentTo(self.hydrantScale)
        self.avatar.pose('firehose', 30)
        self.avatar.update(0)
        torso = self.avatar.getPart('torso')
        if 'dgm' in self.avatar.getTorso():
            self.hydrant.setPos(torso, 0, 0, -1.85)
        else:
            self.hydrant.setPos(torso, 0, 0, -1.45)
        hbase = self.hydrant.find('**/base')
        hbase.setColor(1, 1, 1, 0.5)
        hbase.setPos(self.avatar, 0, 0, 0)

        self.avatar.loop('neutral')

        tAppearDelay = 0.7
        dAnimHold = 5.1
        dHoseHold = 0.7
        tSprayDelay = 2.8
        track = Parallel()
        toonTrack = Sequence(Wait(tAppearDelay),
                             Func(self.avatar.setForcedTorsoAnim, 'firehose'),
                             self.getAnimationTrack('firehose', endFrame = 30),
                             Func(self.__doBob))
        propTrack = Sequence(Func(self.hydrantNode.reparentTo, self.avatar), LerpScaleInterval(self.hydrantScale, tAppearDelay * 0.5, Point3(1, 1, 1.4),
            startScale=Point3(1, 1, 0.01)), LerpScaleInterval(self.hydrantScale, tAppearDelay * 0.3, Point3(1, 1, 0.8), startScale=Point3(1, 1, 1.4)),
            LerpScaleInterval(self.hydrantScale, tAppearDelay * 0.1, Point3(1, 1, 1.2), startScale=Point3(1, 1, 0.8)),
            LerpScaleInterval(self.hydrantScale, tAppearDelay * 0.1, Point3(1, 1, 1), startScale=Point3(1, 1, 1.2)),
            ActorInterval(self.model, 'chan', endFrame = 30))
        track.append(toonTrack)
        track.append(propTrack)
        self.setAnimTrack(track, startNow = True)

        if self.isFirstPerson():
            self.hydrantNode.hide()

        return True
Beispiel #14
0
 def initIntervals(self):
     self.baseSpinDuration = 1.0
     self.propellerSpinLerp = LerpFunctionInterval(
         self.propeller.setH,
         fromData=0.0,
         toData=360.0,
         duration=self.baseSpinDuration,
         name='%s.propellerSpinLerp-%s' %
         (self.__class__.__name__, self.toon.doId))
     singleBlinkTime = Globals.Gameplay.TargetedWarningSingleBlinkTime
     blinkTime = Globals.Gameplay.TargetedWarningBlinkTime
     self.blinkLoop = Sequence(
         Wait(singleBlinkTime / 2.0),
         Func(self.setBackpackTexture,
              Globals.Gameplay.BackpackStates.Attacked),
         Wait(singleBlinkTime / 2.0),
         Func(self.setBackpackTexture,
              Globals.Gameplay.BackpackStates.Targeted),
         name='%s.blinkLoop-%s' % (self.__class__.__name__, self.toon.doId))
     self.blinkWarningSeq = Sequence(
         Func(self.blinkLoop.loop),
         Wait(blinkTime),
         Func(self.blinkLoop.clearToInitial),
         name='%s.blinkWarningSeq-%s' %
         (self.__class__.__name__, self.toon.doId))
     dur = Globals.Gameplay.BackpackRefuelDuration
     self.refuelSeq = Sequence(
         Func(self.setPropellerSpinRate, Globals.Gameplay.RefuelPropSpeed),
         Wait(dur),
         Func(self.returnBackpackToLastStateFunc),
         name='%s.refuelSeq-%s' % (self.__class__.__name__, self.toon.doId))
     scale = self.redTapeRing.getScale()
     pulseTime = 1.0
     self.pulseBubbleSeq = Parallel(
         Sequence(
             LerpFunctionInterval(self.redTapeRing.setScale,
                                  fromData=scale,
                                  toData=scale * 1.1,
                                  duration=pulseTime / 2.0,
                                  blendType='easeInOut'),
             LerpFunctionInterval(self.redTapeRing.setScale,
                                  fromData=scale * 1.1,
                                  toData=scale,
                                  duration=pulseTime / 2.0,
                                  blendType='easeInOut')),
         LerpHprInterval(self.redTapeRing,
                         pulseTime,
                         Vec3(360, 0, 0),
                         startHpr=Vec3(0, 0, 0)),
         name='%s.pulseBubbleSeq-%s' %
         (self.__class__.__name__, self.toon.doId))
     bouncePercent = 1.2
     scaleTime = 0.5
     scaleBounceTime = 0.25
     self.popUpBubbleLerp = LerpScaleInterval(self.redTapeRing,
                                              scaleTime,
                                              scale * bouncePercent,
                                              startScale=0.0,
                                              blendType='easeInOut')
     self.popUpBubbleSeq = Sequence(
         Func(self.updateLerpStartScale, self.popUpBubbleLerp,
              self.redTapeRing),
         Func(self.redTapeRing.show),
         self.popUpBubbleLerp,
         LerpScaleInterval(self.redTapeRing,
                           scaleBounceTime,
                           scale,
                           startScale=scale * bouncePercent,
                           blendType='easeInOut'),
         Func(self.pulseBubbleSeq.loop),
         name='%s.popUpBubbleSeq-%s' %
         (self.__class__.__name__, self.toon.doId))
     self.removeBubbleLerp = LerpScaleInterval(self.redTapeRing,
                                               scaleBounceTime,
                                               scale * bouncePercent,
                                               startScale=scale,
                                               blendType='easeInOut')
     self.removeBubbleSeq = Sequence(
         Func(self.pulseBubbleSeq.clearToInitial),
         Func(self.updateLerpStartScale, self.removeBubbleLerp,
              self.redTapeRing),
         self.removeBubbleLerp,
         LerpScaleInterval(self.redTapeRing,
                           scaleTime,
                           0.0,
                           startScale=scale * bouncePercent,
                           blendType='easeInOut'),
         Func(self.redTapeRing.hide),
         name='%s.removeBubbleSeq-%s' %
         (self.__class__.__name__, self.toon.doId))
     self.redTapeRing.setScale(0.0)
     self.deathInterval = Sequence(
         Parallel(
             LerpHprInterval(self.toon, 1.0, Vec3(720, 0, 0)),
             LerpFunctionInterval(self.toon.setScale,
                                  fromData=1.0,
                                  toData=0.1,
                                  duration=1.0)),
         Func(self.toon.stash),
         name='%s.deathInterval-%s' %
         (self.__class__.__name__, self.toon.doId))
     self.spawnInterval = Sequence(
         Func(self.toon.stash),
         Func(self.resetToon),
         Wait(1.0),
         Func(self.toon.setAnimState, 'TeleportIn'),
         Func(self.toon.unstash),
         name='%s.spawnInterval-%s' %
         (self.__class__.__name__, self.toon.doId))
     singleBlinkTime = Globals.Gameplay.InvulSingleBlinkTime
     blinkTime = Globals.Gameplay.InvulBlinkTime
     invulBuffTime = Globals.Gameplay.InvulBuffTime
     self.blinkBubbleLoop = Sequence(
         LerpFunctionInterval(self.redTapeRing.setAlphaScale,
                              fromData=1.0,
                              toData=0.0,
                              duration=singleBlinkTime / 2.0,
                              blendType='easeInOut'),
         LerpFunctionInterval(self.redTapeRing.setAlphaScale,
                              fromData=0.0,
                              toData=1.0,
                              duration=singleBlinkTime / 2.0,
                              blendType='easeInOut'),
         name='%s.blinkBubbleLoop-%s' %
         (self.__class__.__name__, self.toon.doId))
     self.blinkBubbleSeq = Sequence(
         Wait(invulBuffTime - blinkTime),
         Func(self.blinkBubbleLoop.loop),
         Wait(blinkTime),
         Func(self.blinkBubbleLoop.finish),
         name='%s.blinkBubbleSeq-%s' %
         (self.__class__.__name__, self.toon.doId))
    def setEveryoneDone(self):
        if not self.hasLocalToon: return
        if self.gameFSM.getCurrentState().getName() != 'play':
            self.notify.warning('ignoring setEveryoneDone msg')
            return

        self.notify.debug('setEveryoneDone')

        def endGame(task, self=self):
            if not PairingGameGlobals.EndlessGame:
                self.gameOver()
            return Task.done

        # hide the timer
        self.timer.hide()

        # hide the bonus
        self.bonusGlow.hide()

        # if it was a perfect game, let the players know
        if len(self.inactiveList) == len(self.cards):
            self.notify.debug("perfect game!")

            perfectTextSubnode = hidden.attachNewNode(
                self.__genText(TTLocalizer.PairingGamePerfect))
            perfectText = hidden.attachNewNode('perfectText')
            perfectTextSubnode.reparentTo(perfectText)
            # offset the subnode so that the text is centered on both axes
            # we need the parent node so that the text will scale correctly
            frame = self.__textGen.getCardActual()
            offsetY = -abs(frame[2] + frame[3]) / 2.
            perfectTextSubnode.setPos(0, 0, offsetY)

            perfectText.setColor(1, .1, .1, 1)

            def fadeFunc(t, text=perfectText):
                text.setColorScale(1, 1, 1, t)

            def destroyText(text=perfectText):
                text.removeNode()

            textTrack = Sequence(
                Func(perfectText.reparentTo, aspect2d),
                Parallel(
                    LerpScaleInterval(perfectText,
                                      duration=.5,
                                      scale=.3,
                                      startScale=0.),
                    LerpFunctionInterval(
                        fadeFunc,
                        fromData=0.,
                        toData=1.,
                        duration=.5,
                    )),
                Wait(2.),
                Parallel(
                    LerpScaleInterval(perfectText, duration=.5, scale=1.),
                    LerpFunctionInterval(fadeFunc,
                                         fromData=1.,
                                         toData=0.,
                                         duration=.5,
                                         blendType="easeIn"),
                ),
                Func(destroyText),
                WaitInterval(.5),
                Func(endGame, None),
            )

            soundTrack = SoundInterval(self.sndPerfect)

            self.perfectIval = Parallel(textTrack, soundTrack)
            self.perfectIval.start()
        else:
            taskMgr.doMethodLater(1, endGame, self.EndGameTaskName)
Beispiel #16
0
 def doSplat(self):
     if self.splatTrack and self.splatTrack.isPlaying():
         self.splatTrack.finish()
     self.splat.reparentTo(render)
     self.splat.setPos(self.object, 0, 0, 3.0)
     self.splat.setY(self.splat.getY() - 1.0)
     self._splatSfxIval.node = self.splat
     self.splatTrack = Parallel(self._splatSfxIval, Sequence(Func(self.splat.showThrough), LerpScaleInterval(self.splat, duration=0.5, scale=6, startScale=1, blendType='easeOut'), Func(self.splat.hide)))
     self.splatTrack.start()
Beispiel #17
0
 def showGrab(self):
     self.nodePath.hide()
     self.collNodePath.hide()
     self.collNode.setIntoCollideMask(BitMask32(0))
     if self.penalty:
         self.track = Parallel(SoundInterval(self.penaltyGrabSound), Sequence(Func(self.kaboom.showThrough), LerpScaleInterval(self.kaboom, duration=0.5, scale=Point3(10, 10, 10), blendType='easeOut'), Func(self.kaboom.hide)))
         self.track.start()
 def showKaboom(self):
     if self.kaboomTrack and self.kaboomTrack.isPlaying():
         self.kaboomTrack.finish()
     self.kaboom.reparentTo(render)
     self.kaboom.setPos(self.suit.getPos())
     self.kaboom.setZ(3)
     self.kaboomTrack = Parallel(SoundInterval(self.kaboomSound, volume=0.5), Sequence(Func(self.kaboom.showThrough), LerpScaleInterval(self.kaboom, duration=0.5, scale=Point3(10, 10, 10), startScale=Point3(1, 1, 1), blendType='easeOut'), Func(self.kaboom.hide)))
     self.kaboomTrack.start()
Beispiel #19
0
class Droppable:
    """An object that can be dropped onto. (Part of the Drag & Drop protocol.)

    Initially droppable is disabled, users must call set_droppable(True) to
    enable it.

    """
    def __init__(self):

        pass        

    def drop(self,event):
        """A draggable has been dropped onto this droppable.
        Subclasses should extend this if they want to do something."""
        
        # Finish any intervals that are playing.
        # FIXME: this tightly couples Droppable to Highlightable. Move this code
        # into highlightable.
        if  hasattr(self,'scaleDownInterval') and self.scaleDownInterval.isPlaying():
            self.scaleDownInterval.finish()
        elif hasattr(self,'scaleUpInterval') and self.scaleUpInterval.isPlaying():
            self.scaleUpInterval.finish()
        # Reset the scale.
        if hasattr(self,'prevScale'):
            self.setScale(self.prevScale)                
        
    def set_droppable(self,b):
        """Enable or disable dropping onto the NodePath."""

        # FIXME: move this into Highlightable.
        # Finish any intervals that are playing.
        if  hasattr(self,'scaleDownInterval') and self.scaleDownInterval.isPlaying():
            self.scaleDownInterval.finish()
        elif hasattr(self,'scaleUpInterval') and self.scaleUpInterval.isPlaying():
            self.scaleUpInterval.finish()
        # Reset the scale.
        if hasattr(self,'prevScale'):
            self.setScale(self.prevScale)
        
        if b is True:
            self.np.setPythonTag('droppable',self)
        else:
            self.np.clearPythonTag('droppable')

    def highlight(self):
        """Subclasses should override this method to implement custom drag-over
        behaviour."""
        
        # If we are already scaling up, do nothing.
        if  hasattr(self,'scaleUpInterval') and self.scaleUpInterval.isPlaying():
            return
        # If we are in the process of scaling down, finish it off immediately.
        if  hasattr(self,'scaleDownInterval') and self.scaleDownInterval.isPlaying():
            self.scaleDownInterval.finish()
  
        from direct.interval.IntervalGlobal import LerpScaleInterval        
        self.prevScale = self.getScale()
        self.scaleUpInterval = LerpScaleInterval(self.np, duration=0.2, scale=self.getScale()*1.2, startScale=self.getScale())
        self.scaleUpInterval.start()
    
    def unhighlight(self):
        """Subclasses should override this method to implement custom drag-over
        behaviour."""
        
        # If we are already scaling down, do nothing.
        if  hasattr(self,'scaleDownInterval') and self.scaleDownInterval.isPlaying():
            return
        # If we are in the process of scaling up, stop.
        if  hasattr(self,'scaleUpInterval') and self.scaleUpInterval.isPlaying():
            self.scaleUpInterval.pause()        
        from direct.interval.IntervalGlobal import LerpScaleInterval
        self.scaleDownInterval = LerpScaleInterval(self.np, duration=0.2, scale=self.prevScale, startScale=self.getScale())
        self.scaleDownInterval.start()
 def showSplat(self):
     if self.kaboomTrack and self.kaboomTrack.isPlaying():
         self.kaboomTrack.finish()
     self.splat.reparentTo(render)
     self.splat.setPos(self.suit.getPos())
     self.splat.setZ(3)
     self.kaboomTrack = Parallel(SoundInterval(self.pieHitSound, volume=1.0), Sequence(Func(self.splat.showThrough), LerpScaleInterval(self.splat, duration=0.5, scale=1.75, startScale=Point3(0.1, 0.1, 0.1), blendType='easeOut'), Func(self.splat.hide)))
     self.kaboomTrack.start()
 def makeToonGrabInterval(self, toon):
     toon.pose('leverNeutral', 0)
     toon.update()
     rightHandPos = toon.rightHand.getPos(toon)
     self.toonPitcherPosition = Point3(self.handPos[0] - rightHandPos[0], self.handPos[1] - rightHandPos[1], 0)
     destZScale = rightHandPos[2] / self.handPos[2]
     grabIval = Sequence(Func(toon.wrtReparentTo, self.waterPitcherNode), Func(toon.loop, 'neutral'), Parallel(ActorInterval(toon, 'jump'), Sequence(Wait(0.43), Parallel(ProjectileInterval(toon, duration=0.9, startPos=toon.getPos(self.waterPitcherNode), endPos=self.toonPitcherPosition), LerpHprInterval(toon, 0.9, Point3(0, 0, 0)), LerpScaleInterval(self.waterPitcherModel, 0.9, Point3(1, 1, destZScale))))), Func(toon.setPos, self.toonPitcherPosition), Func(toon.loop, 'leverNeutral'))
     return grabIval
Beispiel #22
0
    def enterShowScores(self):
        self.notify.debug('enterShowScores')
        lerpTrack = Parallel()
        lerpDur = 0.5
        lerpTrack.append(Parallel(LerpPosInterval(self.goalBar, lerpDur, Point3(0, 0, -.6), blendType='easeInOut'), LerpScaleInterval(self.goalBar, lerpDur, Vec3(self.goalBar.getScale()) * 2.0, blendType='easeInOut')))
        tY = 0.6
        bY = -.05
        lX = -.5
        cX = 0
        rX = 0.5
        scorePanelLocs = (((cX, bY),),
         ((lX, bY), (rX, bY)),
         ((cX, tY), (lX, bY), (rX, bY)),
         ((lX, tY),
          (rX, tY),
          (lX, bY),
          (rX, bY)))
        scorePanelLocs = scorePanelLocs[self.numPlayers - 1]
        for i in xrange(self.numPlayers):
            panel = self.scorePanels[i]
            pos = scorePanelLocs[i]
            panel.wrtReparentTo(aspect2d)
            lerpTrack.append(Parallel(LerpPosInterval(panel, lerpDur, Point3(pos[0], 0, pos[1]), blendType='easeInOut'), LerpScaleInterval(panel, lerpDur, Vec3(panel.getScale()) * 2.0, blendType='easeInOut')))

        self.showScoreTrack = Parallel(lerpTrack, Sequence(Wait(MazeGameGlobals.SHOWSCORES_DURATION), Func(self.gameOver)))
        self.showScoreTrack.start()

        #For the Alpha Blueprint ARG
        if base.config.GetBool('want-blueprint4-ARG', False):
            MinigameGlobals.generateDebugARGPhrase()
Beispiel #23
0
    def getSprayTrack(self,
                      color,
                      origin,
                      target,
                      dScaleUp,
                      dHold,
                      dScaleDown,
                      horizScale=1.0,
                      vertScale=1.0,
                      parent=render):
        track = Sequence()
        SPRAY_LEN = 1.5
        sprayProp = MovieUtil.globalPropPool.getProp('spray')
        sprayScale = hidden.attachNewNode('spray-parent')
        sprayRot = hidden.attachNewNode('spray-rotate')
        spray = sprayRot
        spray.setColor(color)
        if color[3] < 1.0:
            spray.setTransparency(1)

        def showSpray(sprayScale, sprayRot, sprayProp, origin, target, parent):
            if callable(origin):
                origin = origin()
            if callable(target):
                target = target()
            sprayRot.reparentTo(parent)
            sprayRot.clearMat()
            sprayScale.reparentTo(sprayRot)
            sprayScale.clearMat()
            sprayProp.reparentTo(sprayScale)
            sprayProp.clearMat()
            sprayRot.setPos(origin)
            sprayRot.lookAt(Point3(target))

        track.append(
            Func(showSpray, sprayScale, sprayRot, sprayProp, origin, target,
                 parent))

        def calcTargetScale(target=target,
                            origin=origin,
                            horizScale=horizScale,
                            vertScale=vertScale):
            if callable(target):
                target = target()
            if callable(origin):
                origin = origin()
            distance = Vec3(target - origin).length()
            yScale = distance / SPRAY_LEN
            targetScale = Point3(yScale * horizScale, yScale,
                                 yScale * vertScale)
            return targetScale

        track.append(
            LerpScaleInterval(sprayScale,
                              dScaleUp,
                              calcTargetScale,
                              startScale=Point3(0.01, 0.01, 0.01)))
        track.append(Func(self.checkHitObject))
        track.append(Wait(dHold))

        def prepareToShrinkSpray(spray, sprayProp, origin, target):
            if callable(target):
                target = target()
            if callable(origin):
                origin = origin()
            sprayProp.setPos(Point3(0.0, -SPRAY_LEN, 0.0))
            spray.setPos(target)

        track.append(
            Func(prepareToShrinkSpray, spray, sprayProp, origin, target))
        track.append(
            LerpScaleInterval(sprayScale, dScaleDown, Point3(0.01, 0.01,
                                                             0.01)))

        def hideSpray(spray, sprayScale, sprayRot, sprayProp, propPool):
            sprayProp.detachNode()
            MovieUtil.removeProp(sprayProp)
            sprayRot.removeNode()
            sprayScale.removeNode()

        track.append(
            Func(hideSpray, spray, sprayScale, sprayRot, sprayProp,
                 MovieUtil.globalPropPool))
        return track
Beispiel #24
0
    def getDropIval(self):
        shadow = self.shadow
        drop = self.drop
        id = self.id
        hangTime = Globals.ShadowTime
        dropTime = Globals.DropTime
        dropHeight = Globals.DropHeight
        targetShadowScale = 0.5
        targetShadowAlpha = 0.4
        shadowScaleIval = LerpScaleInterval(shadow,
                                            dropTime,
                                            targetShadowScale,
                                            startScale=0)
        shadowAlphaIval = LerpColorScaleInterval(
            shadow,
            hangTime,
            Point4(1, 1, 1, targetShadowAlpha),
            startColorScale=Point4(1, 1, 1, 0))
        shadowIval = Parallel(shadowScaleIval, shadowAlphaIval)
        startPos = Point3(0, 0, dropHeight)
        drop.setPos(startPos)
        dropIval = LerpPosInterval(drop,
                                   dropTime,
                                   Point3(0, 0, 0),
                                   startPos=startPos,
                                   blendType='easeIn')
        dropSoundIval = self._dropSfx
        dropSoundIval.node = self
        self.drop.setTransparency(1)

        def _setRandScale(t):
            self.drop.setScale(self, 1 - random.random() / 16,
                               1 - random.random() / 16,
                               1 - random.random() / 4)

        scaleChange = 0.4 + random.random() / 4
        dropShakeSeq = Sequence(
            LerpScaleInterval(self.drop,
                              0.25,
                              Vec3(1.0 + scaleChange, 1.0 + scaleChange / 2,
                                   1.0 - scaleChange),
                              blendType='easeInOut'),
            LerpScaleInterval(self.drop,
                              0.25,
                              Vec3(1.0, 1.0, 1.0),
                              blendType='easeInOut'),
            Func(self.disableCollisionDamage),
            LerpScaleInterval(self.drop,
                              0.2,
                              Vec3(1.0 + scaleChange / 8,
                                   1.0 + scaleChange / 8,
                                   1.0 - scaleChange / 8),
                              blendType='easeInOut'),
            LerpScaleInterval(self.drop,
                              0.2,
                              Vec3(1.0, 1.0, 1.0),
                              blendType='easeInOut'),
            LerpScaleInterval(self.drop,
                              0.15,
                              Vec3(1.0 + scaleChange / 16,
                                   1.0 + scaleChange / 16,
                                   1.0 - scaleChange / 16),
                              blendType='easeInOut'),
            LerpScaleInterval(self.drop,
                              0.15,
                              Vec3(1.0, 1.0, 1.0),
                              blendType='easeInOut'),
            LerpScaleInterval(self.drop,
                              0.1,
                              Vec3(1.0 + scaleChange / 16,
                                   1.0 + scaleChange / 8,
                                   1.0 - scaleChange / 16),
                              blendType='easeInOut'),
            LerpColorScaleInterval(self.drop, Globals.DropFadeTime,
                                   Vec4(1.0, 1.0, 1.0, 0.0)))
        ival = Sequence(Func(self.reparentTo, render),
                        Parallel(Sequence(WaitInterval(hangTime), dropIval),
                                 shadowIval),
                        Parallel(Func(self.game.dropHit, self, id),
                                 dropSoundIval, dropShakeSeq),
                        Func(self.game.cleanupDrop, id),
                        name='drop%s' % id)
        self.ival = ival
        return ival
Beispiel #25
0
 def getPulseIval(self, node, scale = 1, duration = 0.25):
     return Sequence(LerpScaleInterval(node, duration, scale * 1.1, 0.001, blendType = 'easeOut'), LerpScaleInterval(node, duration / 2.0, scale))
class FountainPenAttack(Attack):
    notify = directNotify.newCategory('FountainPenAttack')
    attack = 'fountainpen'

    def __init__(self, attacksClass, suit):
        Attack.__init__(self, attacksClass, suit)
        self.pen = None
        self.spray = None
        self.splat = None
        self.spraySfx = None
        self.sprayParticle = None
        self.sprayScaleIval = None
        self.wsnp = None
        return

    def loadAttack(self):
        self.pen = loader.loadModel('phase_5/models/props/pen.bam')
        self.pen.reparentTo(self.suit.find('**/joint_Rhold'))
        self.sprayParticle = ParticleLoader.loadParticleEffect('phase_5/etc/penSpill.ptf')
        self.spray = loader.loadModel('phase_3.5/models/props/spray.bam')
        self.spray.setColor(VBase4(0, 0, 0, 1))
        self.splat = Actor('phase_3.5/models/props/splat-mod.bam', {'chan': 'phase_3.5/models/props/splat-chan.bam'})
        self.splat.setColor(VBase4(0, 0, 0, 1))
        self.sprayScaleIval = LerpScaleInterval(self.spray, duration=0.3, scale=(1,
                                                                                 20,
                                                                                 1), startScale=(1,
                                                                                                 1,
                                                                                                 1))
        sphere = CollisionSphere(0, 0, 0, 0.5)
        sphere.setTangible(0)
        if hasattr(self.suit, 'uniqueName'):
            collName = self.suit.uniqueName('fountainPenCollNode')
        else:
            collName = 'fountainPenCollNode'
        collNode = CollisionNode(collName)
        collNode.addSolid(sphere)
        collNode.setCollideMask(CIGlobals.WallBitmask)
        self.wsnp = self.spray.attachNewNode(collNode)
        self.wsnp.setY(1)

    def doAttack(self, ts=0):
        self.loadAttack()
        if hasattr(self.suit, 'uniqueName'):
            name = self.suit.uniqueName('doFountainPenAttack')
        else:
            name = 'doFountainPenAttack'
        self.suitTrack = Parallel(name=name)
        self.suitTrack.append(ActorInterval(self.suit, 'fountainpen'))
        self.suitTrack.append(Sequence(Wait(1.2), Func(self.acceptOnce, 'enter' + self.wsnp.node().getName(), self.handleSprayCollision), Func(self.playWeaponSound), Func(self.attachSpray), Func(self.sprayParticle.start, self.pen.find('**/joint_toSpray'), self.pen.find('**/joint_toSpray')), self.sprayScaleIval, Wait(0.5), Func(self.sprayParticle.cleanup), Func(self.spray.setScale, 1), Func(self.spray.reparentTo, hidden), Func(self.ignore, 'enter' + self.wsnp.node().getName())))
        self.suitTrack.setDoneEvent(self.suitTrack.getName())
        self.acceptOnce(self.suitTrack.getDoneEvent(), self.finishedAttack)
        self.suitTrack.delayDelete = DelayDelete.DelayDelete(self.suit, name)
        self.suitTrack.start(ts)

    def attachSpray(self):
        self.spray.reparentTo(self.pen.find('**/joint_toSpray'))
        pos = self.spray.getPos(render)
        hpr = self.spray.getHpr(render)
        self.spray.reparentTo(render)
        self.spray.setPos(pos)
        self.spray.setHpr(hpr)
        self.spray.setP(0)
        if self.suit.type == 'C':
            self.spray.setH(self.spray.getH() + 7.5)
        self.spray.setTwoSided(True)

    def handleSprayCollision(self, entry):
        if self.suit:
            self.suit.sendUpdate('toonHitByWeapon', [self.getAttackId(self.attack), base.localAvatar.doId])
            base.localAvatar.b_handleSuitAttack(self.getAttackId(self.attack), self.suit.doId)
        self.sprayScaleIval.pause()

    def playWeaponSound(self):
        self.spraySfx = base.audio3d.loadSfx('phase_5/audio/sfx/SA_fountain_pen.ogg')
        base.audio3d.attachSoundToObject(self.spraySfx, self.pen)
        self.spraySfx.play()

    def cleanup(self):
        Attack.cleanup(self)
        if self.wsnp:
            self.wsnp.node().clearSolids()
            self.wsnp.removeNode()
            self.wsnp = None
        if self.pen:
            self.pen.removeNode()
            self.pen = None
        if self.sprayParticle:
            self.sprayParticle.cleanup()
            self.sprayParticle = None
        if self.spray:
            self.spray.removeNode()
            self.spray = None
        if self.splat:
            self.splat.cleanup()
            self.splat = None
        if self.sprayScaleIval:
            self.sprayScaleIval.pause()
            self.sprayScaleIval = None
        self.spraySfx = None
        return
Beispiel #27
0
    def start(self):
        base.transitions.fadeOut(t=0)

        self.setColorScale(Vec4(1, 1, 1, 1))

        if self.fadeTrack is not None:
            self.fadeTrack.finish()
            self.fadeTrack = None

        self.fadeTrack = base.transitions.getFadeInIval(t=2)
        self.fadeTrack.start()

        if self.logoScaleTrack is not None:
            self.logoScaleTrack.finish()
            self.logoScaleTrack = None

        self.logoScaleTrack = Sequence(
            LerpScaleInterval(self.logo,
                              2,
                              Vec3(1.1, 1, 0.55),
                              Vec3(1, 1, 0.5),
                              blendType='easeInOut'),
            LerpScaleInterval(self.logo,
                              2,
                              Vec3(1, 1, 0.5),
                              Vec3(1.1, 1, 0.55),
                              blendType='easeInOut'))

        if self.logoPosTrack is not None:
            self.logoPosTrack.finish()
            self.logoPosTrack = None

        self.logoPosTrack = Sequence(
            LerpPosInterval(self.logo,
                            2,
                            Point3(0, 0, -0.85),
                            Point3(0, 0, -0.7),
                            blendType='easeOut'),
            Func(self.logoScaleTrack.loop))
        self.logoPosTrack.start()

        if self.labelColorScaleTrack is not None:
            self.labelColorScaleTrack.finish()
            self.labelColorScaleTrack = None

        self.labelColorScaleTrack = Sequence(
            LerpColorScaleInterval(self.label, 1, Vec4(1, 1, 1, 0.6),
                                   Vec4(1, 1, 1, 1)),
            LerpColorScaleInterval(self.label, 1, Vec4(1, 1, 1, 1),
                                   Vec4(1, 1, 1, 0.6)))

        if self.labelPosTrack is not None:
            self.labelPosTrack.finish()
            self.labelPosTrack = None

        self.labelPosTrack = Sequence(
            LerpPosInterval(self.label,
                            2,
                            Point3(0, 0, 0.35),
                            Point3(0, 0, 0.15),
                            blendType='easeOut'),
            Func(self.labelColorScaleTrack.loop))
        self.labelPosTrack.start()

        self.acceptOnce('mouse1', self.begin)
Beispiel #28
0
    def __center_view_on_objects(self, transition=True, obj_to_align_to=None, obj_id=None):

        if self._lerp_interval:
            return

        from math import tan, radians

        if obj_to_align_to:

            objs = [obj_to_align_to]

        elif obj_id:

            obj = Mgr.get("object", obj_id)
            objs = [obj]

        else:

            pixel_color = Mgr.get("pixel_under_mouse")
            obj = Mgr.get("object", pixel_color=pixel_color)

            if obj:

                objs = [obj]

            else:

                selection = Mgr.get("selection_top")

                if selection:
                    objs = selection
                else:
                    objs = Mgr.get("objects")

        if not objs:
            return

        obj_root = Mgr.get("object_root")
        cam = self.cam
        bounds_np = cam.origin.attach_new_node("cam_aligned_node")
        tmp_np = bounds_np.attach_new_node("tmp_node")

        if obj_to_align_to:
            bounds_np.set_hpr(obj_to_align_to.get_pivot(), 0., 0., 0.)

        parents = {}
        parent_copies = {}

        bboxes = dict((obj, obj.get_bbox()) for obj in objs if obj.get_type() == "model")

        for bbox in bboxes.values():
            bbox.get_origin().detach_node()

        for obj in objs:

            orig = obj.get_origin()
            parent = orig.get_parent()
            parents[orig] = parent

            if parent in parent_copies:
                parent_copy = parent_copies[parent]
            else:
                parent_copy = NodePath("parent_copy")
                parent_copy.set_transform(parent.get_transform(self.world))
                parent_copy.wrt_reparent_to(tmp_np)
                parent_copies[parent] = parent_copy

            orig.reparent_to(parent_copy)

        bounds = tmp_np.get_tight_bounds()

        for orig, parent in parents.items():
            orig.reparent_to(parent)

        for obj, bbox in bboxes.items():
            bbox.get_origin().reparent_to(obj.get_origin())

        centers = {}

        for obj in objs:

            center = obj.get_center_pos(tmp_np)

            if centers:
                centers["min"].x = min(centers["min"].x, center.x)
                centers["min"].y = min(centers["min"].y, center.y)
                centers["min"].z = min(centers["min"].z, center.z)
                centers["max"].x = max(centers["max"].x, center.x)
                centers["max"].y = max(centers["max"].y, center.y)
                centers["max"].z = max(centers["max"].z, center.z)
            else:
                centers = {"min": center, "max": VBase3(center)}

        if bounds:
            point_min, point_max = bounds
            point_min.x = min(point_min.x, centers["min"].x)
            point_min.y = min(point_min.y, centers["min"].y)
            point_min.z = min(point_min.z, centers["min"].z)
            point_max.x = max(point_max.x, centers["max"].x)
            point_max.y = max(point_max.y, centers["max"].y)
            point_max.z = max(point_max.z, centers["max"].z)
        else:
            point_min, point_max = centers["min"], centers["max"]

        if cam.lens.is_perspective():
            vec = (point_min - point_max) * .5
            center_pos = self.world.get_relative_point(tmp_np, point_max + vec)
        else:
            vec = point_max - point_min
            center_pos = self.world.get_relative_point(tmp_np, point_min + vec * .5)

        bounds_np.remove_node()

        if cam.lens.is_perspective():

            fov_h, fov_v = cam.lens.get_fov()
            x, y, z = vec
            x = min(-.01, x)
            y = min(-.01, y)
            z = min(-.01, z)

            if vec.length_squared() < .000001:
                zoom = None
            else:
                zoom = y + ((x / tan(radians(fov_h * .5))) if x / z > fov_h / fov_v
                    else (z / tan(radians(fov_v * .5))))
                zoom = max(-1000000., min(-cam.lens.get_near(), zoom))

            if transition:
                if zoom is None:
                    interval1 = None
                else:
                    interval1 = LerpPosInterval(cam.origin, .3, Point3(0., zoom, 0.),
                                                blendType="easeInOut")
            else:
                set_zoom = lambda: None if zoom is None else cam.origin.set_y(zoom)

        else:

            size_h, size_v = cam.lens.get_film_size()
            x, y, z = vec
            x = max(.01, x)
            y = max(.01, y)
            z = max(.01, z)

            if vec.length_squared() < .000001:
                zoom = None
            else:
                zoom = (x / size_h) if x / z > size_h / size_v else (z / size_v)
                zoom *= cam.target.get_sx()
                zoom = min(100000., max(.0004, zoom))

            if transition:
                if zoom is None:
                    interval1 = None
                else:
                    interval1 = LerpScaleInterval(cam.target, .3, zoom, blendType="easeInOut")
            else:
                set_zoom = lambda: None if zoom is None else cam.target.set_scale(zoom)

        if transition:

            interval2 = LerpPosInterval(cam.pivot, .3, center_pos, blendType="easeInOut")
            lerp_interval = Parallel(interval2)

            if interval1 is not None:
                lerp_interval.append(interval1)

            if obj_to_align_to:
                quat = obj_to_align_to.get_pivot().get_quat(self.world)
                interval3 = LerpQuatInterval(cam.pivot, .3, quat, blendType="easeInOut")
                interval4 = LerpQuatInterval(cam.target, .3, Quat(), blendType="easeInOut")
                interval5 = LerpQuatInterval(Mgr.get("view_gizmo_root"), .5,
                                             quat, blendType="easeInOut")
                lerp_interval.append(interval3)
                lerp_interval.append(interval4)
                lerp_interval.append(interval5)

            self._lerp_interval = lerp_interval
            lerp_interval.start()
            Mgr.add_task(self.__transition_view, "transition_view", sort=30)
            Mgr.do("start_view_gizmo_transition")
            self._dest_view = "obj_extents"
            self._transition_done = False

        else:

            cam.pivot.set_pos(center_pos)
            set_zoom()
            Mgr.do("update_transf_gizmo")
            Mgr.do("update_coord_sys")
            Mgr.do("update_zoom_indicator")

            if obj_to_align_to:
                Mgr.do("update_view_gizmo", False, True)

            if GlobalData["coord_sys_type"] == "screen":
                Mgr.get("selection").update_transform_values()

        if obj_to_align_to:
            self.is_front_custom = True
            quat = Quat()
            zoom = cam.zoom if zoom is None else zoom
            self.custom_home_default_pos = center_pos
            self.custom_home_default_quat = quat
            self.custom_home_default_zoom = zoom
            self.home_pos = center_pos
            self.home_quat = quat
            self.home_zoom = zoom
 def setSwingInfo(self, power, angle, sequenceNum):
     av = base.cr.doId2do.get(self.avId)
     self.swingInterval = Sequence()
     if av:
         self.stopAdjustClubTask()
         self.swingInterval = Sequence(ActorInterval(av, 'swing-putt', startFrame=0, endFrame=GolfGlobals.BALL_CONTACT_FRAME), Func(self.startBallPlayback, power, angle, sequenceNum), Func(self.ballModel.hide), ActorInterval(av, 'swing-putt', startFrame=GolfGlobals.BALL_CONTACT_FRAME, endFrame=24), Func(self.ballModel.setScale, 0.1), Func(self.ballModel.show), LerpScaleInterval(self.ballModel, 1.0, Point3(1, 1, 1)), Func(self.enableControlKey))
         if av == localAvatar:
             self.swingInterval.append(Func(self.switchToAnimState, 'GolfPuttLoop', True))
     self.swingInterval.start()
Beispiel #30
0
class FountainPenAttack(Attack):
    notify = directNotify.newCategory('FountainPenAttack')
    attack = 'fountainpen'

    def __init__(self, attacksClass, suit):
        Attack.__init__(self, attacksClass, suit)
        self.pen = None
        self.spray = None
        self.splat = None
        self.spraySfx = None
        self.sprayParticle = None
        self.sprayScaleIval = None
        self.wsnp = None
        return

    def loadAttack(self):
        self.pen = loader.loadModel('phase_5/models/props/pen.bam')
        self.pen.reparentTo(self.suit.find('**/joint_Rhold'))
        self.sprayParticle = ParticleLoader.loadParticleEffect('phase_5/etc/penSpill.ptf')
        self.spray = loader.loadModel('phase_3.5/models/props/spray.bam')
        self.spray.setColor(VBase4(0, 0, 0, 1))
        self.splat = Actor('phase_3.5/models/props/splat-mod.bam', {'chan': 'phase_3.5/models/props/splat-chan.bam'})
        self.splat.setColor(VBase4(0, 0, 0, 1))
        self.sprayScaleIval = LerpScaleInterval(self.spray, duration=0.3, scale=(1, 20, 1), startScale=(1, 1, 1))
        sphere = CollisionSphere(0, 0, 0, 0.5)
        sphere.setTangible(0)
        if hasattr(self.suit, 'uniqueName'):
            collName = self.suit.uniqueName('fountainPenCollNode')
        else:
            collName = 'fountainPenCollNode'
        collNode = CollisionNode(collName)
        collNode.addSolid(sphere)
        collNode.setCollideMask(CIGlobals.WallBitmask)
        self.wsnp = self.spray.attachNewNode(collNode)
        self.wsnp.setY(1)

    def doAttack(self, ts = 0):
        self.loadAttack()
        if hasattr(self.suit, 'uniqueName'):
            name = self.suit.uniqueName('doFountainPenAttack')
        else:
            name = 'doFountainPenAttack'
        self.suitTrack = Parallel(name=name)
        self.suitTrack.append(ActorInterval(self.suit, 'fountainpen'))
        self.suitTrack.append(Sequence(Wait(1.2), Func(self.acceptOnce, 'enter' + self.wsnp.node().getName(), self.handleSprayCollision), Func(self.playWeaponSound), Func(self.attachSpray), Func(self.sprayParticle.start, self.pen.find('**/joint_toSpray'), self.pen.find('**/joint_toSpray')), self.sprayScaleIval, Wait(0.5), Func(self.sprayParticle.cleanup), Func(self.spray.setScale, 1), Func(self.spray.reparentTo, hidden), Func(self.ignore, 'enter' + self.wsnp.node().getName())))
        self.suitTrack.setDoneEvent(self.suitTrack.getName())
        self.acceptOnce(self.suitTrack.getDoneEvent(), self.finishedAttack)
        self.suitTrack.delayDelete = DelayDelete.DelayDelete(self.suit, name)
        self.suitTrack.start(ts)

    def attachSpray(self):
        self.spray.reparentTo(self.pen.find('**/joint_toSpray'))
        pos = self.spray.getPos(render)
        hpr = self.spray.getHpr(render)
        self.spray.reparentTo(render)
        self.spray.setPos(pos)
        self.spray.setHpr(hpr)
        self.spray.setP(0)
        if self.suit.type == 'C':
            self.spray.setH(self.spray.getH() + 7.5)
        self.spray.setTwoSided(True)

    def handleSprayCollision(self, entry):
        if self.suit:
            self.suit.sendUpdate('toonHitByWeapon', [self.getAttackId(self.attack), base.localAvatar.doId])
            base.localAvatar.b_handleSuitAttack(self.getAttackId(self.attack), self.suit.doId)
        self.sprayScaleIval.pause()

    def playWeaponSound(self):
        self.spraySfx = base.audio3d.loadSfx('phase_5/audio/sfx/SA_fountain_pen.mp3')
        base.audio3d.attachSoundToObject(self.spraySfx, self.pen)
        self.spraySfx.play()

    def cleanup(self):
        Attack.cleanup(self)
        if self.wsnp:
            self.wsnp.node().clearSolids()
            self.wsnp.removeNode()
            self.wsnp = None
        if self.pen:
            self.pen.removeNode()
            self.pen = None
        if self.sprayParticle:
            self.sprayParticle.cleanup()
            self.sprayParticle = None
        if self.spray:
            self.spray.removeNode()
            self.spray = None
        if self.splat:
            self.splat.cleanup()
            self.splat = None
        if self.sprayScaleIval:
            self.sprayScaleIval.pause()
            self.sprayScaleIval = None
        self.spraySfx = None
        return
Beispiel #31
0
    def getDropIval(self, x, y, dropObjName, generation, num):
        objType = PartyGlobals.Name2DropObjectType[dropObjName]
        id = (generation, num)
        dropNode = hidden.attachNewNode('catchDropNode%s' % (id, ))
        dropNode.setPos(x, y, 0)
        shadow = self.dropShadow.copyTo(dropNode)
        shadow.setZ(PartyGlobals.CatchDropShadowHeight)
        shadow.setColor(1, 1, 1, 1)
        object = self.getObjModel(dropObjName)
        object.reparentTo(hidden)
        if dropObjName in ['watermelon', 'anvil']:
            objH = object.getH()
            absDelta = {'watermelon': 12, 'anvil': 15}[dropObjName]
            delta = (self.randomNumGen.random() * 2.0 - 1.0) * absDelta
            newH = objH + delta
        else:
            newH = self.randomNumGen.random() * 360.0
        object.setH(newH)
        sphereName = 'FallObj%s' % (id, )
        radius = self.ObjRadius
        if objType.good:
            radius *= lerp(1.0, 1.3, 0.5)
        collSphere = CollisionSphere(0, 0, 0, radius)
        collSphere.setTangible(0)
        collNode = CollisionNode(sphereName)
        collNode.setCollideMask(PartyGlobals.CatchActivityBitmask)
        collNode.addSolid(collSphere)
        collNodePath = object.attachNewNode(collNode)
        collNodePath.hide()
        if self.ShowObjSpheres:
            collNodePath.show()
        catchEventName = 'ltCatch' + sphereName

        def eatCollEntry(forward, collEntry):
            forward()

        self.accept(
            catchEventName,
            Functor(eatCollEntry, Functor(self.__handleCatch, id[0], id[1])))

        def cleanup(self=self, dropNode=dropNode, id=id, event=catchEventName):
            self.ignore(event)
            dropNode.removeNode()

        duration = objType.fallDuration
        onscreenDuration = objType.onscreenDuration
        targetShadowScale = 0.3
        if self.trickShadows:
            intermedScale = targetShadowScale * (self.OffscreenTime /
                                                 self.BaselineDropDuration)
            shadowScaleIval = Sequence(
                LerpScaleInterval(shadow,
                                  self.OffscreenTime,
                                  intermedScale,
                                  startScale=0))
            shadowScaleIval.append(
                LerpScaleInterval(shadow,
                                  duration - self.OffscreenTime,
                                  targetShadowScale,
                                  startScale=intermedScale))
        else:
            shadowScaleIval = LerpScaleInterval(shadow,
                                                duration,
                                                targetShadowScale,
                                                startScale=0)
        targetShadowAlpha = 0.4
        shadowAlphaIval = LerpColorScaleInterval(
            shadow,
            self.OffscreenTime,
            Point4(1, 1, 1, targetShadowAlpha),
            startColorScale=Point4(1, 1, 1, 0))
        shadowIval = Parallel(shadowScaleIval, shadowAlphaIval)
        if self.useGravity:

            def setObjPos(t, objType=objType, object=object):
                z = objType.trajectory.calcZ(t)
                object.setZ(z)

            setObjPos(0)
            dropIval = LerpFunctionInterval(setObjPos,
                                            fromData=0,
                                            toData=onscreenDuration,
                                            duration=onscreenDuration)
        else:
            startPos = Point3(0, 0, self.MinOffscreenHeight)
            object.setPos(startPos)
            dropIval = LerpPosInterval(object,
                                       onscreenDuration,
                                       Point3(0, 0, 0),
                                       startPos=startPos,
                                       blendType='easeIn')
        ival = Sequence(Func(Functor(dropNode.reparentTo, self.root)),
                        Parallel(
                            Sequence(
                                WaitInterval(self.OffscreenTime),
                                Func(Functor(object.reparentTo, dropNode)),
                                dropIval), shadowIval),
                        Func(cleanup),
                        name='drop%s' % (id, ))
        if objType == PartyGlobals.Name2DropObjectType['anvil']:
            ival.append(Func(self.playAnvil))
        return ival
 def enterAnnounceGameOver(self):
     whistle = base.loadSfx('phase_4/audio/sfx/AA_sound_whistle.mp3')
     base.playSfx(whistle)
     self.gameOverLbl = OnscreenText(text='Game Over!', fg=(1, 1, 1, 1), font=CIGlobals.getMinnieFont(), scale=0.1)
     self.gameOverScaleIval = LerpScaleInterval(self.gameOverLbl, duration=1.0, scale=0.1, startScale=0.0, blendType='easeOut')
    def enterShowScores(self):
        self.notify.debug('enterShowScores')
        lerpTrack = Parallel()
        lerpDur = 0.5
        lerpTrack.append(Parallel(LerpPosInterval(self.goalBar, lerpDur, Point3(0, 0, -.6), blendType='easeInOut'), LerpScaleInterval(self.goalBar, lerpDur, Vec3(self.goalBar.getScale()) * 2.0, blendType='easeInOut')))
        tY = 0.6
        bY = -.05
        lX = -.5
        cX = 0
        rX = 0.5
        scorePanelLocs = (((cX, bY),),
         ((lX, bY), (rX, bY)),
         ((cX, tY), (lX, bY), (rX, bY)),
         ((lX, tY),
          (rX, tY),
          (lX, bY),
          (rX, bY)))
        scorePanelLocs = scorePanelLocs[self.numPlayers - 1]
        for i in xrange(self.numPlayers):
            panel = self.scorePanels[i]
            pos = scorePanelLocs[i]
            lerpTrack.append(Parallel(LerpPosInterval(panel, lerpDur, Point3(pos[0], 0, pos[1]), blendType='easeInOut'), LerpScaleInterval(panel, lerpDur, Vec3(panel.getScale()) * 2.0, blendType='easeInOut')))

        self.showScoreTrack = Parallel(lerpTrack, Sequence(Wait(MazeGameGlobals.SHOWSCORES_DURATION), Func(self.gameOver)))
        self.showScoreTrack.start()
class DistributedCameraShyGame(DistributedMinigame):
    notify = directNotify.newCategory('DistributedCameraShyGame')

    def __init__(self, cr):
        try:
            self.DistributedCameraShyGame_initialized
            return
        except:
            self.DistributedCameraShyGame_initialized = 1

        DistributedMinigame.__init__(self, cr)
        self.headPanels.delete()
        self.headPanels = CameraShyHeadPanels()
        self.fsm.addState(State('countdown', self.enterCountdown, self.exitCountdown, ['play']))
        self.fsm.addState(State('announceGameOver', self.enterAnnounceGameOver, self.exitAnnounceGameOver, ['showWinner']))
        self.fsm.addState(State('showWinner', self.enterShowWinner, self.exitShowWinner, ['gameOver']))
        self.fsm.getStateNamed('waitForOthers').addTransition('countdown')
        self.fsm.getStateNamed('play').addTransition('announceGameOver')
        self.maze = None
        self.mazeCollModel = None
        self.spawnPoints = []
        self.remoteAvatars = []
        self.myRemoteAvatar = None
        self.thisPlayerWinsLbl = None
        self.sky = None
        self.firstPerson = CameraShyFirstPerson(self)
        self.skyUtil = None
        self.pbpText = None
        return

    def generateOtherPlayerGui(self):
        self.headPanels.generateOtherPlayerGui()

    def updateOtherPlayerHead(self, avId, otherAvId, state):
        self.headPanels.updateOtherPlayerHead(avId, otherAvId, state)

    def getPlayByPlayText(self):
        return OnscreenText(text='', fg=(1, 1, 1, 1), shadow=(0, 0, 0, 1), pos=(0, 0.75))

    def removePlayByPlay(self):
        if self.pbpText:
            taskMgr.remove('DCameraShyGame-removePlayByPlay')
            self.pbpText.destroy()
            self.pbpText = None
        return

    def removePlayByPlayTask(self, task):
        self.removePlayByPlay()
        return Task.done

    def showPlayByPlay(self, situation, avId):
        self.removePlayByPlay()
        av = self.cr.doId2do.get(avId)
        name = av.getName()
        if situation == 0:
            self.pbpText = self.getPlayByPlayText()
            self.pbpText.setText('{0} took a picture of you!'.format(name))
        taskMgr.doMethodLater(3.0, self.removePlayByPlayTask, 'DCameraShyGame-removePlayByPlay')

    def tookPictureOfMe(self, avId):
        self.headPanels.hideFrames()
        self.firstPerson.stopCameraFlash()
        base.transitions.setFadeColor(1, 1, 1)
        base.transitions.fadeOut(0.1)
        self.showPlayByPlay(0, avId)
        Sequence(Wait(1), Func(self.respawn)).start()

    def respawn(self):
        base.transitions.fadeIn()
        pos, hpr = self.pickSpawnPoint()
        base.localAvatar.setPos(pos)
        base.localAvatar.setHpr(hpr - (180, 0, 0))
        base.localAvatar.d_broadcastPositionNow()
        Sequence(Wait(0.6), Func(self.headPanels.showFrames), Func(base.transitions.setFadeColor, 0, 0, 0)).start()

    def announceGameOver(self):
        self.fsm.request('announceGameOver')

    def showWinner(self, avId):
        base.transitions.fadeOut()
        Sequence(Wait(0.51), Func(self.fsm.request, 'showWinner', [avId])).start()

    def enterGameOver(self, winner, winnerDoId, allPrize):
        try:
            currentCamPos = base.camera.getPos(render)
            currentCamHpr = base.camera.getHpr(render)
            self.firstPerson.reallyEnd()
            base.camera.setPos(currentCamPos)
            base.camera.setHpr(currentCamHpr)
        except:
            pass

        DistributedMinigame.enterGameOver(self, winner, winnerDoId, allPrize)

    def enterShowWinner(self, winnerId):
        self.firstPerson.reallyEnd()
        avatar = self.getRemoteAvatar(winnerId)
        avatar.avatar.loop('neutral')
        avatar.detachCamera()
        self.thisPlayerWinsLbl = OnscreenText(text='{0} Wins!'.format(avatar.avatar.getName()), fg=(1, 1, 1, 1), font=CIGlobals.getMinnieFont(), pos=(0, 0.8), scale=0.1)
        if winnerId == base.localAvatar.doId:
            self.thisPlayerWinsLbl.setText('You Win!')
        base.camera.reparentTo(avatar.avatar)
        base.camera.setPos(0, 7, 3)
        base.camera.setH(180)
        base.transitions.fadeIn()
        Sequence(Wait(0.5), Func(avatar.doWinDance)).start()

    def exitShowWinner(self):
        pass

    def enterAnnounceGameOver(self):
        whistle = base.loadSfx('phase_4/audio/sfx/AA_sound_whistle.mp3')
        base.playSfx(whistle)
        self.gameOverLbl = OnscreenText(text='Game Over!', fg=(1, 1, 1, 1), font=CIGlobals.getMinnieFont(), scale=0.1)
        self.gameOverScaleIval = LerpScaleInterval(self.gameOverLbl, duration=1.0, scale=0.1, startScale=0.0, blendType='easeOut')

    def exitAnnounceGameOver(self):
        self.gameOverScaleIval.finish()
        del self.gameOverScaleIval
        self.gameOverLbl.destroy()
        del self.gameOverLbl

    def remoteAvatarTakePicture(self, avId):
        avatar = self.getRemoteAvatar(avId)
        if avatar:
            avatar.takePicture()

    def standingAvatar(self, avId):
        avatar = self.getRemoteAvatar(avId)
        if avatar:
            avatar.stand()

    def runningAvatar(self, avId):
        avatar = self.getRemoteAvatar(avId)
        if avatar:
            avatar.run()

    def createRemoteAvatar(self, avId):
        if avId == base.localAvatar.doId:
            self.myRemoteAvatar = RemoteCameraShyAvatar(self, self.cr, avId)
            self.remoteAvatars.append(self.myRemoteAvatar)
        else:
            av = RemoteCameraShyAvatar(self, self.cr, avId)
            av.stand()
            self.remoteAvatars.append(av)

    def getRemoteAvatar(self, avId):
        for avatar in self.remoteAvatars:
            if avatar.avId == avId:
                return avatar

    def allPlayersReady(self):
        self.fsm.request('countdown')

    def enterCountdown(self):
        base.localAvatar.chatInput.disableKeyboardShortcuts()
        base.localAvatar.disableChatInput()
        base.setBackgroundColor(CIGlobals.DefaultBackgroundColor)
        base.render.show()
        self.playMinigameMusic()
        self.countdownLbl = OnscreenText(text='', fg=(1, 1, 1, 1), font=CIGlobals.getMinnieFont(), scale=0.1)
        self.countdownTrack = Sequence(Func(self.countdownLbl.setText, '5'), Wait(1.0), Func(self.countdownLbl.setText, '4'), Wait(1.0), Func(self.countdownLbl.setText, '3'), Wait(1.0), Func(self.countdownLbl.setText, '2'), Wait(1.0), Func(self.countdownLbl.setText, '1'), Wait(1.0), Func(self.fsm.request, 'play'))
        self.countdownTrack.start()
        self.firstPerson.start()
        self.firstPerson.disableMouse()

    def exitCountdown(self):
        if hasattr(self, 'countdownTrack'):
            self.countdownTrack.pause()
            del self.countdownTrack
        if hasattr(self, 'countdownLbl'):
            self.countdownLbl.destroy()
            del self.countdownLbl

    def enterPlay(self):
        self.createTimer()
        self.firstPerson.reallyStart()

    def exitPlay(self):
        self.firstPerson.end()
        self.firstPerson.enableMouse()
        self.deleteTimer()
        base.localAvatar.createChatInput()
        base.localAvatar.chatInput.enableKeyboardShortcuts()
        DistributedMinigame.exitPlay(self)

    def createWorld(self):
        self.deleteWorld()
        self.maze = loader.loadModel('phase_4/models/minigames/maze_1player.bam')
        self.maze.find('**/maze_walls').setSz(1.5)
        self.maze.reparentTo(base.render)
        self.mazeCollModel = loader.loadModel('phase_4/models/minigames/maze_1player_collisions.egg')
        self.mazeCollModel.reparentTo(base.render)
        self.mazeCollModel.hide()
        self.mazeCollModel.setTransparency(1)
        self.mazeCollModel.setColorScale(1, 1, 1, 0)
        for node in self.mazeCollModel.findAllMatches('**'):
            node.setSz(1.5)

        self.sky = loader.loadModel('phase_3.5/models/props/TT_sky.bam')
        self.skyUtil = SkyUtil()
        self.skyUtil.startSky(self.sky)
        self.sky.reparentTo(base.camera)
        ce = CompassEffect.make(NodePath(), CompassEffect.PRot | CompassEffect.PZ)
        self.sky.node().setEffect(ce)
        self.spawnPoints.append((Point3(0, 0, 0), Vec3(0, 0, 0)))
        self.spawnPoints.append((Point3(-23.89, 18.58, 0.0), Vec3(90.0, 0.0, 0.0)))
        self.spawnPoints.append((Point3(-23.89, 6.3, 0.0), Vec3(0.0, 0.0, 0.0)))
        self.spawnPoints.append((Point3(23.78, 6.3, 0.0), Vec3(0.0, 0.0, 0.0)))
        self.spawnPoints.append((Point3(8.12, -17.79, 0.0), Vec3(270.0, 0.0, 0.0)))

    def deleteWorld(self):
        if self.maze:
            self.maze.removeNode()
            self.maze = None
        if self.mazeCollModel:
            self.mazeCollModel.removeNode()
            self.mazeCollModel = None
        if self.skyUtil:
            self.skyUtil.stopSky()
            self.skyUtil = None
        if self.sky:
            self.sky.removeNode()
            self.sky = None
        return

    def pickSpawnPoint(self):
        return random.choice(self.spawnPoints)

    def setSpawnPoint(self, index):
        pos, hpr = self.spawnPoints[index]
        base.localAvatar.setPos(pos)
        base.localAvatar.setHpr(hpr)

    def load(self):
        self.createWorld()
        self.setMinigameMusic('phase_6/audio/bgm/GS_Race_SS.mid')
        self.setDescription('Be the first to take 3 pictures of all the other Toons with your camera. ' + 'Use WASD to move and the mouse to look around. Press the left mouse button to take a picture. ' + 'Your camera takes some time to recharge after taking a picture. ' + 'You know you have a good shot when the view finder is green!')
        self.setWinnerPrize(30)
        self.setLoserPrize(15)
        base.render.hide()
        base.setBackgroundColor(0, 0, 0)
        DistributedMinigame.load(self)

    def announceGenerate(self):
        base.camLens.setMinFov(CIGlobals.GunGameFOV / (4.0 / 3.0))
        self.load()
        DistributedMinigame.announceGenerate(self)

    def disable(self):
        if self.thisPlayerWinsLbl:
            self.thisPlayerWinsLbl.destroy()
            self.thisPlayerWinsLbl = None
        base.camera.reparentTo(render)
        base.camera.setPos(0, 0, 0)
        base.camera.setHpr(0, 0, 0)
        if self.myRemoteAvatar:
            self.myRemoteAvatar.cleanup()
            del self.myRemoteAvatar
        self.firstPerson.cleanup()
        del self.firstPerson
        self.deleteWorld()
        base.camLens.setMinFov(CIGlobals.DefaultCameraFov / (4.0 / 3.0))
        DistributedMinigame.disable(self)
        return
Beispiel #35
0
class Highlightable:   
    """A mixin class that receives notifications from zcanvas when the mouse
    pointer enters or leaves its nodepath. These events can be used to highlight
    a nodepath as the mouse cursor moves over it. The default implementation
    scales the nodepath to 120% of its original size over a 0.2 second interval
    when the mouse enters the nodepath, and scales it back over the same amount
    of time when the mouse leaves."""

    def __init__(self):
            
        pass

    def highlight(self):
        """The mouse pointer has entered the bounds of this nodepath. Subclasses
        should override this method to implement custom mouse-over behaviour.
        
        """        
        # If we are already scaling up, do nothing.
        if  hasattr(self,'scaleUpInterval') and self.scaleUpInterval.isPlaying():
            return

        # If we are in the process of scaling down, finish it off immediately.
        if  hasattr(self,'scaleDownInterval') and self.scaleDownInterval.isPlaying():
            self.scaleDownInterval.finish()
        
        from direct.interval.IntervalGlobal import LerpScaleInterval        
        self.prevScale = self.getScale()
        self.scaleUpInterval = LerpScaleInterval(self.np, duration=0.2, scale=self.getScale()*1.2, startScale=self.getScale())
        self.scaleUpInterval.start()

    def unhighlight(self):
        """The mouse pointer has left the bounds of this nodepath. Subclasses 
        should override this method to implement custom mouse-over behaviour.
        
        """
        # If we are already scaling down, do nothing.
        if  hasattr(self,'scaleDownInterval') and self.scaleDownInterval.isPlaying():
            return

        # If we are in the process of scaling up, stop.
        if  hasattr(self,'scaleUpInterval') and self.scaleUpInterval.isPlaying():
            self.scaleUpInterval.pause()
        
        from direct.interval.IntervalGlobal import LerpScaleInterval
        self.scaleDownInterval = LerpScaleInterval(self.np, duration=0.2, scale=self.prevScale, startScale=self.getScale())
        self.scaleDownInterval.start()

    def set_highlightable(self,boolean):
        """Enable or disable mouse-over highlighting of this nodepath. (When
        disabled, the highlight and unhighlight methods will not be
        called.)
        
        """    
        # Finish any intervals that are playing.
        if  hasattr(self,'scaleDownInterval') and self.scaleDownInterval.isPlaying():
            self.scaleDownInterval.finish()
        elif hasattr(self,'scaleUpInterval') and self.scaleUpInterval.isPlaying():
            self.scaleUpInterval.finish()
    
        # Reset the scale.
        if hasattr(self,'prevScale'):
            self.setScale(self.prevScale)

        if boolean:
            self.np.setPythonTag("highlightable",self)
        else:    
            self.np.clearPythonTag("highlightable")
 def onActivate(self, entity, suit):
     slidePos = entity.getPos(render)
     slidePos.setY(slidePos.getY() - 5.1)
     moveTrack = Sequence(Wait(0.1), LerpPosInterval(self.gag, 0.1, slidePos))
     animTrack = Sequence(ActorInterval(self.gag, 'banana', startTime=3.1), Wait(1.1), LerpScaleInterval(self.gag, 1,
                                     Point3(0.01, 0.01, 0.01)))
     suitTrack = ActorInterval(suit, 'slip-backward')
     soundTrack = Sequence(SoundInterval(self.slipSfx, duration=0.55, node=suit), SoundInterval(self.activateSfx, node=suit))
     Parallel(moveTrack, animTrack, suitTrack, soundTrack).start()
     ActivateTrapGag.onActivate(self, entity, suit)