Exemple #1
0
def Smoke(self,model):
    p1 = ParticleEffect()
    p1.cleanup()
    p1 = ParticleEffect()
    p1.loadConfig(Filename(MYDIRPART+'smoke.ptf'))        
    p1.start(model)
    p1.setPos(3.000, 0.000, 2.250)
Exemple #2
0
def Water(self,model):
    p1 = ParticleEffect()
    p1.cleanup()
    p1 = ParticleEffect()
    p1.loadConfig(Filename(MYDIRPART+'fountain.ptf'))        
    p1.start(model)
    p1.setPos(3.000, 0.000, 2.250)
Exemple #3
0
    def _switch_garland(self):
        """Christmas related method.

        Enables or removes the locomotive garland
        and an ability to shot a flapper.
        """
        if self._garland is None:
            self._garland = loader.loadModel(address("garland"))  # noqa: F821
            self._garland.reparentTo(self._model)

            self._confetti = []

            for color in ("red", "blue", "green"):
                confetti = ParticleEffect()
                confetti.loadConfig("effects/confetti_{}.ptf".format(color))
                confetti.setPos(0, 0.32, 0.29)
                self._confetti.append(confetti)

            self._confetti_snd = base.sound_mgr.loadSfx(  # noqa: F821
                "sounds/train/flapper.ogg")
            base.sound_mgr.attachSoundToObject(  # noqa: F821
                self._confetti_snd, self._model)
        else:
            self._garland.removeNode()
            self._garland = None

            for effect in self._confetti:
                effect.softStop()
                effect.cleanup()

            self._confetti = None
            base.sound_mgr.detach_sound(self._confetti_snd)  # noqa: F821
            self._confetti_snd = None
class BlockDestroyedEffect(object):
    __base = None
    __pos = None
    def __init__(self, base, pos):
        self.__base = base
        self.__pos = pos
        self.particleEffect()

    def particleEffect(self):
        self.p = ParticleEffect()
        self.loadParticleConfig('particleEffect.ptf')
        self.__base.taskMgr.doMethodLater(0.5, self.stopParticles, "stop")
        self.__base.taskMgr.doMethodLater(2.0, self.cleanUpParticles, "cleanup")


    def cleanUpParticles(self, task):
         self.p.cleanup()

    def stopParticles(self, task):
         self.p.softStop()

    def loadParticleConfig(self, file):
        self.p.cleanup()
        self.p = ParticleEffect()
        self.p.loadConfig(Filename(file))
        self.p.setPos(self.__pos.x, self.__pos.y, 2)
        self.p.start(parent = self.__base.render, renderParent = self.__base.render)
Exemple #5
0
def SmokeRing(self,model):
    p1 = ParticleEffect()
    p1.cleanup()
    p1 = ParticleEffect()
    p1.loadConfig(Filename(MYDIRPART+'smokering.ptf'))        
    p1.start(model)
    p1.setPos(0, 0.000, 0)
Exemple #6
0
 def particle(path, parent, render_parent, pos, timeout):
     par = ParticleEffect()
     par.loadConfig(path)
     par.start(parent=parent, renderParent=render_parent)
     par.set_pos(pos)
     args = timeout, lambda par: par.cleanup(), [par]
     eng.do_later(*args)
Exemple #7
0
class AoeDamageItem(Item):
    '''
    一次全房间伤害
    '''
    def __init__(self, damageVal=defaultScopeDamageVal):
        super(AoeDamageItem, self).__init__('item_AoeDamage')
        self.damageVal = damageVal

    def cleanup(self):
        self.particle.cleanup()
        self.sound.stop()

    def action(self, entry):
        # 发送事件  事件处理函数将房间内的所有怪物的血量减少damageVal
        super(AoeDamageItem, self).action(entry)
        base.messenger.send("global-damage", [self.damageVal])

        self.sound = loader.loadSfx("Audio/aoe.wav")
        self.sound.play()

        self.particle = ParticleEffect()
        self.particle.loadConfig("assets/particles/globalBoom.ptf")
        self.particle.setScale(10)
        self.particle.start(render)
        base.taskMgr.doMethodLater(1.2,
                                   self.cleanup,
                                   "stop Particle",
                                   extraArgs=[])

        # 销毁道具
        self._destroy()
 def __createToonInterval(self, delay):
     track = Sequence(Wait(delay))
     sprayEffect = ParticleEffect()
     sprayEffect.loadConfig('phase_5/etc/soundWave.ptf')
     sprayEffect.setDepthWrite(0)
     sprayEffect.setDepthTest(0)
     sprayEffect.setTwoSided(1)
     I1 = 2.8
     track.append(
         ActorInterval(self.avatar,
                       'sound',
                       playRate=1.0,
                       startTime=0.0,
                       endTime=I1))
     track.append(
         Func(self.setPosFromOther, sprayEffect, self.gag,
              Point3(0, 1.6, -0.18)))
     track.append(
         self.__getPartTrack(sprayEffect,
                             0.0,
                             6.0, [sprayEffect, self.avatar, 0],
                             softStop=-3.5))
     track.append(
         ActorInterval(self.avatar, 'sound', playRate=1.0, startTime=I1))
     return track
Exemple #9
0
 def mouBala(bala, balaImage, vel, queue, task):
     if task.time > 3:
         balaImage.detachNode()
         expbala = ParticleEffect()
         expbala.reparentTo(self.particlesDummy)
         expbala.loadConfig('explosio.ptf')
         expbala.start(bala)
         taskMgr.doMethodLater(.25,
                               suprimir,
                               "suprimir",
                               extraArgs=[bala, expbala])
         return task.done
     if queue.getNumEntries() != 0:
         balaImage.detachNode()
         entry = queue.getEntry(0)
         bala.setPos(entry.getSurfacePoint(self.particlesDummy))
         expbala = ParticleEffect()
         expbala.reparentTo(self.particlesDummy)
         expbala.loadConfig('explosio.ptf')
         expbala.start(bala)
         taskMgr.doMethodLater(.25,
                               suprimir,
                               "suprimir",
                               extraArgs=[bala, expbala])
         return task.done
     bala.setFluidPos(bala, 0, vel * globalClock.getDt(), 0)
     balaImage.setR(balaImage, 1000 * globalClock.getDt())
     return task.cont
class ParticleDemo(ShowBase):

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

        # Standard title and instruction text
        self.title = OnscreenText(
            text="Panda3D: Tutorial - Particles",
            parent=base.a2dBottomCenter,
            style=1, fg=(1, 1, 1, 1), pos=(0, 0.1), scale=.08)
        self.escapeEvent = OnscreenText(
            text=HELP_TEXT, parent=base.a2dTopLeft,
            style=1, fg=(1, 1, 1, 1), pos=(0.06, -0.06),
            align=TextNode.ALeft, scale=.05)

        # More standard initialization
        self.accept('escape', sys.exit)
        self.accept('1', self.loadParticleConfig, ['steam.ptf'])
        self.accept('2', self.loadParticleConfig, ['dust.ptf'])
        self.accept('3', self.loadParticleConfig, ['fountain.ptf'])
        self.accept('4', self.loadParticleConfig, ['smoke.ptf'])
        self.accept('5', self.loadParticleConfig, ['smokering.ptf'])
        self.accept('6', self.loadParticleConfig, ['fireish.ptf'])

        self.accept('escape', sys.exit)
        base.disableMouse()
        base.camera.setPos(0, -20, 2)
        base.camLens.setFov(25)
        base.setBackgroundColor(0, 0, 0)

        # This command is required for Panda to render particles
        base.enableParticles()
        self.t = loader.loadModel("teapot")
        self.t.setPos(0, 10, 0)
        self.t.reparentTo(render)
        self.setupLights()
        self.p = ParticleEffect()
        self.loadParticleConfig('steam.ptf')

    def loadParticleConfig(self, filename):
        # Start of the code from steam.ptf
        self.p.cleanup()
        self.p = ParticleEffect()
        self.p.loadConfig(Filename(filename))
        # Sets particles to birth relative to the teapot, but to render at
        # toplevel
        self.p.start(self.t)
        self.p.setPos(3.000, 0.000, 2.250)

    # Setup lighting
    def setupLights(self):
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.4, .4, .35, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(LVector3(0, 8, -2.5))
        directionalLight.setColor((0.9, 0.8, 0.9, 1))
        # Set lighting on teapot so steam doesn't get affected
        self.t.setLight(self.t.attachNewNode(directionalLight))
        self.t.setLight(self.t.attachNewNode(ambientLight))
Exemple #11
0
 def addEffects(self):
     if self.mp.has_key('effects'):
         base.enableParticles()
         for effect in self.mp['effects']:
             p = ParticleEffect()
             p.loadConfig(GAME + '/particles/' + effect['file'] + '.ptf')
             p.start(render)
             p.setPos(self.logic2terrain(effect['position']))
 def addEffects(self):
     if self.mp.has_key('effects'):
         base.enableParticles()
         for effect in self.mp['effects']:
             p = ParticleEffect()
             p.loadConfig(GAME+'/particles/'+effect['file']+'.ptf') 
             p.start(render)
             p.setPos(self.logic2terrain( effect['position'] ))
Exemple #13
0
def Flame(self,model):
    p1 = ParticleEffect()
    p1.cleanup()
    p1 = ParticleEffect()
    p1.loadConfig(Filename('ee.ptf'))#'fireish.ptf'))        
    p1.start(model)
    p1.setPos(3.000, 0.000, 2.250)
    setupLights(self,model)
Exemple #14
0
 def initTorchParticles(self):
     torchTops = self.level.findAllMatches("**/TorchTop*")
     fxList = ['TorchSmoke.ptf', 'TorchFire.ptf']
     for torch in torchTops:
         for fx in fxList:
             p = ParticleEffect()
             p.loadConfig(Filename(fx))
             p.setPos(torch.getPos(render))
             p.start(self.level)
Exemple #15
0
 def create_vfx(vfxname):
     particles = ParticleEffect()
     if pman.is_frozen():
         vfxpath = f'assets/vfx/{vfxname}.ptf'
     else:
         vfxpath = f'.built_assets/vfx/{vfxname}.ptf'
     particles.loadConfig(vfxpath)
     particles.set_shader_auto(True)
     return particles
Exemple #16
0
 def createMyParticle(self, size):
     particle = ParticleEffect()
     smokeEffect = self.path + "smoke.ptf"
     particle.loadConfig(Filename(smokeEffect))
     p0 = particle.particlesDict['particles']
     p0.emitter.setOffsetForce(Vec3(0.0, 0.0, 0.0))
     p0.factory.setLifespanBase(0.3 * size)
     p0.setPoolSize(200)
     return particle
Exemple #17
0
 def load_particles (self, name):
     p = ParticleEffect ()
     p.loadConfig (Filename (name))
     p.setLightOff () 
     p.setTransparency (TransparencyAttrib.MAlpha) 
     p.setBin ('fixed', 0) 
     p.setDepthWrite (False)
     p.setShaderOff ()
     return p
Exemple #18
0
    def loadParticles(fileName):
        extension = "ptf"
        directory = "Particles/"
        if not fileName.endswith(".{0}".format(extension)):
            fileName = "{0}.{1}".format(fileName, extension)
        fileName = "{0}{1}".format(directory, fileName)

        particleEffect = ParticleEffect()
        particleEffect.loadConfig(fileName)
        return particleEffect
Exemple #19
0
class fireSystem(NodePath):

    lifeSpanSeconds = 1
    lifeRemaining = 0

    isAlight = False

    def __init__(self, name, fireType):
        NodePath.__init__(self, "fire" + str(name))
        NodePath.setPythonTag(self, "fireSystem", self)
        self.setScale(1, 1, 1)

        self.fire = ParticleEffect()
        self.fire.loadConfig('fire.ptf')
        try:
            file = open(fireType + ".txt")
            lines = file.readlines()
            newFireColor = LColor()
            colorLine = lines[0].split(",")
            for i in range(4):
                newFireColor[i] = float(colorLine[i])
            self.fire.getParticlesList()[0].getRenderer().setColor(
                newFireColor)
            self.lifeSpanSeconds = float(lines[1])
            file.close()
        except IOError:
            print("Firetype not found")

        self.lifeRemaining = self.lifeSpanSeconds
        fireSphere = CollisionSphere(0, 0, 1.25, 2.5)
        self.collisionNodeName = "fire{}Collision".format(self.id)
        fireCollisionNode = CollisionNode(self.collisionNodeName)
        fireCollisionNode.addSolid(fireSphere)
        self.collision = self.attachNewNode(fireCollisionNode)
        base.cTrav.addCollider(self.collision, base.handler)

        self.fire.start(self, self)
        self.fire.softStop()
        self.burn = taskMgr.add(self.burnTask, "burnTask")

        self.notifier = CollisionHandlerEvent

    def burnTask(self, task):
        if self.isAlight:
            deltaTime = globalClock.getDt()
            self.lifeRemaining -= deltaTime
            if self.lifeRemaining <= 0:
                self.fire.softStop()
                self.isAlight = False
        return task.cont

    def ignite(self):
        self.isAlight = True
        self.lifeRemaining = self.lifeSpanSeconds
        self.fire.softStart()
Exemple #20
0
class GoodsParticle(Goods):
    def __init__(self, name, pos, scale, parent, sort):
        base.enableParticles()
        self.particle = ParticleEffect()
        self.particle.loadConfig(Filename("res/particles/" + name + ".ptf"))
        self.particle.start(render)
        self.particle.setPos(pos)
        self.particle.setBin("fixed", sort)
        self.particle.setDepthWrite(False)
        self.particle.setScale(scale)
        Goods.__init__(self, self.particle, [name], name, False)
def init_player(self, left_btn, right_btn, player_number ,pos=(0,0,0), heading=0):
    color = (configs.COLORS_MAP[player_number][0])

    nodePath = loadObject()
    nodePath.setPos(pos)
    nodePath.setScale(configs.SCALE*0.004)
    nodePath.setColor(color)

    p = ParticleEffect()
    p.loadConfig('textures/flare.ptf')
    p.start(parent = nodePath, renderParent = render)
    p0 = p.getParticlesList()[0]
    p0.emitter.setRadiateOrigin(Point3(0.05*cos(heading* pi/180), 0.0, 0.05*sin(heading* pi/180)))
    p.setPos(0,-1,0)
    # p.setBin("unsorted", 0)
    # p.setDepthTest(False)
    p.setTwoSided(True)

    text= TextNode('text') 
    text.setText(str("%s" % player_number))
    text.setTextColor(color)
    text.setAlign(TextNode.ACenter)
    # text.font = self.font
    text3d = NodePath(text) 
    text3d.setTwoSided(True)
    text3d.setPos(nodePath, -1,-3,-4)
    text3d.reparentTo(render)
    circle = loadObject(tex='circle.png')
    circle.reparentTo(render)
    circle.setPos(nodePath, 0,-2,0)
    text3d.setScale(0.13)
    circle.setScale(0.09)
    text3d.setColorScale(color)
    circle.setColorScale(color)


    new_line, line_vertex, line_node = start_new_line(self, pos[0], pos[2], color)
    line_id = configs.ENTITY_ID
    configs.ENTITIES[configs.ENTITY_ID] = {'CATEGORY':'line', 'GEOM':new_line, 'VERTEX':line_vertex, "NODE": line_node}
    configs.ENTITY_ID += 1
    speed = configs.FORWARD_SPEED
    right_angle = configs.FORCE_RIGHT_ANGLE_TURN
    # print left_btn
    # print right_btn
    self.accept(("%s" % left_btn),     player_controls, [configs.ENTITY_ID, 'TURN_LEFT', 1])
    self.accept(("%s-up" % left_btn),  player_controls, [configs.ENTITY_ID, 'TURN_LEFT', 0])
    self.accept(("%s" % right_btn),     player_controls, [configs.ENTITY_ID, 'TURN_RIGHT', 1])
    self.accept(("%s-up" % right_btn),  player_controls, [configs.ENTITY_ID, 'TURN_RIGHT', 0])

    configs.ENTITIES[configs.ENTITY_ID] = {'CATEGORY':'player','ALIVE':True, 'NODE':nodePath,'PARTICLE_PARENT':p, 'PARTICLE':p0, 
        'HEADING':heading, 'CURRENT_LINE':line_id, 'TICKNESS':configs.SCALE, 'TURN_LEFT':0, 'TURN_RIGHT':0, 'COLOR':color, 
        'PLAYER_ID':text3d, 'CIRCLE_NODE':circle, 'LEFT_ARMED':True, 'RIGHT_ARMED':True, 'PLAYER_NUMBER': player_number, 'SPEED':speed,
        'RIGHT_ANGLE_TURN':right_angle }
    configs.ENTITY_ID += 1
class World(DirectObject):
    def __init__(self):
        #Standard title and instruction text
        self.title = OnscreenText(
            text="Panda3D: Tutorial - Particles",
            style=1, fg=(1,1,1,1), pos=(0.8,-0.95), scale = .07)
        self.escapeEvent = OnscreenText(
            text=HELPTEXT,
            style=1, fg=(1,1,1,1), pos=(-1.3, 0.95),
            align=TextNode.ALeft, scale = .05)

        #More standard initialization
        self.accept('escape', sys.exit)
        self.accept('1', self.loadParticleConfig , ['steam.ptf'])
        self.accept('2', self.loadParticleConfig , ['dust.ptf'])
        self.accept('3', self.loadParticleConfig , ['fountain.ptf'])
        self.accept('4', self.loadParticleConfig , ['smoke.ptf'])
        self.accept('5', self.loadParticleConfig , ['smokering.ptf'])
        self.accept('6', self.loadParticleConfig , ['fireish.ptf'])
        
        self.accept('escape', sys.exit)
        base.disableMouse()
        camera.setPos(0,-20,2)
        base.setBackgroundColor( 0, 0, 0 )

        #This command is required for Panda to render particles
        base.enableParticles()
        self.t = loader.loadModel("models/teapot")
        self.t.setPos(0,10,0)
        self.t.reparentTo(render)
        self.setupLights()
        self.p = ParticleEffect()
        self.loadParticleConfig('steam.ptf')

    def loadParticleConfig(self, file):
        #Start of the code from steam.ptf
        self.p.cleanup()
        self.p = ParticleEffect()
        self.p.loadConfig(Filename(file))        
        #Sets particles to birth relative to the teapot, but to render at toplevel
        self.p.start(self.t)
        self.p.setPos(3.000, 0.000, 2.250)
    
    #Setup lighting
    def setupLights(self):
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.4, .4, .35, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3( 0, 8, -2.5 ) )
        directionalLight.setColor(Vec4( 0.9, 0.8, 0.9, 1 ) )
        #Set lighting on teapot so steam doesn't get affected
        self.t.setLight(self.t.attachNewNode(directionalLight))
        self.t.setLight(self.t.attachNewNode(ambientLight))
Exemple #23
0
class app(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        
        self.planet=self.loader.loadModel(MAINDIR+'/Engine/Dark_soul.egg')
        self.planet.setPos(0,0,0)
        self.planet.setScale(0.09,0.09,0.09)
        self.planet.reparentTo(render)
        
        self.setBackgroundColor(0.2,0.2,0.2,1)

        self.backgrnd=OnscreenImage(image=str(MAINDIR)+'/Engine/Stars.png',scale=(1.78,1,1))
        self.backgrnd.reparentTo(render)
        self.backgrnd.setPos(0,0,0)

        self.enableParticles()
        self.testpart=ParticleEffect()
        self.testpart.loadConfig(MAINDIR+'/Engine/destruction_ring.ptf')
        self.testpart.start(parent=render,renderParent=render)
        self.pointA,self.pointB=LPoint3f(0,0,0),LPoint3f(1,0.1,0.3)
        vec = self.pointB - self.pointA
        norm=vec.length()
        H,P,R=-atan(vec[0]/vec[1])*180/pi+180,(-atan(vec[2]/vec[1])+pi/2)*180/pi,0 # cette formule vaut son poids en or X)
        #H,P,R=30,-30,0
        self.planet.setHpr(H,P,R)
        self.testpart.setHpr(H,P,R) 
        self.testpart.radiateOrigin=(vec[0]/norm,vec[1]/norm,vec[2]/norm)
        
        # axis
        coord=[(1,0,0),(0,1,0),(0,0,1)]
        axis=[]
        for c in range(3): 
            axis.append(LineSegs())
            axis[c].moveTo(0,0,0)
            axis[c].drawTo(coord[c])
            axis[c].setThickness(3)
            axis[c].setColor(tuple([coord[c][u]*255 for u in range(len(coord[c]))] +[0.05]))
            NodePath(axis[c].create()).reparent_to(render)

        # end of axis

        testline=LineSegs()
        testline.moveTo(self.pointA)
        testline.drawTo(self.pointB)
        testline.setThickness(3)
        testline.set_color(0,0,0,1)
        NodePath(testline.create()).reparent_to(render)


        plight=render.attachNewNode(PointLight('plight01'))
        plight.setPos(5,0,0)
        self.planet.setLight(plight)
Exemple #24
0
    def shootParticles(self,collision_result):
        "Summons and explosion of particles where the player shot."
        # Create Particle
        p = ParticleEffect()
        p.loadConfig("../../models/particle_shot.ptf")
        
        # Put particle at shot point
        p.setPos(collision_result.getHitPos())        
        p.start(parent = self.mainRef.render, renderParent = self.mainRef.render)

        # Schedule particle effect cleanup
        particle_timeout = 0.2 # Time in seconds for the particle effect to fade
        taskMgr.doMethodLater(particle_timeout, self.releaseParticle, 'Particle Effect Cleanup', extraArgs = [p])
Exemple #25
0
 def __createToonInterval(self, delay):
     track = Sequence(Wait(delay))
     sprayEffect = ParticleEffect()
     sprayEffect.loadConfig('phase_5/etc/soundWave.ptf')
     sprayEffect.setDepthWrite(0)
     sprayEffect.setDepthTest(0)
     sprayEffect.setTwoSided(1)
     I1 = 2.8
     track.append(ActorInterval(self.avatar, 'sound', playRate=1.0, startTime=0.0, endTime=I1))
     track.append(Func(self.setPosFromOther, sprayEffect, self.gag, Point3(0, 1.6, -0.18)))
     track.append(self.__getPartTrack(sprayEffect, 0.0, 6.0, [sprayEffect, self.avatar, 0], softStop=-3.5))
     track.append(ActorInterval(self.avatar, 'sound', playRate=1.0, startTime=I1))
     return track
Exemple #26
0
class BombExplosion:
    """A hand bomb explosion reusable effect.

    Includes sound and particle effects.

    Args:
        parent (object): Object to explode. Must include "model" property.
    """

    def __init__(self, parent):
        self._parent = parent

        self._smoke = ParticleEffect()
        self._smoke.loadConfig("effects/bomb_smoke1.ptf")

        self._sparks = ParticleEffect()
        self._sparks.loadConfig("effects/white_sparks1.ptf")

        self._snd = base.sound_mgr.loadSfx(  # noqa: F821
            "sounds/combat/bomb_explosion1.ogg"
        )
        base.sound_mgr.attachSoundToObject(self._snd, parent.model)  # noqa: F821

    def _stop_explosion(self, task):
        """Disable explosion effect."""
        self._smoke.softStop()
        self._sparks.softStop()
        return task.done

    def play(self):
        """Make actual explosion and plan its stop."""
        self._snd.play()
        self._smoke.start(self._parent.model, render)  # noqa: F821
        self._sparks.start(self._parent.model, render)  # noqa: F821
        self._smoke.softStart()
        self._sparks.softStart()

        taskMgr.doMethodLater(  # noqa: F821
            2.49, self._stop_explosion, "train_disable_bomb_explosion"
        )

    def setPos(self, x, y, z):
        """Set explosion position.

        Args:
            x (float): X coordinate.
            y (float): Y coordinate.
            z (float): Z coordinate.
        """
        self._smoke.setPos(x, y, z)
        self._sparks.setPos(x, y, z)
Exemple #27
0
class World:
    def __init__(self, missionMap):
        self.map = missionMap
        base.taskMgr.add(self.loadScene)
        self.loaded = False

    async def loadScene(self, task):
        text = OnscreenText("Loading...")

        self.terrain = await loader.loadModel(models["terrain"],
                                              blocking=False)
        self.terrain.reparentTo(render)
        if USE_RENDER_PIPELINE:
            rp.prepare_scene(self.terrain)
        self.terrain.setScale(18)

        modelList = parseMissionFile(self.map)
        print(modelList)
        for model in modelList:
            try:
                m = loader.loadModel("models/" + model.modelName)
                m.reparentTo(self.terrain)
                m.setPos(*model.modelPos)
            except:
                #Its a particle system
                floater = render.attachNewNode("particle floater")
                floater.setPos(self.terrain, *model.particlePos)
                floater.setScale(5)
                self.particles = ParticleEffect()
                self.particles.loadConfig(model.ptfFile)
                print(model.particlePos)
                self.particles.start(parent=floater, renderParent=floater)
                #self.particles.setPos(*model.particlePos)

        #Once loaded, remove loading text
        text.hide()
        del text

        self.loaded = True

    def show(self):
        self.terrain.show()

    def hide(self):
        self.terrain.hide()

    def destroy(self):
        self.terrain.removeNode()
        del self.terrain
        del self
Exemple #28
0
class Effects:
    def __init__(self):

        #Initialisierung
        base.enableParticles()
        self.__space = ParticleEffect()
        self.__particlepath = ""

        #Dropvariablen
        self.__nDrop = None
        self.__dropitem = ""
        self.__chance = 0

        #Explosionen Attribute
        self.__nExplosion = None

        #Dropattribute
        self.__heal = 0

    def createSpaceStars(self, particlefile):
        self.__particlepath = particlefile
        self.__space.loadConfig(Filename(self.__particlepath))

        self.__space.setPos(0, 10000, -20)
        self.__space.setScale(250, 200, 250)

    def removeSpaceStars(self):
        self.__space.cleanup()

    def getDrop(self, drop, chnc, pos):
        self.__dropitem = drop
        self.__chance = chnc
        generate = choice(range(0, 100) + range(0, 100))
        if generate < self.__chance:
            self.__nDrop = loader.loadModel(self.__dropitem)
            self.__nDrop.setScale(1, 1, 1)
            self.__nDrop.reparentTo(render)
            self.__nDrop.setPos(pos)
            return self.__nDrop
        else:
            self.__nDrop = None

    def getExplosion(self, pos):
        self.__nExplosion = loader.loadModel("models/box")
        self.__nExplosion.reparentTo(render)
        self.__nExplosion.setScale(1, 1, 1)
        self.__nExplosion.setPos(pos)
        return self.__nExplosion
class FlameTest:
    def __init__(self):
        self.setupLights()
        self.loadItem()
        self.loadParticles()
    
    
    def loadItem(self):
        self.itemNode = loader.loadModel('../Models/torch')
        self.itemNode.setColor(Vec4(1,1,1,1))
        self.itemNode.setScale(2)
        self.itemNode.reparentTo(render)
        self.itemNode.setPos(0,0,0)

    def loadParticles(self):
        base.enableParticles()
        self.rFlame = ParticleEffect()
        self.rFlame.loadConfig("../Models/fire.ptf")
        self.rFlame.start(self.itemNode)
        pos = self.itemNode.getPos()
        self.rFlame.setPos(pos[0], pos[1], pos[2] + 4)
        
        lightNode = NodePath('flame')
        lightNode.reparentTo(self.rFlame)
        lightNode.setZ(lightNode.getZ() + 0.5)
        flame = PointLight('flame-light')
        flameNP = lightNode.attachNewNode(flame)
        flameNP.node().setColor(Vec4(0.9, 0.7, 0.5, 1.0))
        # flameNP.node().setAttenuation(Vec3(0, 0.001, 0.000009))
        flameNP.setZ(flameNP.getZ() + 0.6)
        render.setLight(flameNP)
        
    
    def setupLights(self):
        # set up an ambient light
        self.ambientLight = AmbientLight("ambientLight")
        
        #for setting colors, alpha is largely irrelevant
        # slightly blue to try and produce a wintry, snowy look
        self.ambientLight.setColor((0.1, 0.1, 0.1, 1.0))
        
        #create a NodePath, and attach it directly into the scene
        self.ambientLightNP = render.attachNewNode(self.ambientLight)
        
        #the node that calls setLight is what's illuminated by the given light
        #you can use clearLight() to turn it off
        render.setLight(self.ambientLightNP)
Exemple #30
0
class smoke_emitter():
    def __init__(self, parent, _x, _y, _z):
        self.x = _x
        self.y = _y
        self.z = _z
        self.parent = parent
        self.p = ParticleEffect()
        self.load_config('steam.ptf')
        self.p.setScale(200)

    def load_config(self, file_name):
        self.p.cleanup()
        self.p = ParticleEffect()
        self.p.loadConfig(file_name)
        self.p.start(render)
        self.p.setPos(self.x, self.y, self.z)
        self.p.reparentTo(self.parent)
Exemple #31
0
class fireSystem():

    lifeSpanSeconds = 20
    lifeRemaining = 0

    isAlight = False

    def __init__(self, id, parent):
        self.id = id
        self.actor = Actor()
        self.actor.reparentTo(parent)

        self.lifeRemaining = self.lifeSpanSeconds

        self.fire = ParticleEffect()
        self.fire.loadConfig('fire.ptf')
        self.fire.reparentTo(self.actor)
        self.fire.setPos(0.000, 0.000, 4.250)

        fireSphere = CollisionSphere(0, 0, 4.25, 2.5)
        self.collisionNodeName = "fire{}Collision".format(self.id)
        fireCollisionNode = CollisionNode(self.collisionNodeName)
        fireCollisionNode.addSolid(fireSphere)
        self.collision = self.actor.attachNewNode(fireCollisionNode)
        base.cTrav.addCollider(self.collision, base.handler)

        self.burn = taskMgr.add(self.burnTask, "burnTask")

        self.notifier = CollisionHandlerEvent

    def burnTask(self, task):
        if self.isAlight:

            deltaTime = globalClock.getDt()
            self.lifeRemaining -= deltaTime
            if self.lifeRemaining <= 0:
                self.fire.softStop()
            else:
                return task.cont
        else:
            return task.cont

    def ignite(self):
        self.isAlight = True
        self.fire.start()
Exemple #32
0
    def __init__(self, loc_model):
        self._is_loading = False
        self.is_up = False

        self._coors = [None, None, None, None]
        self._sights = []
        self._explosions = []
        self._ground_holes = []
        self._smokes = []
        self._bombs = []
        self._explosion_snds = []

        self._train_mod = loc_model
        self._model = Actor(address("cluster_bomb_launcher"))
        self._model.reparentTo(loc_model)

        for _ in range(4):
            sight = loader.loadModel(address("grenade_sight"))  # noqa: F82
            sight.reparentTo(loc_model)
            sight.hide()
            self._sights.append(sight)

            explosion = ParticleEffect()
            explosion.loadConfig("effects/grenade_explode.ptf")
            self._explosions.append(explosion)

            smoke = ParticleEffect()
            smoke.loadConfig("effects/bomb_smoke1.ptf")
            self._smokes.append(smoke)

            snd = loader.loadSfx("sounds/combat/bomb_explosion1.ogg")  # noqa: F821
            snd.setVolume(random.uniform(0.1, 0.15))
            snd.setPlayRate(random.uniform(0.8, 1))
            self._explosion_snds.append(snd)

            hole = loader.loadModel(address("ground_hole"))  # noqa: F821
            hole.reparentTo(loc_model)
            hole.setTransparency(TransparencyAttrib.MAlpha)
            hole.hide()
            self._ground_holes.append(hole)

        self._load_snd = loader.loadSfx("sounds/combat/howitzer_load.ogg")  # noqa: F821
        self._load_snd.setPlayRate(0.8)

        base.accept("3", self.change_state)  # noqa: F82
 def __init__(self):
     ShowBase.__init__(self)
     base.cam.setPos(0, -60, 0)
     base.enableParticles()
     with open('fire.json') as f:
         values = json.load(f)
     particle_effect = createEffect(values)
     p = ParticleEffect()
     p.loadConfig('fireish.ptf')
     p.start(parent=render, renderParent=render)
     p.setPos(5, 0, 0)
     p2 = ParticleEffect()
     p2.loadConfig('fireish2.ptf')
     p2.start(parent=render, renderParent=render)
     p2.setPos(10, 0, 0)
     self.smiley2 = loader.loadModel('smiley')
     self.smiley2.setPos(-5, 0, 0)
     vfx(self.smiley2, texture='vfx/big_fire3.png', scale=1.0).loop()
Exemple #34
0
class World(DirectObject):
    def __init__(self):
        

        #More standard initialization
        self.accept('escape', sys.exit)
        self.accept('1', self.loadParticleConfig , ['spark.ptf'])
        
        
        self.accept('escape', sys.exit)
        base.disableMouse()
        camera.setPos(0,-20,2)
        base.setBackgroundColor( 0, 0, 0 )

        #This command is required for Panda to render particles
        base.enableParticles()
        self.t = loader.loadModel("models/stepipe")
        self.t.setPos(0,0,0)
        self.t.reparentTo(render)
        self.setupLights()
        self.p = ParticleEffect()
        self.loadParticleConfig('spark.ptf')
        self.p.setScale(3)

    def loadParticleConfig(self, file):
        #Start of the code from spark.ptf
        self.p.cleanup()
        self.p = ParticleEffect()
        self.p.loadConfig(Filename(file))        
        #Sets particles to birth relative to the teapot, but to render at toplevel
        self.p.start(self.t)
        self.p.setPos(-2.00, 0.000, 3.150)
    
    #Setup lighting
    def setupLights(self):
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.4, .4, .35, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3( 0, 8, -2.5 ) )
        directionalLight.setColor(Vec4( 0.9, 0.8, 0.9, 1 ) )
        #Set lighting on teapot so spark doesn't get affected
        self.t.setLight(self.t.attachNewNode(directionalLight))
        self.t.setLight(self.t.attachNewNode(ambientLight))
Exemple #35
0
class SmokeTrail(object):
    def __init__(self, warsim):
        self.warsim = warsim
        self.initialize()

    def initialize(self):
        smokeEffect = self.warsim.path + "smoke.ptf"
        self.particle = ParticleEffect()
        self.particle.loadConfig(Filename(smokeEffect))
        self.litterMin = 1.0
        # rough estimate based on masses that are around 50000->120000.  gets the max litter down to 25 -> 60
        self.litterMax = self.warsim.myShip.mass / 2500.0
        self.litterSize = self.litterMin
        self.particleStarted = False

    def update(self, facing):

        if self.warsim.myShip.strength >= 99.0:
            return

        if not self.particleStarted:
            self.particle.start(parent=self.warsim.sim,
                                renderParent=render)  #, renderParent=self.sim)
            self.particleStarted = True

        p0 = self.particle.particlesDict['particles']

        # 90 degree offset from what you waht expect
        radians = math.radians(self.warsim.myShip.facing - 90)
        xvec = math.cos(radians)
        yvec = math.sin(radians)

        p0.emitter.setOffsetForce(Vec3(0.0, xvec, yvec))

        futureLitterSize = self.warsim.myShip.strength * self.litterMax / 100.0
        futureLitterSize = abs(self.litterMax - futureLitterSize)
        if self.litterSize != futureLitterSize:
            # want the inverse
            self.litterSize = futureLitterSize
            p0.setLitterSize(int(self.litterSize))

    def cleanup(self):
        self.particle.cleanup()
Exemple #36
0
class Swarm(Unit):
    '''
    Subclass of Units, Tier 1 Swarm
    '''
    def __init__(self, host_planet, player):
        '''
        Constructor
        @param host_planet : The planet where the unit is constructed
        '''
        base.enableParticles()
        super(Swarm, self).__init__(host_planet, player, SWARM_VELOCITY, SWARM_MAX_ENERGY, SWARM_DAMAGE, [])
        self.quad_path.setScale(2)
#        self.quad_path.removeNode()
        self._loadSounds("swarm")
        self.model_path.setColor(Vec4(1,1,1,0.1))
        self.model_path.setLightOff()
        self.p = ParticleEffect()
        self.p.loadConfig('models/units/swarm/swarm.ptf')
        self.p.start(self.model_path)
    def damageCogsNearby(self, radius=None):
        if self.avatar.doId != base.localAvatar.doId:
            return
        if not radius:
            radius = self.soundRange
        suits = []
        for obj in base.cr.doId2do.values():
            if obj.__class__.__name__ in CIGlobals.SuitClasses:
                if obj.getPlace() == base.localAvatar.zoneId:
                    if obj.getDistance(self.avatar) <= radius:
                        if self.avatar.doId == base.localAvatar.doId:
                            suits.append(obj)

        def shouldContinue(suit, track):
            if suit.isDead():
                track.finish()

        for suit in suits:
            if self.name != CIGlobals.Opera:
                suit.sendUpdate('hitByGag', [self.getID()])
            else:
                breakEffect = ParticleEffect()
                breakEffect.loadConfig('phase_5/etc/soundBreak.ptf')
                breakEffect.setDepthWrite(0)
                breakEffect.setDepthTest(0)
                breakEffect.setTwoSided(1)
                suitTrack = Sequence()
                if suit.isDead():
                    return
                suitTrack.append(Wait(2.5))
                delayTime = random.random()
                suitTrack.append(Wait(delayTime + 2.0))
                suitTrack.append(Func(shouldContinue, suit, suitTrack))
                suitTrack.append(
                    Func(self.setPosFromOther, breakEffect, suit,
                         Point3(0, 0, 0)))
                suitTrack.append(SoundInterval(self.hitSfx, node=suit))
                suitTrack.append(
                    Func(suit.sendUpdate, 'hitByGag', [self.getID()]))
                suitTrack.start()

        suits = None
        return
Exemple #38
0
  def doEffect(self,name,source,track = False,pos = None,quat = None):
    """Creates the particle effect with the given name. source is the node to
       appear at - if track is false its initialised here and then remains fixed
       in world space, otherwise it moves with the source node. pos and quat are
       offset's in source's local coordinate sytem for the origin."""

    # Create node to store the particle effect in...
    if track:
      n = source.attachNewNode('')
      self.prepNode(n)
    else:
      n = render.attachNewNode('')
      self.prepNode(n)

      n.setPos(render,source.getPos(render))
      n.setQuat(render,source.getQuat(render))

    # Handle local offset/rotation...
    if pos!=None:
      n.setPos(n,pos)
    if quat!=None:
      n.setQuat(n,quat)

    # Create the particle effect...
    p = ParticleEffect()
    p.loadConfig(Filename(self.pdb[name]['file']))
    p.start(n)

    # Store effect in the effect database...
    self.effects[id(p)] = (p,n)

    # If the effect has a finite life arrange for it to be terminated...
    if self.pdb[name]['life']!=None:
      def kill(p):
        if self.effects.has_key(id(p)):
          pn = self.effects[id(p)]
          pn[0].cleanup()
          pn[0].remove_node()
          pn[1].removeNode()
          del self.effects[id(p)]
      s = Sequence(Wait(float(self.pdb[name]['life'])),Func(kill,p))
      s.start()
Exemple #39
0
class Game(ShowBase):
    '''
    '''
    def __init__(self):
        '''
        '''
        # loadPrcFileData("", "want-pstats 1\n pstats-host 127.0.0.1\n pstats-tasks 1\n task-timer-verbose 1")
        # loadPrcFileData("", "pstatshost 192.168.220.121")
        ShowBase.__init__(self)
        loadPrcFileData(
            "",
            "default-directnotify-level debug\n notify-level-x11display fatal")

        # PStatClient.connect() #activate to start performance measuring with pstats
        base.setFrameRateMeter(True)  # Show the Framerate
        # base.toggleWireframe()

        self.startGame()
        # -----------------------------------------------------------------

    # -----------------------------------------------------------------

    def startGame(self):
        '''
        Start the game
        '''

        base.enableParticles()
        # self.p = ParticleEffect()
        # self.loadParticleConfig('./data.parcticles/blowout_fire.ptf')
        # Start of the code from steam.ptf
        # self.p.cleanup()
        self.p = ParticleEffect()
        self.p.loadConfig('./data/particles/blowout_test.ptf')
        # Sets particles to birth relative to the teapot, but to render at toplevel
        self.p.start(render)
        self.p.setPos(0.000, 0.000, 0)

        # Load the Lights
        ambilight = AmbientLight('ambilight')
        ambilight.setColor(VBase4(0.2, 0.2, 0.2, 1))
        render.setLight(render.attachNewNode(ambilight))
class GameApi(DirectObject):
    def light(self):
        sun = DirectionalLight("sun")
        sun.set_color_temperature(6000)
        sun.color = sun.color * 4
        sun_path = render.attach_new_node(sun)
        sun_path.set_pos(10, -10, -10)
        sun_path.look_at(0, 0, 0)
        sun_path.hprInterval(self.sun_interval, (sun_path.get_h(), sun_path.get_p() - 360, sun_path.get_r()), bakeInStart=True).loop()
        render.set_light(sun_path)

    def object(self, path, scale, pos):
        self.object = loader.loadModel(path)
        self.object.reparentTo(render)
        self.object.setScale(scale)
        self.object.setPos(pos)

        return self.object

    def sound(self, path, volume):
        self.sound = loader.loadMusic(path)
        self.sound.setVolume(volume)

        return self.sound

    def shaders(self, vert, frag):
        render.set_shader(Shader.load(Shader.SL_GLSL, vert, frag))

    def loadParticleConfig(self, filename, pos, object):
        self.p.cleanup()
        self.p = ParticleEffect()
        self.p.loadConfig(Filename(filename))

        self.p.start(object)
        self.p.setPos(pos)

    def make_shader(self, object, pos):
        '''Про шейдер'''
        object.set_shader(self.light_shader())
        object.set_shader_input('pos_light', pos)
Exemple #41
0
 def mouBala(bala, balaImage, vel, queue, task):
     if task.time > 3:
         balaImage.detachNode()
         expbala = ParticleEffect()
         expbala.reparentTo(self.particlesDummy)
         expbala.loadConfig("explosio.ptf")
         expbala.start(bala)
         taskMgr.doMethodLater(0.25, suprimir, "suprimir", extraArgs=[bala, expbala])
         return task.done
     if queue.getNumEntries() != 0:
         balaImage.detachNode()
         entry = queue.getEntry(0)
         bala.setPos(entry.getSurfacePoint(self.particlesDummy))
         expbala = ParticleEffect()
         expbala.reparentTo(self.particlesDummy)
         expbala.loadConfig("explosio.ptf")
         expbala.start(bala)
         taskMgr.doMethodLater(0.25, suprimir, "suprimir", extraArgs=[bala, expbala])
         return task.done
     bala.setFluidPos(bala, 0, vel * globalClock.getDt(), 0)
     balaImage.setR(balaImage, 1000 * globalClock.getDt())
     return task.cont
Exemple #42
0
  def doEffect(self,name,source,track = False,pos = None,quat = None):
    """Creates the particle effect with the given name. source is the node to appear at - if track is false its initialised here and then remains fixed in world space, otherwise it moves with the source node. pos and quat are offset's in source's local coordinate sytem for the origin."""

    # Create node to store the particle effect in...
    if track:
      n = source.attachNewNode('')
      self.prepNode(n)
    else:
      n = render.attachNewNode('')
      self.prepNode(n)
      
      n.setPos(render,source.getPos(render))
      n.setQuat(render,source.getQuat(render))

    # Handle local offset/rotation...
    if pos!=None:
      n.setPos(n,pos)
    if quat!=None:
      n.setQuat(n,quat)

    # Create the particle effect...
    p = ParticleEffect()
    p.loadConfig(Filename(self.pdb[name]['file']))
    p.start(n)
    
    # Store effect in the effect database...
    self.effects[id(p)] = (p,n)

    # If the effect has a finite life arrange for it to be terminated...
    if self.pdb[name]['life']!=None:
      def kill(p):
        if self.effects.has_key(id(p)):
          pn = self.effects[id(p)]
          pn[0].cleanup()
          pn[0].remove()
          pn[1].removeNode()
          del self.effects[id(p)]
      s = Sequence(Wait(float(self.pdb[name]['life'])),Func(kill,p))
      s.start()
Exemple #43
0
    def _shot(self):
        """Make a cluster howitzer shot."""
        self.change_state()
        base.ignore("3")  # noqa: F82

        rocket = loader.loadModel(address("cluster_rocket"))  # noqa: F82
        rocket.reparentTo(self._model)
        rocket.setPos(0, -0.325, 0.3)
        rocket.setP(20)

        smoke = ParticleEffect()
        smoke.loadConfig("effects/smoke_tail.ptf")
        smoke.start(rocket, render)  # noqa: F821

        hiss_snd = base.sound_mgr.loadSfx("sounds/rocket_fly.ogg")  # noqa: F821
        base.sound_mgr.attachSoundToObject(hiss_snd, rocket)  # noqa: F821
        hiss_snd.play()

        open_snd = base.sound_mgr.loadSfx("sounds/cluster_open.ogg")  # noqa: F821
        base.sound_mgr.attachSoundToObject(open_snd, rocket)  # noqa: F821

        Sequence(
            Parallel(
                LerpPosInterval(rocket, 2, (0, 1.8, 3)),
                LerpHprInterval(rocket, 2, (0, 80, 0)),
            ),
            SoundInterval(open_snd),
            Func(self._clear_rocket, rocket, smoke, hiss_snd),
            Func(self._bombs_down),
        ).start()

        taskMgr.doMethodLater(  # noqa: F82
            45,
            base.accept,  # noqa: F82
            "unblock_cluster_launcher",
            extraArgs=["3", self.change_state],
        )
        base.train.make_shot("Cluster Howitzer")  # noqa: F82
Exemple #44
0
    def __init__(self):
        self._train_pos = base.train.root_node.getPos()  # noqa: F821
        self._mod = loader.loadModel(address("city_hangar"))  # noqa: F821

        base.camera_ctrl.set_hangar_pos(self._mod)  # noqa: F821

        self._mod.reparentTo(base.train.model)  # noqa: F821

        lens = PerspectiveLens()
        lens.setNearFar(0, 10)
        lens.setFov(100, 100)

        lighter = Spotlight("hangar_light")
        lighter.setColor((1, 1, 1, 1))
        lighter.setLens(lens)
        self._lighter_np = self._mod.attachNewNode(lighter)
        self._lighter_np.setPos(-0.3, 0.65, 4)
        self._lighter_np.lookAt(base.train.model)  # noqa: F821

        render.setLight(self._lighter_np)  # noqa: F821

        flies = ParticleEffect()
        flies.loadConfig("effects/flies.ptf")
        flies.setPos(-0.465, 0.11, 0.17)
        flies.start(self._mod, render)  # noqa: F821

        lens = PerspectiveLens()
        lens.setNearFar(0, 50)
        lens.setFov(80, 80)

        lamp = Spotlight("hangar_light")
        lamp.setColor((0.7, 0.7, 0.7, 1))
        lamp.setLens(lens)
        lamp.setExponent(0.002)
        self._lamp_np = self._mod.attachNewNode(lamp)
        self._lamp_np.setPos(-0.47, 0.11, 0.195)
        self._lamp_np.setHpr(-180, -60, 0)
        render.setLight(self._lamp_np)  # noqa: F821
Exemple #45
0
    def damageCogsNearby(self, radius = None):
        if not radius:
            radius = self.soundRange
        suits = []
        for obj in base.cr.doId2do.values():
            if obj.__class__.__name__ == 'DistributedSuit':
                if obj.getPlace() == base.localAvatar.zoneId:
                    if obj.getDistance(self.avatar) <= radius:
                        if self.avatar.doId == base.localAvatar.doId:
                            suits.append(obj)

        def shouldContinue(suit, track):
            if suit.isDead():
                track.finish()

        for suit in suits:
            if self.name != CIGlobals.Opera:
                self.avatar.sendUpdate('suitHitByPie', [suit.doId, self.getID()])
            else:
                breakEffect = ParticleEffect()
                breakEffect.loadConfig('phase_5/etc/soundBreak.ptf')
                breakEffect.setDepthWrite(0)
                breakEffect.setDepthTest(0)
                breakEffect.setTwoSided(1)
                suitTrack = Sequence()
                if suit.isDead():
                    return
                suitTrack.append(Wait(2.5))
                delayTime = random.random()
                suitTrack.append(Wait(delayTime + 2.0))
                suitTrack.append(Func(shouldContinue, suit, suitTrack))
                suitTrack.append(Func(self.setPosFromOther, breakEffect, suit, Point3(0, 0, 0)))
                suitTrack.append(SoundInterval(self.hitSfx, node=suit))
                suitTrack.append(Func(self.avatar.sendUpdate, 'suitHitByPie', [suit.doId, self.getID()]))
                suitTrack.start()

        suits = None
        return
Exemple #46
0
    def _bombs_down(self):
        """Move bombs down to the ground and do explosion."""
        move_par = Parallel()
        for num in range(4):
            bomb = loader.loadModel(address("hand_bomb1"))  # noqa: F82
            bomb.reparentTo(self._train_mod)
            bomb.setPos(*self._coors[num], 2)
            bomb.setScale(2)

            smoke = ParticleEffect()
            smoke.loadConfig("effects/smoke_tail.ptf")
            smoke.start(bomb, render)  # noqa: F821

            self._bombs.append((bomb, smoke))
            move_par.append(
                LerpPosInterval(
                    bomb, random.uniform(0.45, 0.7), (*self._coors[num], 0)
                ),
            )

        Sequence(
            move_par, Func(self._clear_grenades), Func(self._explode_grenades),
        ).start()
Exemple #47
0
class BurnSmoke:
    """Smoke from a burning object effect.

    Args:
        parent (object): Object to parent the effect to.
    """

    def __init__(self, parent):
        self._parent = parent
        self._smoke = ParticleEffect()
        self._smoke.loadConfig("effects/after_explode_smoke1.ptf")

    def _clear_smoke(self, task):
        """Clear the smoke effect."""
        self._smoke.softStop()
        self._smoke.cleanup()
        return task.done

    def play(self):
        """Start playing the particle effect."""
        self._smoke.start(self._parent.model, render)  # noqa: F821
        taskMgr.doMethodLater(  # noqa: F821
            11, self._clear_smoke, self._parent.id + "_stop_smoke"
        )
Exemple #48
0
class Saucer(DirectObject):
    def __init__(self):
    
        self.ship = loader.loadModel("Art\ufo.egg")
        self.beam = loader.loadModel("Art\eam.egg")
        self.health = 100
      
        #Dummy is used to position the tractor beam collisionsphere
        self.dummy = NodePath('dummy')
        self.dummy.reparentTo(render)
        
        #Dummy2 used to position abductees
        self.dummy2 =  NodePath('dummy2')
        self.dummy2.reparentTo(render)

        self.beam.reparentTo(self.dummy2)
        
        self.glownode = self.ship.find("**/l_glownode")
        self.glownode.setColor(0,0,.5,1)
        
        self.glownode2 = self.ship.find("**/r_glownode")
        self.glownode2.setColor(0,0,.5,1)
            
        self.ship.reparentTo(render)
        self.ship.setScale(1)
        #self.ship.setH(180)
        self.ship.setPos(0,0,25)
        self.dummy.setPos(0,0,25)
        self.dummy2.setPos(0,0,25)
        
        #list of things currently abducting
        self.abductlist = []
        self.animals = []
        self.inanimates = []
        taskMgr.add(self.abductTask, "abductTask")
        taskMgr.add(self.lightTask, "lightTask")
        self.stuntime = 30
        self.stunbase = 30
        self.updown = False
        self.beamspeed = 1
        self.basebeamspeed = 2
        
        self.collected = 0
        
        self.beamon = True
        
        taskMgr.add(self.particleTask, "shipparticleTask")

        self.mydir = os.path.abspath(sys.path[0])
        self.mydir = Filename.fromOsSpecific(self.mydir).getFullpath()
        self.mydir = Filename(self.mydir)
        #self.mydir = self.mydir.toOsSpecific()
        
        self.abductp = ParticleEffect()
        self.abductp.loadConfig(self.mydir + '/abduct.ptf')
        self.pcount = 0
        self.particletime = 60 #Must be integer 

    def pickUp(self,object):   #Pick up another pickupable 
        if object.stuncount < self.stuntime:
            object.stunned = True
        else:
            if (len(self.abductlist) < 15):
                if object.type1 == 'inanimate':
                    self.inanimates.append(object)
                elif object.type1 == 'hostile':
                    self.inanimates.append(object)
                elif object.type1 == 'animal':
                    self.animals.append(object)
                    
                self.findSpeed()
                
                object.resetStun()
                object.abduct = True
                self.abductlist.append(object)
                object.playPickupSound()
                object.pickup.reparentTo(self.dummy2)
                object.pickup.setHpr(0,0,0)
                object.pickup.setPos(0,0,-37)
            else:
                print ("Pickup list full.")
    
    def drop(self,env): #Drop all
        for object in self.abductlist:
            object.abduct = False
            object.pickup.wrtReparentTo(env)
            #object.pickup.setPos(self.dummy2.getX(),self.dummy2.getY(),self.dummy2.getZ())
        self.abductlist[:] = []
 
    def lightTask(self,task):
        if not self.beamon:
            self.glownode.setColor(.1,.06,.92,1)
            self.glownode2.setColor(.1,.06,.92,1)
        if self.beamon:
            s = self.beamspeed/25     
            self.glownode.setColor(.12 - s/10,1 - s,.08 - s/10,1)
            self.glownode2.setColor(.12 - s/10,1 - s,.08- s/10,1)
        return task.cont
            
    def abductTask(self,task):
        if self.updown:
            self.dummy.setZ(self.ship.getZ())
            self.updown = False
        else:
            self.dummy.setZ(36)
            self.updown = True
    
        for obj in self.abductlist:
            obj.rise(self)
            
        return Task.cont

    def cowbig(self,me):
        if me > self.panda and me > self.pigs and me > self.sheep:
            return True
    def pigbig(self,me):
        if me > self.cows and me > self.sheep and me > self.panda:
            return True
    def sheepbig(self,me):
        if me > self.cows and me > self.pigs and me > self.panda:
            return True
    def pandabig(self,me):
        if me > self.cows and me > self.pigs and me > self.sheep:
            return True            


    def biggest(self):
        if self.cowbig(self.cows):
            return self.cows - ((self.pigs + self.sheep + self.panda) / 3)
        if self.pigbig(self.pigs):
            return self.pigs - ((self.cows + self.sheep + self.panda) / 3)
        if self.sheepbig(self.sheep):
            return self.sheep - ((self.pigs + self.cows + self.panda) / 3)
        if self.pandabig(self.panda):
            return self.panda - ((self.pigs + self.sheep + self.cows) / 3)
          
        return 0
        
    def findSpeed(self):
        self.cows = 0
        self.pigs = 0
        self.sheep = 0
        self.panda = 0
        for animal in self.animals:
            if animal.type2 == 'cow':
                self.cows += 1
            if animal.type2 == 'pig':
                self.pigs += 1
            if animal.type2 == 'sheep':
                self.sheep += 1
            if animal.type2 == 'panda':
                self.panda += 1
        
        speedadd = self.biggest() * 1.7
        
        speeddeduct = len(self.inanimates)
        self.beamspeed = self.basebeamspeed - speeddeduct + speedadd
        self.stuntime = self.stunbase - (self.beamspeed * 1.5)
        
        if self.stuntime < 2:
            self.stuntime = 2
        
        #Minimum beam speed
        if self.beamspeed < 2:
            self.beamspeed = 2
            
    def abductAnimal(self):
        self.pcount = self.particletime
        #self.abductp.start(parent = self.ship, renderParent = self.ship)
        self.collected += 1

        
    def particleTask(self,task):
        if self.pcount > 0:
            self.pcount -= 1
        elif self.pcount == 0:
            self.pcount = -1
            self.abductp.reset()
            self.abductp.disable()
            
        return task.cont
Exemple #49
0
class Vehicle(Actor):

    BACKWARDS = -1
    STOPPED = 0
    FORWARDS = 1

    def __init__(self, modelStr, driveStr, world):
        Actor.__init__(self, modelStr, {"drive": driveStr})
        self.world = world
        self.setScale(0.005)
        self.setH(180)
        self.reparentTo(render)
        self.prevtime = 0
        # some movement stats
        self.accel = 40.0
        self.deccel = -40.0
        self.bkwdsAccel = -10.0
        self.speed = 0.0
        self.maxSpeed = 100.0
        self.maxBkwdsSpeed = -40.0
        self.direction = Vehicle.STOPPED
        self.isTurning = False
        self.turnFactor = 4.0

    def setupBooster(self):
        # Booster Stuff
        self.boosters = ParticleEffect()
        self.boosterStartTime = -1
        self.boosterLight = PointLight("boostlight")
        self.boosterLight.setColor(VBase4(0, 0, 0, 1))
        self.boosterLight.setAttenuation(Point3(0, 0.001, 0.001))
        self.world.boosterLightNP = self.attachNewNode(self.boosterLight)
        self.world.boosterLightNP.setPos(0, 500, 275)
        self.world.boosterLightNP.setHpr(180, 90, 0)
        self.world.boosterLightNP.setScale(200)
        self.world.setWorldLight(self)

    def addKeyMap(self, keyMap):
        self.keyMap = keyMap
        keyMap["boost"] = 0

    def move(self, task):
        elapsed = task.time - self.prevtime

        startpos = self.getPos()  # Initial position
        wasMoving = self.isTurning or (self.direction != Vehicle.STOPPED)

        if self.speed > 0:
            self.direction = Vehicle.FORWARDS
        if self.speed == 0:
            self.direction = Vehicle.STOPPED
        if self.speed < 0:
            self.direction = Vehicle.BACKWARDS

        # Deal with turning
        if self.keyMap["left"]:
            self.setH(self.getH() + elapsed * self.speed * self.turnFactor)
            if self.direction != Vehicle.STOPPED:
                self.isTurning = True
        elif self.keyMap["right"]:
            self.setH(self.getH() - elapsed * self.speed * self.turnFactor)
            if self.direction != Vehicle.STOPPED:
                self.isTurning = True
        else:
            self.isTurning = False

        # Accelerating
        if (self.keyMap["forward"] and not self.keyMap["backwards"]) or self.keyMap["boost"]:
            if self.direction == Vehicle.BACKWARDS:
                newSpeed = self.speed + (self.accel - self.deccel) * elapsed
            else:
                newSpeed = self.speed + self.accel * elapsed
            if newSpeed > self.maxSpeed:
                self.speed = self.maxSpeed
            else:
                self.speed = newSpeed

        # Braking/Reversing
        if self.keyMap["backwards"] and not (self.keyMap["forward"] or self.keyMap["boost"]):
            if self.direction == Vehicle.FORWARDS:
                newSpeed = self.speed + (self.bkwdsAccel + self.deccel) * elapsed
            else:
                newSpeed = self.speed + self.bkwdsAccel * elapsed
            if newSpeed < self.maxBkwdsSpeed:
                self.speed = self.maxBkwdsSpeed
            else:
                self.speed = newSpeed

        # Even if no key is held down, we keep moving!
        if (not self.keyMap["forward"] and not self.keyMap["backwards"] and not self.keyMap["boost"]) or (
            self.keyMap["forward"] and self.keyMap["backwards"] and self.keyMap["boost"]
        ):
            if self.direction == Vehicle.FORWARDS:
                newSpeed = self.speed + self.deccel * elapsed
            else:
                newSpeed = self.speed - self.deccel * elapsed

            if self.direction == Vehicle.FORWARDS:
                if newSpeed < 0:
                    self.speed = 0
                else:
                    self.speed = newSpeed
            if self.direction == Vehicle.BACKWARDS:
                if newSpeed > 0:
                    self.speed = 0
                else:
                    self.speed = newSpeed

        # Now actually change position
        if self.direction != Vehicle.STOPPED:
            dist = self.speed * elapsed
            angle = deg2Rad(self.getH())
            dx = dist * math.sin(angle)
            dy = dist * -math.cos(angle)
            # self.setPos(self.getX() + dx, self.getY() + dy, self.getZ())
            self.setX(self.getX() + dx)
            self.setY(self.getY() + dy)

        # Next, activate animation if necessary
        isMoving = self.isTurning or (self.direction != Vehicle.STOPPED)
        if not wasMoving and isMoving:
            self.loop("drive")
        elif not isMoving:
            self.stop()
            self.pose("drive", 4)

        # Collisions! Yay?
        print "(%i, %i, %i)" % (self.getX(), self.getY(), self.getZ())
        base.cTrav.traverse(self.world.env)
        # print "(%i, %i, %i)"%(self.getX(), self.getY(), self.getZ())
        # Grab our collision entries
        # entries = []
        # for i in range(self.world.playerGroundHandler.getNumEntries()):
        # entry = self.world.playerGroundHandler.getEntry(i)
        # entries.append(entry)
        # This code got copied from Roaming Ralph
        # entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ()))
        # if (len(entries)>0) and (entries[0].getIntoNode().getName() == "terrain"):
        # self.setZ(entries[0].getSurfacePoint(render).getZ())
        # if (len(entries)>0):
        # print "Hahahaha, nooope"
        # self.setPos(startpos)

        self.prevtime = task.time
        return Task.cont

    def collider(self, cEntry):
        pass

    def startBoosters(self):
        if self.boosterStartTime == -1:
            self.boosters.loadConfig(Filename("flamethrower4.ptf"))
            self.boosters.start(self)
            self.boosters.setPos(0, 200, 275)
            self.boosters.setHpr(180, 90, 0)
            self.boosters.setScale(200)
            self.boosters.setLightOff()
            self.accel = self.accel * 2
            self.keyMap["boost"] = 1
            self.boosterLight.setColor(VBase4(MAX_LIGHT, MAX_LIGHT, MAX_LIGHT, 1))
            taskMgr.add(self.checkBoosterEnd, "endBoosters")

    def checkBoosterEnd(self, task):
        if self.boosterStartTime == -1:
            self.boosterStartTime = task.time
            elapsed = 0
        else:
            elapsed = task.time - self.boosterStartTime

        if elapsed > BOOSTER_LENGTH:
            self.boosterLight.setColor(VBase4(0, 0, 0, 1))
            self.boosters.softStop()
            self.accel = self.accel / 2
            self.keyMap["boost"] = 0
            self.boosterStartTime = -1
            return Task.done
        else:
            return Task.cont
Exemple #50
0
class PipeWires:
    """
    Creates self contained pipe objects with methods that create,
    reference, and destroy models, collision tubes, lights,
    particles, and ActionCommand sequences.
    """



    def __init__(self):

        #SoundIntervals
        #base = ShowBase()
        self.sound = loader.loadSfx("../audio/sparks.wav")
        self.sound.setLoop(True)
        self.sound.play()

        #pick file
        self.fileName = "../models/tunnelwires"
        
        #load model
        self.model = loader.loadModel(self.fileName)
        self.model.setScale(.0175)
        #print self.model.ls()

        self.nodePath = NodePath(self.model)
        self.model.reparentTo(render)
        self.key = self.model.getKey()


        ##self.addModel(bag)
        self.addPointLight(self.model)
        self.shaderEnabled = 0
        #self.addShader()        
        #self.addCollision()
        ##self.addParticle(self.model)

        base.enableParticles()

        self.particle = ParticleEffect()
        self.loadParticleConfig('../models/', 'spark.ptf')
        #self.loadParticleConfig("spark.ptf")

        self.addActionCommand("ru")
        self.type = "wires"

        #rotate by 0, 90, 180, or 270 degrees
        self.model.setR(random.randint(0,3)*90)
        #print self.model.getR()

    def addPointLight(self, pipe):
        """create a point light for pipe"""

        #The redpoint light and helper
        #RED
        # r = random.uniform(700, 900) / 1000
        # g = random.uniform(0, 300) / 1000
        # b = g

        #ORANGE
        r = 1
        b = random.randint(0,91)
        g = (b / 2) + 102
        b = b / 255.0
        g = g / 255.0
        self.helper = loader.loadModel("../models/sphere.egg.pz")

        self.helper.setColor( Vec4( r, g, b, 1 ) )
        self.helper.setPos(pipe.getPos())
        #print self.helper.getColor()

        #This is value is irrelevent at the moment unless I move the lights
        self.helper.setScale(.25*1) #must be greater than 0.001


        #optionally set location of light within pipe
        self.helper.setY(self.helper.getY()-50*35 ) #moves to inbetween segments
        self.helper.setZ(self.helper.getZ()-50*6 ) #makes 3 sided lights

        self.light = self.helper.attachNewNode( PointLight( "self.light" ) )
        self.light.node().setAttenuation( Vec3( .1, 0.04, 0.1 )/2.5 )
        self.light.node().setColor( Vec4( r, g, b, 1 ) )
        self.light.node().setSpecularColor( Vec4( 1 ) )
        self.helper.reparentTo( pipe )
        render.setLight( self.light )
        ###
        self.h = loader.loadModel("../models/sphere.egg.pz")
        self.h.setPos(0, -300, 200)
        self.h.setScale(.25*1)
        self.spl = self.h.attachNewNode( Spotlight( "self.spl") )
        self.spl.node().setColor( Vec4( 5, 5, 5, 1 ) )
        #self.spl.node().setAttenuation( Vec3( 0.003, 0.003, 0.003 ) )
        self.spl.lookAt(0, 20, -200)
        
        self.h.reparentTo( pipe)
        render.setLight( self.spl)
        

    ###def addModel(self, bag):
        """Adds the model to the pipe object"""        
        ####moved to init for some reason


    def addShader(self):
        self.model.setShaderAuto()
        self.shaderEnabled = 1


    def addCollision(self):
        #Finding and adding collision tube to the pipe
        #cSphere = CollisionSphere((200,0,0), 100)
        cNode = self.nodePath.find("**/tube_collision").node()
        #cNode = CollisionNode("pipeCollision")
        #cNode.addSolid(solid)
        self.collision = self.model.attachNewNode(cNode)
        self.collision.show()


    def loadParticleConfig(self, path, file):
        #Start of the code from steam.ptf
        self.particle.cleanup()
        self.particle = ParticleEffect()
        self.particle.loadConfig(Filename(path, file))
        #Sets particles to birth relative to the teapot, but to render at toplevel
        self.particle.start(self.model)
        self.particle.setScale(100)
        self.particle.setPos(0.00, -200.000, -200.00)



    def addActionCommand(self, command):
        self.actionCommand = ActionCommand(command.__len__(), command, command)


    def destroy(self):
        #Remove particles from particle list
        #Idea: Instead of deleting particle effects, try moving them
        #to new pipe segment?
        # self.particle.cleanup()
        # self.particle.removeNode()

        #stop sound
        self.sound.setLoop(False)
        self.sound.stop()

        #remove pointLight from segment
        render.clearLight(self.light)
        render.clearLight(self.spl)
        #render.clearLight(self.plight)
        self.helper.removeNode()

        #remove pipe segment
        self.model.removeNode()

    def reactivate(self, pipe):
        print pipe.nodePath.ls()
        print "\n\n\n\n"
        self.model = pipe.model
        self.helper = pipe.helper
        self.light = pipe.light.node()
        self.shaderEnabled = 0
        self.collision = pipe.collision.node()
        #self.particle = pipe.particle
        
        #rotate by 0, 90, 180, or 270 degrees
        self.model.setR(random.randint(0,3)*90)

    def recycle(self):
        #rotate by 0, 90, 180, or 270 degrees
        self.model.setR(random.randint(0,3)*90)

        #ORANGE
        r = 1
        b = random.randint(0,91)
        g = (b / 2) + 102
        b = b / 255.0
        g = g / 255.0
        self.helper.setColor( Vec4( r, g, b, 1 ) )
        self.light.node().setColor( Vec4( r, g, b, 1 ) )
        self.actionCommand.resetCommand()

    def isCommandEmpty(self):
        print "LETS FIND OUT"
        return self.actionCommand.isEmpty()
Exemple #51
0
class Arena:
    def __init__(self, arenaNr):
        arenaPath = "levels/arena%d/" % arenaNr
        self.arena = loader.loadModel(arenaPath + "arena")
        self.arena.setScale(2)
        self.arena.reparentTo(render)
        self.arena.hide()

        ambientLight = AmbientLight("ambient_light")
        ambientLight.setColor((0.2, 0.2, 0.2, 1))
        self.alnp = render.attachNewNode(ambientLight)

        sunLens = PerspectiveLens()
        sunLens.setFilmSize(50)
        sun = DirectionalLight("sun")
        sun.setColor((1, 1, 1, 1))
        sun.setShadowCaster(True, 2048, 2048)
        sun.setScene(render)
        #sun.showFrustum()

        self.ambientSound = None
        self.levelParticles = None
        if arenaNr == 1:
            sunLens.setNearFar(25,45)
            sun.setLens(sunLens)
            self.sunNp = render.attachNewNode(sun)
            self.sunNp.setPos(-10, -10, 30)
            self.sunNp.lookAt(0,0,0)

            self.ambientSound = loader.loadSfx("assets/audio/ambientLevel1.ogg")
            self.ambientSound.setLoop(True)

            self.fog = Fog("Outside Fog")
            self.fog.setColor(0.3,0.3,0.5)
            self.fog.setExpDensity(0.025)

            self.levelParticles = ParticleEffect()
            self.levelParticles.loadConfig("assets/fx/Leafs.ptf")
            self.levelParticles.start(parent = render2d, renderParent = render2d)
        elif arenaNr == 2:
            sunLens.setFov(120, 40)
            sunLens.setNearFar(2,10)
            sun.setLens(sunLens)
            self.sunNp = render.attachNewNode(sun)
            self.sunNp.setPos(0, 0, 5)
            self.sunNp.lookAt(0,0,0)

            self.fog = Fog("Temple Fog")
            self.fog.setColor(0,0,0)
            self.fog.setExpDensity(0.065)

    def start(self):
        self.arena.show()
        render.setLight(self.alnp)
        render.setLight(self.sunNp)
        if self.ambientSound != None:
            self.ambientSound.play()
        render.setFog(self.fog)

    def stop(self):
        self.arena.hide()
        render.clearLight()
        if self.ambientSound != None:
            self.ambientSound.stop()
        render.clearFog()
        if self.levelParticles != None:
            self.levelParticles.cleanup()

    def getStartPos(self, charNr):
        if charNr == 1:
            return self.arena.find("**/StartPosA").getPos() * 2
        elif charNr == 2:
            return self.arena.find("**/StartPosB").getPos() * 2
        else:
            return (0,0,0)
Exemple #52
0
from util import *  # useful helper functions
from panda3d.core import CollisionTraverser,CollisionNode
from panda3d.core import CollisionHandlerQueue,CollisionRay
from panda3d.core import Filename,AmbientLight,DirectionalLight
from panda3d.core import PandaNode,NodePath,Camera,TextNode
from panda3d.core import Vec3,Vec4,BitMask32
from direct.gui.OnscreenText import OnscreenText
from direct.actor.Actor import Actor
from direct.particles.ParticleEffect import ParticleEffect
from direct.interval.IntervalGlobal import Sequence
from direct.showbase.ShowBase import ShowBase

import random, sys, os, math
from load import *
_FLAME = ParticleEffect()
_FLAME.loadConfig("fireish.ptf")
_ROT_VEC = (0,90,0)
SPEED = 0.5

_PIKACHU_POS = (-109, 10, -0.5)
_PIKACHU_HPR = (180, 0, 0)
_BULBASAUR_POS = (-109.57, -36.61, 0)
_BULBASAUR_HPR = ( 120, 90, 0 )
_PICHU_POS = (-104.57, 11.61, -0.5)
_PICHU_HPR = (180, 90, 0)
_CHARMANDER_POS = (-103.57, -28.39, 0.19)
_CHARMANDER_HPR = (0, 0, 0)
_GROUDON_POS = (19.57, 9.39, 3.89)
_GROUDON_HPR = ( 320, 0, 0)
_SQUIRTLE_POS = (-99.57, -33.39, 0)
_SQUIRTLE_HPR = (230, 0, 0)
Exemple #53
0
class Labryn(ShowBase):
    def setCamera(self, spin):
        # set camera spin state
        self.spin = spin

    def displayInformation(self):
        self.title = addTitle("Single Player")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[wasd]: Move")
        self.inst3 = addInstructions(0.85, "[q/e]: spin camera")
        self.inst4 = addInstructions(0.80, "[z/c]: zoom in/out")
        self.inst5 = addInstructions(0.75, "[shift]: hold and pan")
        self.inst6 = addInstructions(0.70, "[1/2/3]: use moves")
        self.inst7 = addInstructions(0.65, "[h]: hide instructions")
        self.insts = [self.title, self.inst1, self.inst2, self.inst3,
                      self.inst4, self.inst5, self.inst6, self.inst7]

    def hideInstructions(self):
        if self.instStatus == "show":
            self.instStatus = "hide"
            groupHide(self.insts)
        else: # instructions are hidden
            self.instStatus = "show"
            groupShow(self.insts)        
        
    def loadNextMusic(self, task):
        # random load background music
        if (self.music.status()!=self.music.PLAYING):
            # not playing
            self.musicCounter += 1
            index = self.musicCounter % len(_BGMUSIC)
            self.music = load_bgmusic(_BGMUSIC[index])
            self.music.play()
        return task.cont
        
    def spinCamera(self, task):
        # deal with spinning the camera
        # _FOCUS: focus point, changed by panning the camera
        # CAM_R: radius, changed by zooming
        # cameraSpinCount: amount of spinning, changed by spinning
        if self.spin == 1: # spin counter-clockwise
            self.cameraSpinCount += 1
            angleDegrees = self.cameraSpinCount
            angleRadians =  angleDegrees * (pi/ 180)
            self.CAM_RAD = angleRadians
            camera.setPos(_FOCUS[0]+self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1]+self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*self.CAM_R) 
            camera.setHpr(angleDegrees,-65,0)
        elif self.spin == 2: # spin clockwise
            self.cameraSpinCount  -= 1
            angleDegrees = self.cameraSpinCount
            angleRadians =  angleDegrees * (pi/ 180)
            self.CAM_RAD = angleRadians
            camera.setPos(_FOCUS[0]+self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1]+self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*self.CAM_R)
            camera.setHpr(angleDegrees,-65,0)
        elif self.spin == 3: # ZOOM IN not spin
            self.cameraZoomCount += 1
            deltaR = self.cameraZoomCount * 0.1
            new_R = 12-deltaR
            self.CAM_R = new_R
            camera.setPos(_FOCUS[0] + self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1] + self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*new_R)
        elif self.spin == 4: # ZOOM OUT
            self.cameraZoomCount -= 1
            deltaR = self.cameraZoomCount * 0.1
            new_R = 12-deltaR
            self.CAM_R = new_R
            camera.setPos(_FOCUS[0] + self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1] + self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*self.CAM_R)
        return Task.cont

    def takeRecord(self):
        def myCMP(aString, bString):
            a = float(aString.split(',')[0])
            b = float(bString.split(',')[0])
            return int(10*(a - b))
        
        msg = "%.2f,%s\n" %(self.clock/100.0, time.ctime())
        with open('record.txt') as f:
            data = f.readlines()
        # if has no previous data
        if len(data) == 0:
            data.append(msg)
            with open('record.txt','w') as f:
                f.writelines(data)
        else:
            data.append(msg)
            processedData = sorted(data, myCMP)
            with open('record.txt', 'w') as f:
                f.writelines(processedData)

    def printResults(self):
        addEndMessage(self.clock)
        with open('record.txt') as f:
            data = f.readlines()
        for i in xrange(0, len(data)):
            if i < 5: # only print the top 5
                string = data[i]
                printRank(i, string)
        
    def checkForWin(self, task):
        if (checkWin(self.pikachu.getX(), self.pikachu.getY(),
                    self.ballRoot.getX(), self.ballRoot.getY()) and
            self.gameOver == False):
            self.takeRecord()
            self.printResults()
            self.gameOver = True
            # if top 10, if top 1,
            print "WIN"
            # print previous best 10 results
        return Task.cont
    
    def pikachuBark(self, task):
        if self.distance < 3:
            if random.randint(1,200) == 1:
            # randomly bark dangerous sound
                if self.dangerous.status() != self.dangerous.PLAYING:
                    self.dangerous.play()
        elif self.distance > 10:
            if random.randint(1,430) == 1:
                if self.safe.status() != self.safe.PLAYING:
                    self.safe.play()
        return Task.cont
            
    def checkMouse(self, task):
        # get mouse position 
        if base.mouseWatcherNode.hasMouse():
            self.mouseX=base.mouseWatcherNode.getMouseX()
            self.mouseY=base.mouseWatcherNode.getMouseY()
        return Task.cont

    def dropRock(self):
        # when the user clicks, rock is dropped
        if self.pokeMoveChoice == 1: # selected Geodude
            result = MAZE.canDropRock(self.rockX, self.rockY)
            if result != False: # can place rock here
                MAZE.dropRock(result[0],result[1])
                self.rock.setPos(self.rockX, self.rockY, 1)
                self.rockOnMaze = True
                self.pokeMoveChoice = None
                self.myPokeName.hide()
                self.myPokeName = None
                self.updateTwoD()
                self.playerCandyCount -= 1

    def restart(self):
        sys.exit()
                
    def useFlame(self):
        # use flame to Pikachu -> cannot move
        self.onFire = True # on fire
        self.playerCandyCount -= 1
        self.pokeStatus = 1
        self.flame = ParticleEffect()
        self.flame.loadConfig("fireish.ptf")
        self.flame.setPos(self.pikachu.getPos())
        self.flame.start(parent=render, renderParent=render)
        self.updateTwoD()

    def useStringShot(self):
        # use string shot -> speed goes down
        self.pokeStatus = 2
        self.updateTwoD()

    def useThunder(self):
        self.onThunder = True
        self.pokeCandyCount -= 1
        self.thunder = ParticleEffect()
        self.thunder.loadConfig("thunder.ptf")
        self.thunder.start(parent=render, renderParent=render)
        self.use.play()
                
    def placeRock(self, task):
        # rock moves with mouse cursor
        if self.pokeMoveChoice == 1: # selected Geodude
            dX,dY = ((self.mouseX-self.rockRefX),
                     (self.mouseY-self.rockRefY))
            self.rockX, self.rockY = MAZE.translateRockPosition(self.rockRefX,
                                                      self.rockRefY,
                                                      dX, dY)
            self.rock.show()
            self.rock.setPos(self.rockX, self.rockY, 1)
        self.updateTwoD()
        return Task.cont
    
    def placeRareCandy(self, task):
        # place rare candy with interval
        # needs to be improved
        if int(task.time) % 4 == 9 and self.candyOnBoard:
            self.candy.hide()
            self.candyOnBoard = False
            MAZE.clearCandy()
        if int(task.time) % 10 ==  0 and (self.candyOnBoard == False):
            # every 10 seconds
            self.candy.setPos(MAZE.generateCandyPos())
            self.candy.show()
            self.candyOnBoard = True
        return Task.cont

    def updateTwoD(self):
        # update player candy count
        self.playerCandyStatus.destroy()
        self.playerCandyStatus = candyStatus(0, self.playerCandyCount)
        self.pokeCandyStatus.destroy()
        self.pokeCandyStatus = candyStatus(1, self.pokeCandyCount)
        # update my pokes color     
        if self.playerCandyCount == 0 :
            groupHide(self.myPokesBright)
            groupShow(self.myPokesDark)
            # update name
            if self.myPokeName != None:
                self.myPokeName.destroy()

    def clearRock(self):
        # clear rock 
        self.rock.hide()
        self.rockOnMaze = False
        MAZE.clearRock() # clear it in 2D

    def clearFlame(self):
        # clear flame
        self.onFire = False
        self.flame.cleanup()
        self.pokeStatus = 0
        self.pokeMoveChoice = None
        try:
            self.myPokeName.destroy()
        except:
            pass
        self.myPokeName = None

    def clearString(self):
        # clear string shot
        self.pokeStatus = 0
        self.pokeMoveChoice = None
        try:
            self.myPokeName.destroy()
        except:
            pass
        self.myPokeName = None

    def clearThunder(self):
        self.onThunder = False
        try:
            self.thunder.cleanup()
        except:
            pass
        
    def timer(self, task): # deals with moves' lasting effects
        ##############################################################
        self.clock += 1
        if self.rockOnMaze: # rock on maze
            self.rockCounter += 1
        elif self.rockCounter != 1: # rock not on maze, counter not cleared
            self.rockCounter = 0

        if self.onFire:
            self.fireCounter += 1
        elif self.fireCounter != 1:
            self.fireCounter = 0

        if self.pokeStatus == 2: # string shot
            self.stringCounter += 1
        elif self.stringCounter != 1:
            self.stringCounter = 0

        if self.onThunder: # thunderbolt
            self.thunderCounter += 1
        elif self.thunderCounter != 1:
            self.thunderCounter = 0

        if self.gameOver == True: # game is over
            self.gameOverCounter += 1

        ##################################################################
        if self.rockCounter >= 100:
            self.clearRock()

        if self.fireCounter >= 80:
            self.clearFlame()

        if self.thunderCounter >= 150:
            self.clearThunder()
            
        if self.stringCounter >= 120:
            self.clearString()

        if self.gameOverCounter >= 800: # quit the game
            sys.exit()
            
        return Task.cont
    
    def usePokeMove(self, number):
        # use pokemon move
        if self.playerCandyCount > 0: # have more than one candy
            if number == 1 and self.rockOnMaze == False:
                if self.pokeMoveChoice == None: # no choice
                    # set to center position
                    centerx =  base.win.getProperties().getXSize()/2
                    centery =  base.win.getProperties().getYSize()/2
                    base.win.movePointer(0,centerx,centery)
                    self.pokeMoveChoice = 1 # placeRock called here
                    self.rockRefX, self.rockRefY = 0,0
                    self.rock.show()
                    self.rock.setPos(0,0,1)
                elif self.pokeMoveChoice != 1:
                    pass

                else: # self.pokeMoveChoice is already 1, cancel the choice
                    self.pokeMoveChoice = None
                    self.clearRock() # clear rock
            elif number == 2:
                if self.pokeMoveChoice == None:
                    self.pokeMoveChoice = 2
                    self.useFlame()
                elif self.pokeMoveChoice != 2:
                    pass
                else:
                    self.pokeMoveChoice = None

            elif number == 3:
                if self.pokeMoveChoice == None:
                    self.pokeMoveChoice = 3
                    self.useStringShot()
                elif self.pokeMoveChoice != 3:
                    pass
                else: # already 3
                    self.pokeMoveChoice = None

            if self.pokeMoveChoice == None: # no choice
                if self.myPokeName != None: # there is a name on board
                    self.myPokeName.destroy() # kill it
                else: # no name
                    pass
            else: # there is a choice
                if self.myPokeName != None:
                    self.myPokeName.destroy()
                self.myPokeName = writePokeName(self.pokeMoveChoice)
  
    def loadRareCandy(self):
        # load rare candy (a box)
        # needs to be improved
        self.candy = Model_Load.loadRareCandy()
        self.candy.reparentTo(render)
        self.candy.setScale(0.1)
        self.candy.hide()
        
    def eatRareCandy(self, task):
        # check who eats candy
        if self.candyOnBoard: # candy on board
            if checkEat(self.ballRoot.getX(), self.ballRoot.getY(),
                        self.candy.getX(), self.candy.getY()): # ball eats
                self.candy.hide() # eaten
                self.candyOnBoard = False
                if self.playerCandyCount < 3:
                    self.playerCandyCount += 1
                groupShow(self.myPokesBright)
                MAZE.clearCandy()
            elif checkEatPika(self.pikachu.getX(), self.pikachu.getY(),
                          self.candy.getX(), self.candy.getY()):
                self.candy.hide()
                self.candyOnBoard = False
                if self.pokeCandyCount < 3:
                    self.pokeCandyCount += 1
                MAZE.clearCandy()                
        return Task.cont

    def setFocus(self, changing):
        # set focus of the camera while panning
        self.changingFocus = changing
        if changing == True: # Just Pressed
            self.referenceX, self.referenceY = self.mouseX, self.mouseY
        else: # cursor moves up
            self.referenceX, self.referenceY = None, None

    def resetView(self):
        # reset the view to default
        self.CAM_R, self.CAM_RAD = 12, 0
        self.cameraSpinCount, self.cameraZoomCount = 0, 0
        # _FOCUS = [0,0,0] does not work WHY???
        _FOCUS[0], _FOCUS[1], _FOCUS[2] = 0,0,0
        self.changingFocus = False
        self.referenceX, self.referenceY = None, None
        camera.setPos(_FOCUS[0], _FOCUS[1]-self.CAM_R, 25)
        camera.setHpr(0, -65, 0)
        
    def changeFocus(self, task):
        # change focus with displacement of mouse cursor
        if (self.changingFocus == True and self.mouseX != None and
            self.mouseY != None ):
            dX, dY = ((self.mouseX - self.referenceX)*0.1,
                      (self.mouseY - self.referenceY)*0.1)
            _FOCUS[0] += dX
            _FOCUS[1] += dY
            camera.setPos(_FOCUS[0] + self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1] + self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*self.CAM_R)
        return Task.cont

    def thunderbolt(self, task):
        if self.onThunder == True:
            self.thunder.setPos(self.ballRoot.getPos())
        return Task.cont

    def displayClock(self, task):
        msg = "Time: %.2f" %(self.clock/100.0)
        if self.clockMSG == None:
            self.clockMSG = OnscreenText(text=msg, style=1, fg=(1,1,1,1),
                                         pos=(1.3, .95), align=TextNode.ALeft,
                                         scale = .05)
        else:
            self.clockMSG.destroy()
            self.clockMSG = OnscreenText(text=msg, style=1, fg=(1,1,1,1),
                                         pos=(1.3, .95), align=TextNode.ALeft,
                                         scale = .05)
        return task.cont
    
    def initialize(self):
        taskMgr.stop()
        self.musicCounter, self.clock = 0, 0
        self.gameOverCounter = 0
        self.clockMSG = None
        self.music = load_bgmusic(_BGMUSIC[0])
        self.background = loadBackground()
        base.cam2dp.node().getDisplayRegion(0).setSort(-20)
        self.candyOnBoard = False
        self.playerCandyCount, self.pokeCandyCount = 0, 0
        self.gameOver = False
        self.displayInformation()
        self.instStatus = "show"
        ######################Rare Candy###############################
        pokes=['caterpie', 'charmander', 'geodude']
        self.myPokesDark = loadMyPokemon_Dark(pokes) # my pokemons
        self.myPokesBright = loadMyPokemon_Bright()
        groupHide(self.myPokesBright)
        self.loadRareCandy() # load rare candy
        ######################Camera Initialization####################
        self.CAM_R, self.CAM_RAD = 12, 0
        camera.setPos(_FOCUS[0],_FOCUS[1]-12,_FOCUS[2]+25)
        camera.setHpr(0, -65, 0)
        self.cameraSpinCount, self.cameraZoomCount = 0, 0
        self.changingFocus = False
        self.spin = 0
        #######################ICONS###################################
        self.myIcon = loadMyIcon()
        self.pokeIcon = loadPokeIcon()
        self.playerCandyStatus = candyStatus(0, self.playerCandyCount)
        self.pokeCandyStatus = candyStatus(1, self.pokeCandyCount)
        self.rareCandyImage = loadRareCandyImage()
        self.pokeRareCandyImage = loadRareCandyImage(pos=(-.3,0,-.75))
        #######################FLAMES##################################
        base.enableParticles()
        self.fireCounter = 0
        self.onFire = False
        #######################STRINGSHOT#############################
        self.stringCounter = 0
        #######################THUNDER################################
        self.thunderCounter = 0
        #######################SOUND##################################
        self.dangerous = load_sound("pikachu_d.wav")
        self.safe = load_sound("pikachu_s1.wav")
        self.use = load_sound("pikachu_u.wav")
        #######################"GLOBALS"##############################
        self.speedCounter = 0
        self.onThunder = False
        self.direction = 's'
        self.myDirection = ['zx', 'zy']
        self.rockCounter  = 0
        self.rockX, self.rockY = None, None
        self.rockOnMaze = False
        self.pokeMoveChoice = None
        self.myPokeName = None
        self.arrowKeyPressed = False
        self.pokemonDirection = 'd'
        self.mouseX, self.mouseY = None, None
        # direction the ball is going
        self.jerkDirection = None
        base.disableMouse()
        self.jerk = Vec3(0,0,0)
        self.MAZE = Model_Load.loadLabyrinth()
        Control.keyControl(self)
        self.loadPokemonLevel1()
        self.light()
        self.loadBall()
        self.pokeStatus = 0 # 0 is normal, 1 is burned, 2 is slow-speed
        ########################################ROCK###################
        self.rock = Model_Load.loadRock()
        self.rock.reparentTo(render)
        self.rock.hide() # Do not show, but load beforehand for performance
        
    def loadPokemonLevel1(self):
        self.pikachu = load_model("pikachu.egg")
        self.pikachu.reparentTo(render)
        self.pikachu.setScale(0.3)
        endPos = self.MAZE.find("**/end").getPos()
        self.pikachu.setPos(endPos)
        
    def light(self):
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))

    def loadBall(self):
        self.ballRoot = render.attachNewNode("ballRoot")
        self.ball = load_model("ball")
        self.ball.reparentTo(self.ballRoot)
        self.ball_tex = load_tex("pokeball.png")
        self.ball.setTexture(self.ball_tex,1)
        self.ball.setScale(0.8)
        # Find the collision sphere for the ball in egg.
        self.ballSphere = self.ball.find("**/ball")
        self.ballSphere.node().setFromCollideMask(BitMask32.bit(0))
        self.ballSphere.node().setIntoCollideMask(BitMask32.allOff())
        #self.ballSphere.show()
        # Now we create a ray to cast down at the ball.
        self.ballGroundRay = CollisionRay()
        self.ballGroundRay.setOrigin(0,0,10)
        self.ballGroundRay.setDirection(0,0,-1)

        # Collision solids go in CollisionNode
        self.ballGroundCol =  CollisionNode('groundRay')
        self.ballGroundCol.addSolid(self.ballGroundRay)
        self.ballGroundCol.setFromCollideMask(BitMask32.bit(1))
        self.ballGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ballGroundColNp = self.ballRoot.attachNewNode(self.ballGroundCol)
        
        # light
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.55, .55, .55, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(0,0,-1))
        directionalLight.setColor(Vec4(0.375,0.375,0.375,1))
        directionalLight.setSpecularColor(Vec4(1,1,1,1))
        self.ballRoot.setLight(render.attachNewNode(ambientLight))
        self.ballRoot.setLight(render.attachNewNode(directionalLight))
        # material to the ball
        m = Material()
        m.setSpecular(Vec4(1,1,1,1))
        m.setShininess(96)
        self.ball.setMaterial(m,1)
        
    def __init__(self):

        self.initialize()
        self.WALLS = self.MAZE.find("**/Wall.004")
        self.WALLS.node().setIntoCollideMask(BitMask32.bit(0))
        # collision with the ground. different bit mask
        #self.mazeGround = self.maze.find("**/ground_collide")
        #self.mazeGround.node().setIntoCollideMask(BitMask32.bit(1))
        self.MAZEGROUND = self.MAZE.find("**/Cube.004")
        self.MAZEGROUND.node().setIntoCollideMask(BitMask32.bit(1))

        # add collision to the rock
        cs = CollisionSphere(0, 0, 0, 0.5)
        self.cnodePath = self.rock.attachNewNode(CollisionNode('cnode'))
        self.cnodePath.node().addSolid(cs)
        self.cnodePath.node().setIntoCollideMask(BitMask32.bit(0))
        
        # CollisionTraversers calculate collisions
        self.cTrav = CollisionTraverser()
        #self.cTrav.showCollisions(render)
        #self.cTrav.showCollisions(render)
        # A list collision handler queue
        self.cHandler = CollisionHandlerQueue()
        # add collision nodes to the traverse.
        # maximum nodes per traverser: 32
        self.cTrav.addCollider(self.ballSphere,self.cHandler)
        self.cTrav.addCollider(self.ballGroundColNp,self.cHandler)
        self.cTrav.addCollider(self.cnodePath, self.cHandler)
        # collision traversers have a built-in tool to visualize collisons
        #self.cTrav.showCollisions(render)
        self.start()

    def pokemonTurn(self, pokemon, direction):
        if direction  == 'l' and self.pokemonDirection != 'l':
            self.pokemonDirection = 'l'
            pokemon.setH(-90)
        if direction  == 'r' and self.pokemonDirection != 'r':
            self.pokemonDirection = 'r'
            pokemon.setH(90)
        if direction  == 'd' and self.pokemonDirection != 'd':
            self.pokemonDirection = 'd'
            pokemon.setH(0)
        if direction  == 'u' and self.pokemonDirection != 'u':
            self.pokemonDirection = 'u'
            pokemon.setH(180)
                        
    def pokemonMove(self, pokemon, direction):
        self.pokemonTurn(pokemon, direction)
        if self.pokeStatus == 0: speed = _SPEED
        elif self.pokeStatus == 1: speed = 0
        else: # self.pokeStatus == 2
            speed = _SPEED/2.0
        if direction == 'l':
            newX = pokemon.getX() - speed
            pokemon.setX(newX)
        elif direction == 'r':
            newX = pokemon.getX() + speed
            pokemon.setX(newX)
        elif direction == 'u':
            newY = pokemon.getY() + speed
            pokemon.setY(newY)
        elif direction == 'd':
            newY = pokemon.getY() - speed
            pokemon.setY(newY)
        elif direction == "s": # stop
            pass
        
    def whereToGo(self, task):
        # this returns the direction pokemon should go
        # tell MAZE pokemon and ball's board position
        self.pokemonMove(self.pikachu, self.direction)
        MAZE.setPokeCoord(self.pikachu.getX(), self.pikachu.getY(),
                          self.pokemonDirection)
        MAZE.setBallCoord(self.ballRoot.getX(), self.ballRoot.getY())
        MAZE.sendInformation(self.myDirection, self.rockOnMaze,
                             self.onThunder, self.playerCandyCount,
                             self.pokeCandyCount, self.distance)
        # find out which direction to go
        self.direction = MAZE.getDecision()
        self.pokemonMove(self.pikachu,self.direction)
        return Task.cont

    def whatToDo(self, task):
        # determines when to use thunder
        if self.pokeCandyCount > 0: # Pikachu has candies
            decision = MAZE.useThunderDecision()
            if decision == True:
                self.useThunder()
        return Task.cont
    
    def getInformation(self, task):
        # get information on the board
        self.speedCounter += 1 # sample every other call to avoid 
        if self.speedCounter % 2 == 0:
            dX = self.ballRoot.getX() - self.oldPos[0]
            dY = self.ballRoot.getY() - self.oldPos[1]
            if dX < 0 :
                # print "going left"
                self.myDirection[0] = 'l'
            elif abs(dX) < _EPSILON:
                # print "not moving horiz"
                self.myDirection[0] = 'zx'
            else:
                # print "going right"
                self.myDirection[0] = 'r'
            if dY < 0 :
                # print "going down"
                self.myDirection[1] = 'd'
            elif abs(dY) < _EPSILON:
                # print "not moving verti"
                self.myDirection[1] = 'zy'
            else:
                # print "going up"
                self.myDirection[1] = 'u'
            self.oldPos = self.ballRoot.getPos()
        # calculate distance
        self.distance = MAZE.getDistance()
        return Task.cont
    
    def start(self):
        # maze model has a locator in it
        # self.ballRoot.show()
        self.startPos = self.MAZE.find("**/start").getPos()
        self.oldPos = self.MAZE.find("**/start").getPos()
        self.ballRoot.setPos(self.startPos) # set the ball in the pos
        self.ballV = Vec3(0,0,0) # initial velocity
        self.accelV = Vec3(0,0,0) # initial acceleration

        # for a traverser to work, need to call traverser.traverse()
        # base has a task that does this once a frame
        base.cTrav = self.cTrav

        # create the movement task, make sure its not already running
        taskMgr.remove("rollTask")
        taskMgr.add(self.placeRock, "placeRock")
        taskMgr.add(self.displayClock, "displayClock")
        taskMgr.add(self.timer, "timer")
        taskMgr.add(self.loadNextMusic, "loadNextMusic")
        taskMgr.add(self.getInformation, "getInformation")
        taskMgr.add(self.eatRareCandy, "eatRareCandy")
        taskMgr.add(self.placeRareCandy, "placeRareCandy")
        taskMgr.add(self.checkMouse, "checkMouse")
        taskMgr.add(self.spinCamera, "spinCamera")
        taskMgr.add(self.changeFocus, "changeFocus")
        taskMgr.add(self.whereToGo, "whereToGo")
        taskMgr.add(self.whatToDo, "whatToDo")
        taskMgr.add(self.moveBall, "moveBall")
        taskMgr.add(self.thunderbolt, "thunderbolt")
        taskMgr.add(self.checkForWin, "checkForWin")
        taskMgr.add(self.pikachuBark, "pikachuBark")
        self.mainLoop = taskMgr.add(self.rollTask, "rollTask")
        self.mainLoop.last = 0

    def moveBallWrapper(self, direction):
        # wrapper for moving the ball
        # needs to be improved
        if direction == False:
            self.arrowKeyPressed = False
        else:
            self.arrowKeyPressed = True
            self.jerkDirection = direction
    
    def moveBall(self, task):
        # move the ball
        # a key press changes the jerk
        direction = self.jerkDirection
        if self.arrowKeyPressed == True and self.onThunder == False:
            if direction == "u":
                self.jerk = Vec3(0,_JERK,0)
            elif direction == "d":
                self.jerk = Vec3(0,-_JERK,0)
            elif direction == "l":
                self.jerk = Vec3(-_JERK,0,0)
            elif direction == "r":
                self.jerk = Vec3(_JERK,0,0)
        elif self.onThunder == True:
            self.jerk = self.jerk
        return Task.cont        

    # collision between ray and ground
    # info about the interaction is passed in colEntry
    
    def groundCollideHandler(self,colEntry):
        # set the ball to the appropriate Z for it to be on the ground
        newZ = colEntry.getSurfacePoint(render).getZ()
        self.ballRoot.setZ(newZ+.4)

        # up vector X normal vector
        norm = colEntry.getSurfaceNormal(render)
        accelSide = norm.cross(UP)
        self.accelV = norm.cross(accelSide)

    # collision between the ball and a wall
    def wallCollideHandler(self,colEntry):
        # some vectors needed to do the calculation
        norm = colEntry.getSurfaceNormal(render) * -1
        norm.normalize()
        curSpeed = self.ballV.length()
        inVec = self.ballV/curSpeed
        velAngle = norm.dot(inVec) # angle of incidance
        hitDir = colEntry.getSurfacePoint(render) - self.ballRoot.getPos()
        hitDir.normalize()
        hitAngle = norm.dot(hitDir)
    # deal with collision cases
        if velAngle > 0 and hitAngle >.995:
            # standard reflection equation
            reflectVec = (norm * norm.dot(inVec*-1)*2) + inVec
            # makes velocity half of hitting dead-on
            self.ballV = reflectVec * (curSpeed * (((1-velAngle)*.5)+.5))
            # a collision means the ball is already a little bit buried in
            # move it so exactly touching the wall
            disp = (colEntry.getSurfacePoint(render) -
                    colEntry.getInteriorPoint(render))
            newPos = self.ballRoot.getPos() + disp
            self.ballRoot.setPos(newPos)
            
    def rollTask(self,task):
        # standard technique for finding the amount of time
        # since the last frame
        dt = task.time - task.last
        task.last = task.time
        # If dt is large, then there is a HICCUP
        # ignore the frame
        if dt > .2: return Task.cont
        # dispatch which function to handle the collision based on name
        for i in range(self.cHandler.getNumEntries()):
            entry = self.cHandler.getEntry(i)
            name = entry.getIntoNode().getName()
            if name == "Wall.004":
                self.wallCollideHandler(entry)
            elif name=="Cube.004":
                self.groundCollideHandler(entry)
            else:
                if self.rockOnMaze == True:
                    self.wallCollideHandler(entry)
                    
        self.accelV += self.jerk
        # move the ball, update the velocity based on accel
        self.ballV += self.accelV * dt * ACCELERATION
        # clamp the velocity to the max speed
        if self.ballV.lengthSquared() > MAX_SPEED_SQ:
            self.ballV.normalize()
            self.ballV *= MAX_SPEED
        # update the position
        self.ballRoot.setPos(self.ballRoot.getPos() + (self.ballV*dt))

        # uses quaternion to rotate the ball
        prevRot = LRotationf(self.ball.getQuat())
        axis = UP.cross(self.ballV)
        newRot = LRotationf(axis, 45.5 * dt * self.ballV.length())
        self.ball.setQuat(prevRot * newRot)
        return Task.cont # continue the task     
Exemple #54
0
def loadParticle(phase, name):
    particle = ParticleEffect()
    particle.loadConfig('phase_%s/etc/%s.ptf' % (str(phase), name))
    return particle
Exemple #55
0
class World(DirectObject):
	def __init__(self):
		#sys.path.append('../game')
		#Standard title and instruction text
		self.title = OnscreenText(
			text="PSG: Test - Explosion",
			style=1, fg=(1,1,1,1), pos=(0.9,-0.95), scale = .07)
		self.escapeEvent = OnscreenText(
			text=HELPTEXT,
			style=1, fg=(1,1,1,1), pos=(-1.3, 0.95),
			align=TextNode.ALeft, scale = .05)

		#More standard initialization
		self.accept('escape', sys.exit)
		self.accept('1', self.loadParticleConfig , ['explosion1.ptf'])
		self.accept('2', self.loadParticleConfig , ['explosion2.ptf'])
		self.accept('3', self.loadParticleConfig , ['explosion3.ptf'])
		self.accept('4', self.loadParticleConfig , ['explosion4.ptf'])
		self.accept('5', self.loadParticleConfig , ['explosion5.ptf'])
		self.accept('6', self.loadParticleConfig , ['explosion6.ptf'])
		
		self.accept('escape', sys.exit)
		base.disableMouse()
		camera.setPos(0,-20,2)
		base.setBackgroundColor( 0, 0, 0 )

		#This command is required for Panda to render particles
		base.enableParticles()
		self.t = loader.loadModel("../data/models/ship_03.egg")
		self.t.setScale(0.5)
		self.t.setHpr(180, 0, 0)
		self.t.setPos(0,10,0)
		self.t.reparentTo(render)
		self.setupLights()
		self.p = ParticleEffect()
		self.loadParticleConfig('explosion1.ptf')

	def loadParticleConfig(self,file):
		#Start of the code from steam.ptf
		self.p.cleanup()
		self.p = ParticleEffect()
		self.p.loadConfig(Filename(file))        
		#Sets particles to birth relative to the teapot, but to render at toplevel
		self.p.start(self.t)
		self.p.setPos(0.000, 0.000, 0.00)
	
	#Setup lighting
	def setupLights(self):
		lAttrib = LightAttrib.makeAllOff()
		ambientLight = AmbientLight( "ambientLight" )
		ambientLight.setColor( Vec4(.6, .6, .55, 1) )
		lAttrib = lAttrib.addLight( ambientLight )
		directionalLight = DirectionalLight( "directionalLight" )
		directionalLight.setDirection( Vec3( 0, 8, -2.5 ) )
		directionalLight.setColor( Vec4( 0.9, 0.8, 0.9, 1 ) )
		lAttrib = lAttrib.addLight( directionalLight )
		#set lighting on teapot so steam doesn't get affected
		#self.t.attachNewNode( directionalLight.upcastToPandaNode() )
		self.t.attachNewNode( directionalLight ) 
		#self.t.attachNewNode( ambientLight.upcastToPandaNode() )
		self.t.attachNewNode( ambientLight) 
		self.t.node().setAttrib( lAttrib )
Exemple #56
0
class Effects(ShowBase):
	def __init__(self):
		#ShowBase.__init__(self)
		
		#################fulscreen###############
		root = Tkinter.Tk()
		w = root.winfo_screenwidth()
		h = root.winfo_screenheight()
		props = WindowProperties() 
		props.setSize(w, h) 
		base.win.requestProperties(props)
		#################end####################3
		
		
		#camera.setPos(-500,-80,0)
		base.enableParticles()
		self.txt = ""
		self.p = ParticleEffect()
		
		st_x = 5.0 ####-515,-60,0
		st_y = 8.0
		st_z = 0.0
		
		
		self.c2 = Actor('Models/dancer/dancer')#Actor("Models/cat-humans/bvw-f2004--eve-egg/bvw-f2004--eve/eve",{"run":"Models/cat-humans/bvw-f2004--eve-egg/bvw-f2004--eve/eve-run",	"jump":"Models/cat-humans/bvw-f2004--eve-egg/bvw-f2004--eve/eve-jump",	"offbalance":"Models/cat-humans/bvw-f2004--eve-egg/bvw-f2004--eve/eve-offbalance",	"tireroll":"Models/cat-humans/bvw-f2004--eve-egg/bvw-f2004--eve/eve-tireroll"})
		self.c2.setPos(offset_x+st_x,offset_y+st_y+7,offset_z+st_z)
		self.c2.reparentTo(render)
		self.c2.loadAnims({'win':'Models/dancer/dancer'})
		self.c2.loop('win')
		
		'''self.tex = Texture()
		self.tex.setMinfilter(Texture.FTLinear)
		base.win.addRenderTexture(self.tex, GraphicsOutput.RTMTriggeredCopyTexture)
		
		self.backcam = base.makeCamera2d(base.win, sort=-10)
		self.background = NodePath("background")
		self.backcam.reparentTo(self.background)
		self.background.setDepthTest(0)
		self.background.setDepthWrite(0)
		self.backcam.node().getDisplayRegion(0).setClearDepthActive(0)
		
		#taskMgr.add(self.takeSnapShot, "takeSnapShot")
		
		self.bcard = base.win.getTextureCard()
		self.bcard.reparentTo(self.background)
		self.bcard.setTransparency(1)
		self.fcard = base.win.getTextureCard()
		self.fcard.reparentTo(render2d)
		self.fcard.setTransparency(1)
		
		base.setBackgroundColor(0,0,0,1)
		self.bcard.hide()
		self.fcard.show()
		self.fcard.setColor(1.0,1.0,1.0,0.99)
		self.fcard.setScale(1.00)
		self.fcard.setPos(0,0,0)
		self.fcard.setR(0)
		self.clickrate = 30
		self.nextclick = 0'''
		
		self.c4 = Actor('Models/dancer/dancer')
		#self.c2.loadModel('Models/dancer/dancer')
		self.c4.setPos(offset_x-st_x,offset_y+st_y+7,offset_z+st_z)
		self.c4.reparentTo(render)
		self.c4.loadAnims({'win':'Models/dancer/dancer'})
		self.c4.loop('win')
		
		#self.c2.setR(-90)
		
		#self.c2.loop('tireroll')
		#base.setSleep(0.5)
		self.c3 = Actor("Models/cat-humans/bvw-f2004--ralph-egg/bvw-f2004--ralph/ralph")
		self.c3.setScale(2)
		self.c3.setPos(offset_x+0,offset_y+20,offset_z+(-1))
		self.c3.reparentTo(render)
		self.c3.listJoints()
		#self.c4.listJoints()
		self.actorRh = self.c3.controlJoint(None, 'modelRoot', 'RightShoulder')
		self.actorLh = self.c3.controlJoint(None, 'modelRoot', 'LeftShoulder')
		self.actorNeck = self.c3.controlJoint(None, 'modelRoot', 'Neck')
		
		self.actorNeck1 = self.c3.controlJoint(None, 'modelRoot', 'Neck')
		
		#self.actorNeck.hprInterval(3,Point3(0,90,0)).loop()
		self.actorLh.hprInterval(3,Point3(90,0,0)).loop()
		self.actorRh.hprInterval(3,Point3(0,0,-180)).loop()
		#self.actorRh.hprInterval(3,Point3(0,90,0)).loop()
		self.actorRh.setHpr(180,180,-60) # For Both hands upward
		self.actorLh.setHpr(90,-90,120)
		
		
		self.loadchar('','')
		self.duckPlane = loader.loadModel('Models/plane/plane')
		self.duckPlane.setPos(offset_x-2, offset_y+8, offset_z+10)         #set its position
		self.duckPlane.reparentTo(render)       #reparent to render
		self.duckPlane.setTransparency(1)
		self.duckTexs = self.loadTextureMovie(24, 'duck/duck_fly_left',
                                          'png', padding = 2)
		self.duckTask = taskMgr.add(self.textureMovie, "duckTask")
		self.duckTask.fps = 36
		self.duckTask.obj = self.duckPlane  
		self.duckTask.textures = self.duckTexs
		self.duckPlane.node().setEffect(BillboardEffect.makePointEye())
		
		self.expPlane = loader.loadModel('Models/plane/plane')  #load the object
		self.expPlane.setScale(18,10,10)
		self.expPlane.setPos(offset_x+0, offset_y+22, offset_z+4)                         #set the position
		self.expPlane.reparentTo(render)                      #reparent to render
		self.expPlane.setTransparency(1)                      #enable transparency

		self.expTexs = self.loadTextureMovie(50, 'explosion/def','png', padding = 4)
    #create the animation task
		self.expTask = taskMgr.add(self.textureMovie, "movieTask")
		self.expTask.fps = 30                                 #set framerate
		self.expTask.obj = self.expPlane                      #set object
		self.expTask.textures = self.expTexs                  #set texture list
		#self.expPlane.node().setEffect(BillboardEffect.makePointEye())
		
		
		self.c1 = loader.loadModel("Models/Dynamite/Dynamite")
		self.c1.setPos(offset_x-6,offset_y+10,offset_z+2)
		self.c1.reparentTo(render)
		
		self.expPlane1 = loader.loadModel('Models/plane/plane')  #load the object
		#self.expPlane1.setScale(1,10,10)
		self.expPlane1.setPos(offset_x-8, offset_y+10, offset_z+3)                         #set the position
		self.expPlane1.reparentTo(render)                      #reparent to render
		self.expPlane1.setTransparency(1)
		
		self.expTexs1 = self.loadTextureMovie(50, 'explosion1/explosion','png', padding = 4)
    #create the animation task
		self.expTask1 = taskMgr.add(self.textureExplosion, "explosionTask")
		self.expTask1.fps = 30                                 #set framerate
		self.expTask1.obj = self.expPlane1                      #set object
		self.expTask1.textures = self.expTexs1                  #set texture list
		self.expPlane1.node().setEffect(BillboardEffect.makePointEye())
		
		self.orientPlane = loader.loadModel('Models/plane/plane') #Load the object
		#self.orientPlane.setScale(1)
		self.orientTex = loader.loadTexture("Models/plane/textures/carpet.jpg")
		self.orientPlane.setTexture(self.orientTex, 1)        #Set the texture
		self.orientPlane.reparentTo(render)		#Parent to render
    #Set the position, orientation, and scale
		self.orientPlane.setPosHprScale(offset_x+0, offset_y+18, offset_z, 0, -90, 0, 20, 20, 20)

	def textureMovie(self, task):
		currentFrame = int(task.time * task.fps)
		task.obj.setTexture(task.textures[currentFrame % len(task.textures)], 1)
		return Task.cont
	def textureExplosion(self, task):
		currentFrame = int(task.time * task.fps)
		#print "curr  "
		#print currentFrame%51
		if((currentFrame%len(task.textures)) > 10):
			self.c1.hide()
		elif((currentFrame%len(task.textures)) <= 0):
			self.c1.show()
		task.obj.setTexture(task.textures[currentFrame % len(task.textures)], 1)
		return Task.cont
	def takeSnapShot(self, task):
		if (task.time > self.nextclick):
			self.nextclick += 1.0 / self.clickrate
			if (self.nextclick < task.time):
				self.nextclick = task.time
			base.win.triggerCopy()
		return Task.cont
	def loadTextureMovie(self, frames, name, suffix, padding = 1):
		return [loader.loadTexture((name+"%0"+str(padding)+"d."+suffix) % i) 
        for i in range(frames)]
	def loadchar(self,main_char,txt):
		self.txt = txt
		if(txt == ''):
			self.t = loader.loadModel("Models/DJTable/DJTable")
			self.t.setPos(offset_x+0,offset_y+20,offset_z)
			self.t.setH(180)
			self.t.reparentTo(render)
			self.setupLights()
			self.loadParticleConfig('fountain2.ptf')
		else:
			self.t = main_char#loader.loadModel("Models/cat-vehicles-road/bvw-f2004--girlscar-egg/bvw-f2004--girlscar/girlcar")#loader.loadModel("Models/cat-vehicles-road/bvw-f2004--carnsx-egg/bvw-f2004--carnsx/carnsx")
			#self.t.setPos(0,20,0)
			#self.t.reparentTo(render)
			self.setupLights()
			self.loadParticleConfig('steam.ptf')
	def loadParticleConfig(self, file):
        #Start of the code from steam.ptf
		self.p.cleanup()
		self.p = ParticleEffect()
		if(self.txt == ''):
			self.txt = ''
			self.p.loadConfig(Filename(file))
			self.p.setPos(0.000, 0, 2.500)  
		elif(self.txt == 'blue'):
			self.txt = ''
			self.p.loadConfig(Filename('steam_front.ptf'))        
			self.p.setPos(0.000, -1.8, -0.800)
			
		elif(self.txt == 'red'):
			self.txt = ''
			self.p.loadConfig(Filename(file))
			self.p.setPos(0.000, 1.800, 0.250)
		self.p.start(self.t)
	def setupLights(self):
		ambientLight = AmbientLight("ambientLight")
		ambientLight.setColor(Vec4(.4, .4, .35, 1))
		directionalLight = DirectionalLight("directionalLight")
		directionalLight.setDirection(Vec3( 0, 8, -2.5 ) )
		directionalLight.setColor(Vec4( 0.9, 0.8, 0.9, 1 ) )
		
		self.t.setLight(self.t.attachNewNode(directionalLight))
		self.t.setLight(self.t.attachNewNode(ambientLight)) 
#w = Effects()
#run()
Exemple #57
0
import maze
import Key_Control as Control
import Model_Load
from util import *

MAZE = maze.Maze()
ACCELERATION = 70
MAX_SPEED = 4
MAX_SPEED_SQ = MAX_SPEED ** 2
_JERK = 0.08
_SPEED = 0.05
UP = Vec3(0,0,1) # upward vector
_FLOOR = 1
_FOCUS = [0,0,0]
_FLAME = ParticleEffect()
_FLAME.loadConfig("fireish.ptf")
_EPSILON = 0.001
class Labryn(DirectObject):

    def setCamera(self, spin):
        self.spin = spin
    
    def spinCamera(self, task):
        if self.spin == 1: # spin counter-clockwise
            self.cameraSpinCount += 1
            angleDegrees = self.cameraSpinCount
            angleRadians =  angleDegrees * (pi/ 180)
            self.CAM_RAD = angleRadians
            camera.setPos(_FOCUS[0]+self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1]+self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*self.CAM_R) 
Exemple #58
0
class Labryn(DirectObject):

    def setCamera(self, spin):
        self.spin = spin
    
    def spinCamera(self, task):
        if self.spin == 1: # spin counter-clockwise
            self.cameraSpinCount += 1
            angleDegrees = self.cameraSpinCount
            angleRadians =  angleDegrees * (pi/ 180)
            self.CAM_RAD = angleRadians
            camera.setPos(_FOCUS[0]+self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1]+self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*self.CAM_R) 
            camera.setHpr(angleDegrees,-65,0)
        elif self.spin == 2: # spin clockwise
            self.cameraSpinCount  -= 1
            angleDegrees = self.cameraSpinCount
            angleRadians =  angleDegrees * (pi/ 180)
            self.CAM_RAD = angleRadians
            camera.setPos(_FOCUS[0]+self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1]+self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*self.CAM_R)
            camera.setHpr(angleDegrees,-65,0)
        elif self.spin == 3: # ZOOM IN not spin
            self.cameraZoomCount += 1
            deltaR = self.cameraZoomCount * 0.1
            new_R = 12-deltaR
            self.CAM_R = new_R
            camera.setPos(_FOCUS[0] + self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1] + self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*new_R)
        elif self.spin == 4: # ZOOM OUT
            self.cameraZoomCount -= 1
            deltaR = self.cameraZoomCount * 0.1
            new_R = 12-deltaR
            self.CAM_R = new_R
            camera.setPos(_FOCUS[0] + self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1] + self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*self.CAM_R)
                          
        return Task.cont

    def checkMouse(self, task):
        if base.mouseWatcherNode.hasMouse():
            self.mouseX=base.mouseWatcherNode.getMouseX()
            self.mouseY=base.mouseWatcherNode.getMouseY()
        return Task.cont

    def dropRock(self):
        if self.pokeMoveChoice == 1: # selected Geodude
            result = MAZE.canDropRock(self.rockX, self.rockY)
            if result != False: # can place rock here
                MAZE.dropRock(result[0],result[1])
                self.rock.setPos(self.rockX, self.rockY, 1)
                self.rockOnMaze = True
                self.pokeMoveChoice = None
                self.myPokeName.hide()
                self.myPokeName = None
                self.updateTwoD()
                self.playerCandyCount -= 1

    def useFlame(self):
        self.onFire = True # on fire
        self.playerCandyCount -= 1
        self.pokeStatus = 1
        self.flame = ParticleEffect()
        self.flame.loadConfig("fireish.ptf")
        self.flame.setPos(self.pikachu.getPos())
        self.flame.start(parent=render, renderParent=render)
        self.updateTwoD()

    def useStringShot(self):
        self.pokeStatus = 2
        self.updateTwoD()

    def placeRock(self, task):
        if self.pokeMoveChoice == 1: # selected Geodude
            dX,dY = ((self.mouseX-self.rockRefX),
                     (self.mouseY-self.rockRefY))
            self.rockX, self.rockY = MAZE.translateRockPosition(self.rockRefX,
                                                      self.rockRefY,
                                                      dX, dY)
            self.rock.show()
            self.rock.setPos(self.rockX, self.rockY, 1)
        self.updateTwoD()
        return Task.cont
    
    def placeRareCandy(self, task):
        if int(task.time) % 4 == 9 and self.candyOnBoard:
            self.candy.hide()
            self.candyOnBoard = False
        if int(task.time) % 10 ==  0 and (self.candyOnBoard == False):
            # every 10 seconds
            self.candy.setPos(MAZE.generateCandyPos())
            self.candy.show()
            self.candyOnBoard = True
        return Task.cont

    def updateTwoD(self):
        # update player candy count
        self.playerCandyStatus.destroy()
        self.playerCandyStatus = candyStatus(0, self.playerCandyCount)
        # update pikachu candy count
        # TODO
        # update my pokes color     
        if self.playerCandyCount == 0 :
            groupHide(self.myPokesBright)
            groupShow(self.myPokesDark)
            # update name
            if self.myPokeName != None:
                self.myPokeName.destroy()

    def clearRock(self):
        self.rock.hide()
        self.rockOnMaze = False
        MAZE.clearRock() # clear it in 2D

    def clearFlame(self):
        self.onFire = False
        self.flame.cleanup()
        self.pokeStatus = 0
        self.pokeMoveChoice = None
        try:
            self.myPokeName.destroy()
        except:
            pass
        self.myPokeName = None

    def clearString(self):
        self.pokeStatus = 0
        self.pokeMoveChoice = None
        try:
            self.myPokeName.destroy()
        except:
            pass
        self.myPokeName = None

        
    def timer(self, task): # deals with moves' lasting effects
        ##############################################################
        if self.rockOnMaze: # rock on maze
            self.rockCounter += 1
        elif self.rockCounter != 1: # rock not on maze, counter not cleared
            self.rockCounter = 0

        if self.onFire:
            self.fireCounter += 1
        elif self.fireCounter != 1:
            self.fireCounter = 0

        if self.pokeStatus == 2: # string shot
            self.stringCounter += 1
        elif self.stringCounter != 1:
            self.stringCounter = 0

        ##################################################################
        if self.rockCounter == 500:
            self.clearRock()

        if self.fireCounter == 80:
            self.clearFlame()

        if self.stringCounter == 120:
            self.clearString()
            
        return Task.cont
    
    def usePokeMove(self, number):
        if self.playerCandyCount > 0: # have more than one candy
            if number == 1 and self.rockOnMaze == False:
                if self.pokeMoveChoice != 1: # NONE or other
                    # set to center position
                    centerx =  base.win.getProperties().getXSize()/2
                    centery =  base.win.getProperties().getYSize()/2
                    base.win.movePointer(0,centerx,centery)
                    self.pokeMoveChoice = 1 # placeRock called here
                    self.rockRefX, self.rockRefY = 0,0
                    self.rock.show()
                    self.rock.setPos(0,0,1)
                else: # already 1
                    self.pokeMoveChoice = None
                    self.clearRock() # clear rock
            elif number == 2:
                if self.pokeMoveChoice != 2:
                    self.pokeMoveChoice = 2
                    self.useFlame()
                else:
                    self.pokeMoveChoice = None
            elif number == 3:
                if self.pokeMoveChoice != 3:
                    self.pokeMoveChoice = 3
                    self.useStringShot()
                else:
                    self.pokeMoveChoice = None
            if self.pokeMoveChoice == None: # no choice
                if self.myPokeName != None: # there is a name on board
                    self.myPokeName.destroy() # kill it
                else: # no name
                    pass
            else: # there is a choice
                if self.myPokeName != None:
                    self.myPokeName.destroy()
                self.myPokeName = Two_D.writePokeName(self.pokeMoveChoice)
  
    def loadRareCandy(self):
        self.candy = Model_Load.loadRareCandy()
        self.candy.reparentTo(render)
        self.candy.setScale(0.1)
        self.candy.hide()
        
    def eatRareCandy(self, task):
        if self.candyOnBoard: # candy on board
            if checkEat(self.ballRoot.getX(), self.ballRoot.getY(),
                        self.candy.getX(), self.candy.getY()): # ball eats
                self.candy.hide() # eaten
                self.candyOnBoard = False
                self.playerCandyCount += 1
                # self.playerCandyStatus.destroy()
                # self.playerCandyStatus = candyStatus(0,
                                       # self.playerCandyCount) # update
                print "BALL EATS CANDY"
                groupShow(self.myPokesBright)

            elif checkEat(self.pikachu.getX(), self.pikachu.getY(),
                          self.candy.getX(), self.candy.getY()):
                self.candy.hide()
                self.candyOnBoard = False
                self.pokemonCandyCount += 1
        return Task.cont

    def setFocus(self, changing):
        self.changingFocus = changing
        if changing == True: # Just Pressed
            self.referenceX, self.referenceY = self.mouseX, self.mouseY
        else: # cursor moves up
            self.referenceX, self.referenceY = None, None

    def resetView(self):
        self.CAM_R, self.CAM_RAD = 12, 0
        self.cameraSpinCount, self.cameraZoomCount = 0, 0
        # _FOCUS = [0,0,0] does not work WHY???
        _FOCUS[0], _FOCUS[1], _FOCUS[2] = 0,0,0
        self.changingFocus = False
        self.referenceX, self.referenceY = None, None
        camera.setPos(_FOCUS[0], _FOCUS[1]-self.CAM_R, 25)
        camera.setHpr(0, -65, 0)
        
    def changeFocus(self, task):
        if (self.changingFocus == True and self.mouseX != None and
            self.mouseY != None ):
            dX, dY = ((self.mouseX - self.referenceX)*0.1,
                      (self.mouseY - self.referenceY)*0.1)
            _FOCUS[0] += dX
            _FOCUS[1] += dY
            camera.setPos(_FOCUS[0] + self.CAM_R*cos(-pi/2+self.CAM_RAD),
                          _FOCUS[1] + self.CAM_R*sin(-pi/2+self.CAM_RAD),
                          (25.0/12)*self.CAM_R)
        return Task.cont

    def initialize(self):
        #bgmusic = load_bgmusic("palette.mp3")
        #bgmusic.play()

        self.background = Two_D.loadBackground()
        base.cam2dp.node().getDisplayRegion(0).setSort(-20)
        self.candyOnBoard = False
        self.playerCandyCount, self.pokemonCandyCount = 2, 0
        ######################Rare Candy###############################
        pokes=['caterpie', 'charmander', 'geodude']
        self.myPokesDark = Two_D.loadMyPokemon_Dark(pokes) # my pokemons
        self.myPokesBright = Two_D.loadMyPokemon_Bright()
        groupHide(self.myPokesBright)
        self.loadRareCandy() # load rare candy
        ######################Camera Initialization####################
        self.CAM_R, self.CAM_RAD = 12, 0
        camera.setPos(_FOCUS[0],_FOCUS[1]-12,_FOCUS[2]+25)
        camera.setHpr(0, -65, 0)
        self.cameraSpinCount, self.cameraZoomCount = 0, 0
        self.changingFocus = False
        self.spin = 0
        #######################ICONS###################################
        self.myIcon = Two_D.loadMyIcon()
        self.pokeIcon = Two_D.loadPokeIcon()
        self.playerCandyStatus = candyStatus(0, self.playerCandyCount)
        #######################FLAMES##################################
        base.enableParticles()
        self.fireCounter = 0
        self.onFire = False
        #######################STRINGSHOT#############################
        self.stringCounter = 0
        #######################GLOBALS#################################
        self.i = 0
        self.myDirection = ['zx', 'zy']
        self.rockCounter  = 0
        self.rockX, self.rockY = None, None
        self.rockOnMaze = False
        self.pokeMoveChoice = None
        self.myPokeName = None
        self.arrowKeyPressed = False
        self.pokemonDirection = 'd'
        self.mouseX, self.mouseY = None, None
        # direction the ball is going
        self.jerkDirection = None
        base.disableMouse()
        self.jerk = (0,0,0)
        self.MAZE = Model_Load.loadLabyrinth()
        Control.keyControl(self)
        self.loadPokemonLevel1()
        self.light()
        self.loadBall()
        self.pokeStatus = 0 # 0 is normal, 1 is burned, 2 is slow-speed
        ########################################ROCK###################
        self.rock = Model_Load.loadRock()
        self.rock.reparentTo(render)
        self.rock.hide() # Do not show, but load beforehand for performance
        
    def loadPokemonLevel1(self):
        self.pikachu = load_model("pikachu.egg")
        self.pikachu.reparentTo(render)
        self.pikachu.setScale(0.3)
        endPos = self.MAZE.find("**/end").getPos()
        self.pikachu.setPos(endPos) 
        
    def light(self):
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))

    def loadBall(self):
        self.ballRoot = render.attachNewNode("ballRoot")
        self.ball = load_model("ball")
        self.ball.reparentTo(self.ballRoot)
        self.ball_tex = load_tex("pokeball.png")
        self.ball.setTexture(self.ball_tex,1)
        self.ball.setScale(0.8)
        # Find the collision sphere for the ball in egg.
        self.ballSphere = self.ball.find("**/ball")
        self.ballSphere.node().setFromCollideMask(BitMask32.bit(0))
        self.ballSphere.node().setIntoCollideMask(BitMask32.allOff())
        #self.ballSphere.show()
        # Now we create a ray to cast down at the ball.
        self.ballGroundRay = CollisionRay()
        self.ballGroundRay.setOrigin(0,0,10)
        self.ballGroundRay.setDirection(0,0,-1)

        # Collision solids go in CollisionNode
        self.ballGroundCol =  CollisionNode('groundRay')
        self.ballGroundCol.addSolid(self.ballGroundRay)
        self.ballGroundCol.setFromCollideMask(BitMask32.bit(1))
        self.ballGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ballGroundColNp = self.ballRoot.attachNewNode(self.ballGroundCol)
        
        # light
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.55, .55, .55, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(0,0,-1))
        directionalLight.setColor(Vec4(0.375,0.375,0.375,1))
        directionalLight.setSpecularColor(Vec4(1,1,1,1))
        self.ballRoot.setLight(render.attachNewNode(ambientLight))
        self.ballRoot.setLight(render.attachNewNode(directionalLight))
        # material to the ball
        m = Material()
        m.setSpecular(Vec4(1,1,1,1))
        m.setShininess(96)
        self.ball.setMaterial(m,1)

    def __init__(self):
        self.initialize()
        self.WALLS = self.MAZE.find("**/Wall.004")
        self.WALLS.node().setIntoCollideMask(BitMask32.bit(0))
        # collision with the ground. different bit mask
        #self.mazeGround = self.maze.find("**/ground_collide")
        #self.mazeGround.node().setIntoCollideMask(BitMask32.bit(1))
        self.MAZEGROUND = self.MAZE.find("**/Cube.004")
        self.MAZEGROUND.node().setIntoCollideMask(BitMask32.bit(1))
        # add collision to the rock
        cs = CollisionSphere(0, 0, 0, 0.5)
        self.cnodePath = self.rock.attachNewNode(CollisionNode('cnode'))
        self.cnodePath.node().addSolid(cs)
        self.cnodePath.show()
        self.cnodePath.node().setIntoCollideMask(BitMask32.bit(0))
        # load the ball and attach it to the scene.
        # it is on a dummy node so that we can rotate the ball
        # without rotating the ray that will be attached to it

        # CollisionTraversers calculate collisions
        self.cTrav = CollisionTraverser()
        #self.cTrav.showCollisions(render)
        #self.cTrav.showCollisions(render)
        # A list collision handler queue
        self.cHandler = CollisionHandlerQueue()
        # add collision nodes to the traverse.
        # maximum nodes per traverser: 32
        self.cTrav.addCollider(self.ballSphere,self.cHandler)
        self.cTrav.addCollider(self.ballGroundColNp,self.cHandler)
        self.cTrav.addCollider(self.cnodePath, self.cHandler)
        # collision traversers have a built-in tool to visualize collisons
        #self.cTrav.showCollisions(render)
        self.start()

    def pokemonTurn(self, pokemon, direction):
        if direction  == 'l' and self.pokemonDirection != 'l':
            self.pokemonDirection = 'l'
            pokemon.setH(-90)
        if direction  == 'r' and self.pokemonDirection != 'r':
            self.pokemonDirection = 'r'
            pokemon.setH(90)
        if direction  == 'd' and self.pokemonDirection != 'd':
            self.pokemonDirection = 'd'
            pokemon.setH(0)
        if direction  == 'u' and self.pokemonDirection != 'u':
            self.pokemonDirection = 'u'
            pokemon.setH(180)
                        
    def pokemonMove(self, pokemon, direction):
        self.pokemonTurn(pokemon, direction)
        if self.pokeStatus == 0: speed = _SPEED
        elif self.pokeStatus == 1: speed = 0
        else: # self.pokeStatus == 2
            speed = _SPEED/2.0
        if direction == 'l':
            newX = pokemon.getX() - speed
            pokemon.setX(newX)
        elif direction == 'r':
            newX = pokemon.getX() + speed
            pokemon.setX(newX)
        elif direction == 'u':
            newY = pokemon.getY() + speed
            pokemon.setY(newY)
        elif direction == 'd':
            newY = pokemon.getY() - speed
            pokemon.setY(newY)
        elif direction == "s": # stop
            pass
        
    def whereToGo(self, task):
        # this returns the direction pokemon should go
        # tell MAZE pokemon and ball's board position
        print self.myDirection
        MAZE.setPokeCoord(self.pikachu.getX(), self.pikachu.getY(),
                          self.pokemonDirection)
        MAZE.setBallCoord(self.ballRoot.getX(), self.ballRoot.getY())
        # find out which direction to go
        direction = MAZE.getDecision()
        self.pokemonMove(self.pikachu,direction)
        return Task.cont

    def getInformation(self, task):
        # get information on the board
        # TODO
        self.i += 1 # sample every other call to avoid 
        if self.i % 2 == 0:
            dX = self.ballRoot.getX() - self.oldPos[0]
            dY = self.ballRoot.getY() - self.oldPos[1]
            if dX < 0 :
                # print "going left"
                self.myDirection[0] = 'l'
            elif abs(dX) < _EPSILON:
                # print "not moving horiz"
                self.myDirection[0] = 'zx'
            else:
                # print "going right"
                self.myDirection[0] = 'r'

            if dY < 0 :
                # print "going down"
                self.myDirection[1] = 'd'
            elif abs(dY) < _EPSILON:
                # print "not moving verti"
                self.myDirection[1] = 'zy'
            else:
                # print "going up"
                self.myDirection[1] = 'u'
            self.oldPos = self.ballRoot.getPos()
        return Task.cont
    
    def start(self):
        # maze model has a locator in it
        # self.ballRoot.show()
        self.startPos = self.MAZE.find("**/start").getPos()
        self.oldPos = self.MAZE.find("**/start").getPos()
        self.ballRoot.setPos(self.startPos) # set the ball in the pos
        self.ballV = Vec3(0,0,0) # initial velocity
        self.accelV = Vec3(0,0,0) # initial acceleration

        # for a traverser to work, need to call traverser.traverse()
        # base has a task that does this once a frame
        base.cTrav = self.cTrav

        # create the movement task, make sure its not already running
        taskMgr.remove("rollTask")
        taskMgr.add(self.placeRock, "placeRock")
        taskMgr.add(self.timer, "timer")
        taskMgr.add(self.getInformation, "getInformation")
        taskMgr.add(self.eatRareCandy, "eatRareCandy")
        taskMgr.add(self.placeRareCandy, "placeRareCandy")
        taskMgr.add(self.checkMouse, "checkMouse")
        taskMgr.add(self.spinCamera, "spinCamera")
        taskMgr.add(self.changeFocus, "changeFocus")
        taskMgr.add(self.whereToGo, "whereToGo")
        # taskMgr.add(lambda task: self.moveBall(task, self.jerkDirection),
                    # "moveBall")
        taskMgr.add(self.moveBall, "moveBall")
        self.mainLoop = taskMgr.add(self.rollTask, "rollTask")
        self.mainLoop.last = 0

    def moveBallWrapper(self, direction):
        if direction == False:
            self.arrowKeyPressed = False
        else:
            self.arrowKeyPressed = True
            self.jerkDirection = direction
    
    def moveBall(self, task):
        direction = self.jerkDirection
        if self.arrowKeyPressed == True:
            if direction == "u":
                self.jerk = Vec3(0,_JERK,0)
            elif direction == "d":
                self.jerk = Vec3(0,-_JERK,0)
            elif direction == "l":
                self.jerk = Vec3(-_JERK,0,0)
            elif direction == "r":
                self.jerk = Vec3(_JERK,0,0)
        return Task.cont        
    """      
    def moveBall(self, task, direction):
        if self.arrowKeyPressed == True:
            if direction == "u":
                self.jerk = Vec3(0,_JERK,0)
            elif direction == "d":
                self.jerk = Vec3(0,-_JERK,0)
            elif direction == "l":
                self.jerk = Vec3(-_JERK,0,0)
            elif direction == "r":
                self.jerk = Vec3(_JERK,0,0)
        return Task.cont
    """       
    # collision between ray and ground
    # info about the interaction is passed in colEntry
    
    def groundCollideHandler(self,colEntry):
        # set the ball to the appropriate Z for it to be on the ground
        newZ = colEntry.getSurfacePoint(render).getZ()
        self.ballRoot.setZ(newZ+.4)

        # up vector X normal vector
        norm = colEntry.getSurfaceNormal(render)
        accelSide = norm.cross(UP)
        self.accelV = norm.cross(accelSide)

    # collision between the ball and a wall
    def wallCollideHandler(self,colEntry):
        # some vectors needed to do the calculation
        norm = colEntry.getSurfaceNormal(render) * -1
        norm.normalize()
        curSpeed = self.ballV.length()
        inVec = self.ballV/curSpeed
        velAngle = norm.dot(inVec) # angle of incidance
        hitDir = colEntry.getSurfacePoint(render) - self.ballRoot.getPos()
        hitDir.normalize()
        hitAngle = norm.dot(hitDir)
    # deal with collision cases

        if velAngle > 0 and hitAngle >.995:
            # standard reflection equation
            reflectVec = (norm * norm.dot(inVec*-1)*2) + inVec

            # makes velocity half of hitting dead-on
            self.ballV = reflectVec * (curSpeed * (((1-velAngle)*.5)+.5))

            # a collision means the ball is already a little bit buried in
            # move it so exactly touching the wall
            disp = (colEntry.getSurfacePoint(render) -
                    colEntry.getInteriorPoint(render))
            newPos = self.ballRoot.getPos() + disp
            self.ballRoot.setPos(newPos)
            
    def rollTask(self,task):
        # standard technique for finding the amount of time
        # since the last frame
        dt = task.time - task.last
        task.last = task.time

        # If dt is large, then there is a HICCUP
        # ignore the frame
        if dt > .2: return Task.cont

        # dispatch which function to handle the collision based on name
        for i in range(self.cHandler.getNumEntries()):
            entry = self.cHandler.getEntry(i)
            name = entry.getIntoNode().getName()
       
            if name == "Wall.004":
                self.wallCollideHandler(entry)
            elif name=="Cube.004":
                self.groundCollideHandler(entry)
            else: 
                if self.rockOnMaze == True:
                    self.wallCollideHandler(entry)
        self.accelV += self.jerk
        # move the ball, update the velocity based on accel
        self.ballV += self.accelV * dt * ACCELERATION
        # clamp the velocity to the max speed
        if self.ballV.lengthSquared() > MAX_SPEED_SQ:
            self.ballV.normalize()
            self.ballV *= MAX_SPEED
        # update the position
        self.ballRoot.setPos(self.ballRoot.getPos() + (self.ballV*dt))

        # uses quaternion to rotate the ball
        prevRot = LRotationf(self.ball.getQuat())
        axis = UP.cross(self.ballV)
        newRot = LRotationf(axis, 45.5 * dt * self.ballV.length())
        self.ball.setQuat(prevRot * newRot)
        return Task.cont # continue the task