Exemplo n.º 1
0
class Pokemao():#Inimigos):
    def __init__(self,render, num):
        self.nome = "Pokemao"
        self.agi = 10
        self.hp = 10
        self.int = 5
        self.str = 1
        self.dano = 5
        self.bloqueio = False
        self.bloqueado = False
        self.velocAtaque = 0.5
        self.arma = None
        self.escudo = None
        self.armadura = None
        self.delete = False
        self.render = render
        self.loadModels(num)
        self.setAI()
        
    
    def getPos(self):
        return self.pokemao.getPos()   
        
    def loadModels(self,num):
        # Seeker
        pokemaoPos = Vec3(-10,-30.0,2.10)
        self.pokemao = Actor('personagens/Modelos/Pokeperna/p1',
                        {"andar" :"personagens/Modelos/Pokeperna/p1-andar.egg",
                        "saltar" :"personagens/Modelos/Pokeperna/p1-saltar.egg",
                        "correr" : "personagens/Modelos/Pokeperna/p1-correr",
                        "abaixar" : "personagens/Modelos/Pokeperna/p1-abaixar"})
        
        self.pokemao.reparentTo(self.render)
        #self.wanderer.setScale(0.5)
        self.pokemao.setPos(pokemaoPos)
        self.pokemao.setTag("inimigo",str(num))
      
    def setAI(self):
        #Creating AI World
        self.AIworld = AIWorld(self.render)
 
        self.AIchar = AICharacter("wanderer",self.pokemao, 100, 0.05, 5)
        self.AIworld.addAiChar(self.AIchar)
        self.AIbehaviors = self.AIchar.getAiBehaviors()
        
        self.AIbehaviors.wander(5, 0, 10, 1.0)
        self.pokemao.loop("correr")

        #AI World update        
        taskMgr.add(self.AIUpdate,"AIUpdate")
        
    #to update the AIWorld    
    def AIUpdate(self,task):
        if self.hp < 1:
            #self.cleanup()
            self.pokemao.detachNode()
            self.delete = True
        self.AIworld.update()            
        return Task.cont
Exemplo n.º 2
0
    def __init__(self, parent, models, amount):
        AIWorld.__init__(self, parent)
        self._parent = parent
        self._models = models
        self.amount = amount

        # min and max time between spawns in seconds
        self._idle_time_range = (2, 8)

        self.enemies = []
Exemplo n.º 3
0
 def __init__(self, parent, models, amount):
     AIWorld.__init__(self, parent)
     self._parent = parent
     self._models = models
     self.amount = amount
     
     # min and max time between spawns in seconds
     self._idle_time_range = (2, 8)
     
     self.enemies = []
Exemplo n.º 4
0
    def update(self, task):
        """Update the AI World.
        
        If the AI is paused, does nothing.
        """
        if hasattr(self, "_paused") and self._paused:
            pass
        else:
            AIWorld.update(self)

        return task.cont
Exemplo n.º 5
0
 def __init__(self, mouse):
     ShowBase.__init__(self)
     self.mouse = mouse
     self.joy_x = None
     self.joy_y = None
     props = WindowProperties()
     props.setMouseMode(WindowProperties.MRelative)  # keep mouse in screen
     self.disableMouse()
     self.win.requestProperties(props)
     self.setBackgroundColor(0, 0, 0)
     # Make missiles glow
     self.filters = CommonFilters(self.win, self.cam)
     self.filters.setBloom(blend=(0, 0, 0, 1), desat=-0.5, intensity=3.0, size="large")
     self.screen_width = self.win.getXSize()
     self.screen_height = self.win.getYSize()
     self.center_x = self.screen_width/2
     self.center_y = self.screen_height/2
     # self.win.movePointer(0, self.center_x, self.center_y)
     self.enableParticles()
     self.cTrav = CollisionTraverser()
     # self.cTrav.setRespectPrevTransform(True)
     self.pusher = PhysicsCollisionHandler()
     self.pusher.addInPattern('%fn-into-%in')
     self.target = None
     self.maxvel = 50
     self.roll_time = 0
     self.fuel = 1000
     self.ship()
     self.sounds()
     self.hud()
     self.part = Spacedust(self)
     self.events()
     self.camLens.setFov(70)
     self.camLens.setNear(1)
     self.camLens.setFar(500)
     self.get_key = {
         "ACCEL": False,
         "DECEL": False,
         "FORWARD_THRUST": False,
         "REVERSE_THRUST": False,
         "ROLL_LEFT": False,
         "ROLL_RIGHT": False,
         "ROLL_LEFT_BEG": False,
         "ROLL_RIGHT_BEG": False,
         "FIRE": False,
         "FIRING": False,
         "LOCK": False,
         "LOCKING": False,
     }
     self.AIworld = AIWorld(self.render)
     self.taskMgr.add(self.update, "task-update")
     self.taskMgr.doMethodLater(1, self.fuel_usage, "task-fuel-usage")
     self.taskMgr.add(self.AI_update, "AI-update")
     self.gen_enemy()
Exemplo n.º 6
0
 def update(self, task):
     """Update the AI World.
     
     If the AI is paused, does nothing.
     """
     if hasattr(self, "_paused") and self._paused:
         pass
     else:
         AIWorld.update(self)
     
     return task.cont
Exemplo n.º 7
0
 def setAI(self):
     collisions = render.getPythonTag('WorldCollisions')
     collisions.addCogGroundCollision(self.cog)
     self.AIWorld = AIWorld(render)
     self.AIChar = AICharacter('Cog', self.cog.getCog(), -125, 90, -14)
     self.AIWorld.addAiChar(self.AIChar)
     self.AIBehaviors = self.AIChar.getAiBehaviors()
     if self.support == False:
         self.AIBehaviors.pathFollow(8)
         self.AIBehaviors.addToPath(VBase3(110.60, -0.32, 4.57))
         checkpoints = self.spawn.getPath().getCheckpoints()
         for checkpoint in xrange(len(checkpoints)):
             self.AIBehaviors.addToPath(checkpoints[checkpoint].getPos())
         self.AIBehaviors.startFollow()
     else:
         self.AIBehaviors.pursue(render.find('**/Toon'))
     self.cog.getCog().loop('walk')
     base.taskMgr.add(self.AIUpdate, "AIUpdate")
Exemplo n.º 8
0
    def __init__(self):

        ShowBase.__init__(self)

        base.setFrameRateMeter(True)

        set_app(self)

        app = self

        # Rocket Gui
        LoadFontFace("gui/Raleway.otf")
        self.region = RocketRegion.make('pandaRocket', app.win)
        self.region.setActive(1)
        self.context = self.region.getContext()
        self.hud = self.context.LoadDocument('gui/hud.rml')
        ih = RocketInputHandler()
        app.mouseWatcher.attachNewNode(ih)
        self.region.setInputHandler(ih)
        self.hud.Show()

        self.cTrav = CollisionTraverser('coltrav')
        #self.cTrav.showCollisions(self.render)
        self.ai_world = AIWorld(render)

        self.enableParticles()

        self.scene = []
        self.player = Player(self)
        self.scene.append(self.player)

        self.backgrounds = self.gen_background()

        self.enemy_manager = EnemyManager(self)
        self.enemies = self.gen_enemies(self.scene)

        self.bullet_manager = BulletManager(self)
        self.bullet_count = 0

        self.taskMgr.add(self.update, "update")

        self.mouse_pos = Point2(0,0)

        self.set_keys()

        self.music = self.loader.loadSfx('sounds/onegameamonthjan.ogg')
        self.music.setVolume(0.2)
        self.music.play()

        self.item_manager = ItemManager(self)

        self.tree_manager = TreeManager(self)
        self.trees = self.gen_trees()
Exemplo n.º 9
0
    def setAI(self):
        #Creating AI World
        self.AIworld = AIWorld(self.render)
 
        self.AIchar = AICharacter("pokeperna",self.pokeperna, 60, 0.05, 5)
        self.AIworld.addAiChar(self.AIchar)
        self.aiBehaviors = self.AIchar.getAiBehaviors()
        #self.aiBehaviors.initPathFind("mapa/Modelos/cidade/navmesh.csv")
 
        #Path follow (note the order is reveresed)
        #AI World update
        taskMgr.add(self.AIUpdate,"AIUpdate")
Exemplo n.º 10
0
    def setAI(self):
        #Creating AI World
        self.AIworld = AIWorld(self.render)
 
        self.AIchar = AICharacter("wanderer",self.pokemao, 100, 0.05, 5)
        self.AIworld.addAiChar(self.AIchar)
        self.AIbehaviors = self.AIchar.getAiBehaviors()
        
        self.AIbehaviors.wander(5, 0, 10, 1.0)
        self.pokemao.loop("correr")

        #AI World update        
        taskMgr.add(self.AIUpdate,"AIUpdate")
Exemplo n.º 11
0
 def setAI(self):
     collisions = render.getPythonTag('WorldCollisions')
     collisions.addCogGroundCollision(self.cog)
     self.AIWorld = AIWorld(render)
     self.AIChar = AICharacter('Cog', self.cog.getCog(), -125, 90, -14)
     self.AIWorld.addAiChar(self.AIChar)
     self.AIBehaviors = self.AIChar.getAiBehaviors()
     if self.support == False:
         self.AIBehaviors.pathFollow(8)
         self.AIBehaviors.addToPath(VBase3(110.60, -0.32, 4.57))
         checkpoints = self.spawn.getPath().getCheckpoints()
         for checkpoint in xrange(len(checkpoints)):
             self.AIBehaviors.addToPath(checkpoints[checkpoint].getPos())
         self.AIBehaviors.startFollow()
     else:
         self.AIBehaviors.pursue(render.find('**/Toon'))
     self.cog.getCog().loop('walk')
     base.taskMgr.add(self.AIUpdate, "AIUpdate")
Exemplo n.º 12
0
    def __init__(self, model, id):
        
        self.dontSpawn = False
        self.id = id
        #init and render
        self.enemyNode = NodePath('enemy'+str(id))
        self.AIWorld = AIWorld(base.render)
        self.enemyNode.reparentTo(base.render)

        # Load the enemy model, set the scale, and add to render
        self.enemy =Actor(model,{"walk":"resources/humanoid-walk"})
        self.enemy.reparentTo(self.enemyNode)
        self.enemy.setScale(0.2)

	    #configure hit tube
        self.xTop = self.enemy.getX()
        self.yTop = self.enemy.getY()
        self.zTop = self.enemy.getZ() - 15
        xBot = self.xTop
        yBot = self.yTop
        zBot = self.zTop - 10
        self.cs = CollisionTube(self.xTop, self.yTop, self.zTop, xBot, yBot, zBot, 20)
        
        #init cnode
        self.cnodepath = self.enemy.attachNewNode(CollisionNode('cnode'+str(id)))
        self.cnodepath.setTag('objectTag', str(id))
        self.cnodepath.node().addSolid(self.cs)
        
        #so we can walk into the enemies
        self.chand = CollisionHandlerEvent()
        
        # must be same cTrav that was set in player, global collider thing
        base.cTrav.addCollider(self.cnodepath, self.chand)
        self.accept('cnode'+str(id), self.hit)

        # base settings like damage and health. modify spawner later to change these once we have a more diverse population
        self.health = 20*base.damageMod
        self.damage = 25;
        self.fireDelta = 0
        self.fireOffset = random.randint(0, 200)
        self.deadFlag = False
        self.scrubCannon = ScrubCannon(base.camera, self.enemy)
Exemplo n.º 13
0
    def __init__(self):
        # self.load_assets()
        base.cTrav = CollisionTraverser()
        base.pusher = CollisionHandlerPusher()
        base.groundHandler = CollisionHandlerQueue()
        self.AIworld = AIWorld(render)
        ConfigRender.__init__(self)

        self.elapsedSeconds = 0
        self.sound = ConfigSound()
        self.rpgField = RPGField()
        self.enemyData = EnemyModel()
        self.itemData = ItemModel()
        self.magicData = MagicModel()
        self.cutsceneManager = CutsceneManager()
        # print(PandaSystem.getVersionString())
        self.load_fonts()

        # this needs to be called only when game starts
        taskMgr.add(self.updateTime, 'updateTime')
Exemplo n.º 14
0
    def __init__(self):
        '''
        class constructor
        Creates environment, player objects
        '''
        # initialize
        #ShowBase.__init__(self)
        # set keybinds
        setKeybinds()
        mission = self
        self.nextValidSpawn = 0
        # handle collisions
        # collision traversal 'traverses' instances of collides
        base.cTrav = CollisionTraverser()  #switched to base
        base.pusher = CollisionHandlerPusher()  #switched to base

        base.pusher.addInPattern('entityCollision')
        base.groundHandler = CollisionHandlerQueue()
        # add catch-all handler
        #base.entityCollisionHandler.addInPattern('entityCollision')

        # handle entity collisions
        # pass to entityCollided
        base.accept('entityCollision', entityCollided)
        # handle bullet collisions
        # accept this event and pass it to method bulletCollided
        base.accept('bulletCollision', bulletCollided)

        # self.render references base.render
        self.render = base.render

        mission.CAPTURE_TIME = 15  #time to capture single flag
        mission.CAPTURE_RADIUS = 300  #radius that needs to be controlled to cap flag

        #cleanup is list that saves items to destroy on mission end
        base.cleanup = []
        # entities is list of all entities in gamespace. Used for applying gravity etc
        base.entities = []
        # also keep a running list of all structures
        base.structures = []

        #setup for AI
        base.AIworld = AIWorld(base.render)

        # load environment
        self.makeEnviron("example")

        # sfx handler for 3D audio
        #base.audio3d = Audio3DManager(base.sfxManagerList[0], base.camera)
        #background music
        self.music = base.loader.loadSfx("sounds/dramatic.ogg")
        self.music.setLoop(True)
        self.music.setVolume(0.15)
        self.music.play()

        # load GUI
        self.makeGUI()

        #set up player and camera
        #set mouse mode to relative
        base.disableMouse()
        setMouseMode(1)

        #find nodes in environment and store on game object
        self.team0Node = self.environment.find("**/team0")
        self.team0BaseNode = self.environment.find("**/team0base")
        self.team1Node = self.environment.find("**/team1")
        self.team1BaseNode = self.environment.find("**/team1base")

        #load occlusion nodes from environment
        #format in blender:
        #occlusion planes all parented to base level 'occluders' empty
        #occlusion planes named 'occluder#'
        occluder_nodes = self.environment.findAllMatches(
            '**/occluders/+OccluderNode')
        for occluder_nodepath in occluder_nodes:
            base.render.setOccluder(occluder_nodepath)
            occluder_nodepath.node().setDoubleSided(True)

        #for now will attempt to load up to 12 flags, and reject entries that don't work
        #TODO: dynamically load based on amount of flag nodes found
        #also may change capture time depending on flag
        self.flags = []
        self.outposts = []
        for i in range(12):
            thisFlag = self.environment.find("**/flag" + str(i))
            #only append if found successfully
            if thisFlag.error_type == 0:
                self.flags.append(thisFlag)
                thisFlag.setPythonTag('lastCapture',
                                      None)  #last capture attempt
                thisFlag.setPythonTag('lastCaptureTeam',
                                      None)  #last team that tried to cap

        self.spawnPlayer()
        #standing=rifleman(base,self.team0Node.getPos(),0)
        #running = rifleman(base, self.team0Node.getPos(), 0)
        #soldat = rifleman(base, self.team0Node.getPos(), 0)
        #instancee=base.render.attachNewNode('blast')
        #instancee.setX(instancee.getX()+200)
        #instance=soldat.instanceTo(instancee)
        #instancee.setX(instancee.getX()-180)
        #enemy = rifleman(base, (20, 300, 0),1)
        #friendly = rifleman(base, self.team0Node.getPos(), 0)
        #friendly.setGoal(self.flags[1])

        #load gameplay logic

        # update all entities
        taskMgr.add(self.updateEntities, "updateEntitiesTask")
        self.playerScore = 0

        self.spawnBases()
        self.spawnEnemies()
Exemplo n.º 15
0
class Enemy(DirectObject):
    
    #Flag for detecting hit enemy
    delFlag = False
    pauseFlag = False

    #Check for peaceful mode
    configFile = open("config.txt")
    configList = configFile.readlines()
    configFile.close()
    peacefulMode = configList[6].split("=")[1].translate(None,"\n")

    def __init__(self, model, id):
        
        self.dontSpawn = False
        self.id = id
        #init and render
        self.enemyNode = NodePath('enemy'+str(id))
        self.AIWorld = AIWorld(base.render)
        self.enemyNode.reparentTo(base.render)

        # Load the enemy model, set the scale, and add to render
        self.enemy =Actor(model,{"walk":"resources/humanoid-walk"})
        self.enemy.reparentTo(self.enemyNode)
        self.enemy.setScale(0.2)

	    #configure hit tube
        self.xTop = self.enemy.getX()
        self.yTop = self.enemy.getY()
        self.zTop = self.enemy.getZ() - 15
        xBot = self.xTop
        yBot = self.yTop
        zBot = self.zTop - 10
        self.cs = CollisionTube(self.xTop, self.yTop, self.zTop, xBot, yBot, zBot, 20)
        
        #init cnode
        self.cnodepath = self.enemy.attachNewNode(CollisionNode('cnode'+str(id)))
        self.cnodepath.setTag('objectTag', str(id))
        self.cnodepath.node().addSolid(self.cs)
        
        #so we can walk into the enemies
        self.chand = CollisionHandlerEvent()
        
        # must be same cTrav that was set in player, global collider thing
        base.cTrav.addCollider(self.cnodepath, self.chand)
        self.accept('cnode'+str(id), self.hit)

        # base settings like damage and health. modify spawner later to change these once we have a more diverse population
        self.health = 20*base.damageMod
        self.damage = 25;
        self.fireDelta = 0
        self.fireOffset = random.randint(0, 200)
        self.deadFlag = False
        self.scrubCannon = ScrubCannon(base.camera, self.enemy)

    #Sets enemy position
    def setPos(self, x, y, z):
		
        #Set enemy position
        self.enemy.setPos(x, y, z)
        
    
    #Checks for being hit by player projectile
    def hit(self, damage):
        
        #access the thing hit like below, the parrent of the collision node
        #damage health etc below
        self.health = self.health-damage
        if self.health <= 0:
            self.delFlag = True
            self.deadFlag = True
            #self.destroy()
        if self.deadFlag and not self.dontSpawn:
            self.spawnPick()
            self.dontSpawn = True

   
    #Fires enemy projecctile
    def fire(self):

        base.taskMgr.add(self.scrubCannon.fire, "fireE")

    #Activate enemy AI
    def setAI(self):
       
    	# Flag this as an AI character
    	#Faster enemy pursue
        self.AIchar = AICharacter("standby", self.enemy, 100,.05,250)
        self.AIWorld.addAiChar(self.AIchar)
        self.AIbehaviors = self.AIchar.getAiBehaviors()
        self.AIbehaviors.pursue(base.camera)
        self.AIbehaviors.pauseAi("pursue")

        #Slower enemy pursue
        self.AIchar2 = AICharacter("standby2", self.enemy, 100, .05, 100)
        self.AIWorld.addAiChar(self.AIchar2)
        self.AIbehaviors2 = self.AIchar2.getAiBehaviors()
        self.AIbehaviors2.pursue(base.camera)
        self.AIbehaviors2.pauseAi("pursue")

        base.taskMgr.add(self.AIUpdate, "Update AI")


    #Calculate the distance between the player and the enemy.
    def getDistance(self):

        #get enemy (x,y,z)
        eX = self.enemy.getX()
        eY = self.enemy.getY()
        eZ = self.enemy.getZ()
        
        #get player (x,y,z)
        pX = base.player.playerModel.getX()
        pY = base.player.playerModel.getY()
        pZ = base.player.playerModel.getZ()

        #calculate the distance between the enemy and player (x,y,z)
        #(eX - pX)^2
        x = eX - pX
        x = math.pow(x, 2)

        #(eY - pY)^2
        y = eY - pY
        y = math.pow(y,2)

        #(eZ - pZ)^2
        z = eZ - pZ
        z = math.pow(z, 2)

        self.dist = math.sqrt(x + y + z)
        return self.dist

    #AI behavior
    def AIUpdate(self,task):
        
        #if the enemy is not flaged as dead or paused then we update the AI
        self.max = 200
        self.shoot = 140
        self.min = 50
        if not self.deadFlag:
            if not self.pauseFlag:
                dist = self.getDistance()
                self.pickuppos = self.enemy.getPos()
                #if the distance is less than max, resume the pursue
                if(dist < self.max):
                    self.AIbehaviors.resumeAi("pursue")
                    #also if the distance is less than 'shoot range' then enemies can fire
                    if(dist < self.shoot):
                        self.AIbehaviors.pauseAi("pursue")
                        self.AIbehaviors2.resumeAi("pursue")
                        #if the distance becomes less than the min
                        #pause the chasing and double the firing speed
                        if(dist < self.min):
                            self.fireDelta = self.fireDelta *2
                            self.AIbehaviors.pauseAi("pursue")
                            self.AIbehaviors2.pauseAi("pursue")
                        if(self.peacefulMode != "True"):
                            self.fireDelta+=1
                            if self.fireDelta >= 100+self.fireOffset:
                                self.fireDelta = 0
                                self.fire()
                #else if the distance is more than 200 then don't chase or fire
                elif(dist >200):
                    self.AIbehaviors.pauseAi("pursue")
                    self.AIbehaviors2.pauseAi("pursue")
        else:
            return task.done
        self.AIWorld.update()
        
        return task.cont
    #Pauses enemyies 
    def pause(self):
        
        self.AIbehaviors.pauseAi("pursue")
        self.AIbehaviors2.pauseAi("pursue")
        self.pauseFlag = True

    #Resumes enemies
    def resume(self):

        self.pauseFlag = False
    #Randomly spawns health pickup on enemy death
    def spawnPick(self):

        a = random.randint(0, 100)
        if a > 74:
            base.spawnPickup(self.id, self.pickuppos)            
    
    #Clears enemy from the scene graph upon death
    def destroy(self):

        self.enemyNode.removeNode()
        self.enemy.cleanup()
        self.enemy.removeNode()
        self.cnodepath.node().clearSolids()
        
        base.cTrav.removeCollider(self.cnodepath)
        del self
    
    #Animation currently not functional
    def animate(self):
	
        self.enemy.play("walk")
        self.enemy.loop("walk", fromFrame = 10)
Exemplo n.º 16
0
class Engine(ShowBase):

    def __init__(self, mouse):
        ShowBase.__init__(self)
        self.mouse = mouse
        self.joy_x = None
        self.joy_y = None
        props = WindowProperties()
        props.setMouseMode(WindowProperties.MRelative)  # keep mouse in screen
        self.disableMouse()
        self.win.requestProperties(props)
        self.setBackgroundColor(0, 0, 0)
        # Make missiles glow
        self.filters = CommonFilters(self.win, self.cam)
        self.filters.setBloom(blend=(0, 0, 0, 1), desat=-0.5, intensity=3.0, size="large")
        self.screen_width = self.win.getXSize()
        self.screen_height = self.win.getYSize()
        self.center_x = self.screen_width/2
        self.center_y = self.screen_height/2
        # self.win.movePointer(0, self.center_x, self.center_y)
        self.enableParticles()
        self.cTrav = CollisionTraverser()
        # self.cTrav.setRespectPrevTransform(True)
        self.pusher = PhysicsCollisionHandler()
        self.pusher.addInPattern('%fn-into-%in')
        self.target = None
        self.maxvel = 50
        self.roll_time = 0
        self.fuel = 1000
        self.ship()
        self.sounds()
        self.hud()
        self.part = Spacedust(self)
        self.events()
        self.camLens.setFov(70)
        self.camLens.setNear(1)
        self.camLens.setFar(500)
        self.get_key = {
            "ACCEL": False,
            "DECEL": False,
            "FORWARD_THRUST": False,
            "REVERSE_THRUST": False,
            "ROLL_LEFT": False,
            "ROLL_RIGHT": False,
            "ROLL_LEFT_BEG": False,
            "ROLL_RIGHT_BEG": False,
            "FIRE": False,
            "FIRING": False,
            "LOCK": False,
            "LOCKING": False,
        }
        self.AIworld = AIWorld(self.render)
        self.taskMgr.add(self.update, "task-update")
        self.taskMgr.doMethodLater(1, self.fuel_usage, "task-fuel-usage")
        self.taskMgr.add(self.AI_update, "AI-update")
        self.gen_enemy()

    def gen_enemy(self):
        x = randint(-1000, 1000)
        y = randint(-1000, 1000)
        z = randint(-1000, 1000)
        Enemy(self, 0, x, y, z)

    def AI_update(self, task):
        self.AIworld.update()
        return task.cont

    def hud(self):
        self.font = self.loader.loadFont("./fnt/subatomic.tsoonami.ttf")
        self.aim = OnscreenImage(image="./png/ring.png", pos=Vec3(0), scale=0.02)
        self.aim.setTransparency(TransparencyAttrib.MAlpha)
        self.locker = OnscreenImage(image="./png/ring.png", pos=Vec3(0), scale=0.12)
        self.locker.setTransparency(TransparencyAttrib.MAlpha)
        self.locker.hide()

        self.txtFuel = OnscreenText(parent=self.render2d, align=TextNode.ALeft, pos=(-0.95, 0.8), text='FUEL', fg=(1, 1, 1, 0.5), scale=0.05, font=self.font, mayChange=True)
        self.txtSpeed = OnscreenText(parent=self.render2d, align=TextNode.ALeft, pos=(-0.95, 0.7), text='SPEED', fg=(1, 1, 1, 0.5), scale=0.05, font=self.font, mayChange=True)
        self.txtDist = OnscreenText(parent=self.render2d, align=TextNode.ALeft, pos=(-0.95, 0.6), text='DIST', fg=(1, 1, 1, 0.5), scale=0.05, font=self.font, mayChange=True)
        self.txtCoord = OnscreenText(parent=self.render2d, align=TextNode.ALeft, pos=(-0.95, 0.5), text='COORD', fg=(1, 1, 1, 0.5), scale=0.05, font=self.font, mayChange=True)
        self.taskMgr.doMethodLater(1, self.instruments, "task-instruments")

    def instruments(self, task):
        self.txtSpeed.setText("SPEED: %s" % str(int(self.mvel)))
        self.txtFuel.setText("FUEL: %s" % str(self.fuel))
        if self.target is not None:
            self.txtDist.setText("DISTANCE: %s" % str(round(self.dist, 1)))
        else:
            self.txtDist.setText("DISTANCE: ---")
        self.txtCoord.setText("COORD: %s %s %s" % (str(round(self.fighter.getX(), 1)), str(round(self.fighter.getY(), 1)), str(round(self.fighter.getZ(), 1))))
        return task.again

    def set_key(self, key, value):
        self.get_key[key] = value

    def toggle_key(self, key):
        self.set_key(key, not self.get_key[key])

    def init_roll(self, a, task):
        if task.time <= 2:
            if self.roll_time <= task.time:
                self.roll_time = task.time
            else:
                self.roll_time += task.time
                if self.roll_time > 2:
                    self.roll_time = 2
            self.fighter.setR(self.fighter.getR() + a * self.roll_time)
        else:
            self.fighter.setR(self.fighter.getR() + a * 2)
        return task.cont

    def end_roll(self, a, b, task):
        if task.time < b:
            self.roll_time -= task.time
            if self.roll_time < 0:
                self.roll_time = 0
            self.fighter.setR(self.fighter.getR() + a * (b - task.time))
            return task.cont
        else:
            return task.done

    def roll(self, a):
        if a > 0:
            self.set_key("ROLL_RIGHT_BEG", True)
        else:
            self.set_key("ROLL_LEFT_BEG", True)
        self.taskMgr.add(self.init_roll, "task-init-roll", extraArgs=[a], appendTask=True)

    def unroll(self, a):
        if a > 0:
            self.set_key("ROLL_RIGHT_BEG", False)
        else:
            self.set_key("ROLL_LEFT_BEG", False)
        self.taskMgr.remove("task-init-roll")
        self.taskMgr.add(self.end_roll, "task-end-roll", extraArgs=[a, self.roll_time], appendTask=True)

    def to_roll(self):
        if self.get_key["ROLL_LEFT"]:
            if not self.get_key["ROLL_LEFT_BEG"]:
                if self.fuel > 5:
                    self.roll(-1)
                    self.snd_roller.play()
        else:
            if self.get_key["ROLL_LEFT_BEG"]:
                self.unroll(-1)
                self.snd_roller.stop()
        if self.get_key["ROLL_RIGHT"]:
            if not self.get_key["ROLL_RIGHT_BEG"]:
                if self.fuel > 5:
                    self.roll(+1)
                    self.snd_roller.play()
        else:
            if self.get_key["ROLL_RIGHT_BEG"]:
                self.unroll(+1)
                self.snd_roller.stop()

    def fuel_usage(self, task):
        if self.get_key["FORWARD_THRUST"] or self.get_key["REVERSE_THRUST"]:
            self.fuel -= 9
        if self.get_key["ROLL_LEFT_BEG"] or self.get_key["ROLL_RIGHT_BEG"]:
            self.fuel -= 4
        self.fuel -= 1
        if self.fuel < 0:
            self.fuel = 0
        return task.again

    def chk_speed(self, mvel):
        if mvel < 0.01:
            # stop fighter dead
            if self.prt.getActive():
                self.set_key("DECEL", False)
            mvel = 0
        if mvel > self.maxvel:
            # stop fighter accelerating
            if self.pft.getActive():
                self.set_key("ACCEL", False)
            mvel = self.maxvel
        self.part.p.renderer.setLineScaleFactor(mvel*2)
        self.part.pn.setPos(self.fighter, 0, 10, 0)
        return mvel

    def thrust_shake(self, task):
        x = uniform(-1000, 1000)
        y = uniform(-1000, 1000)
        self.repos(x, y, 0.001)
        return task.cont

    def thrust_end(self, task):
        if task.time < 5:
            f = (5. - task.time) / 5.
            s = 1000.*f
            x = uniform(-s, s)
            y = uniform(-s, s)
            self.repos(x, y, 0.001)
            self.snd_thrust.setVolume(f)
            return task.cont
        self.snd_thrust.stop()
        return task.done

    def thrust(self, a):
        if a > 0:
            self.set_key("FORWARD_THRUST", True)
        else:
            self.set_key("REVERSE_THRUST", True)
        self.taskMgr.remove("task-thrust-end")
        self.snd_thrust.setVolume(1)
        self.snd_thrust.play()
        self.taskMgr.add(self.thrust_shake, "task-thrust-shake")

    def unthrust(self, a):
        if a > 0:
            self.set_key("FORWARD_THRUST", False)
        else:
            self.set_key("REVERSE_THRUST", False)
        self.taskMgr.remove("task-thrust-shake")
        self.taskMgr.add(self.thrust_end, "task-thrust-end")

    def to_thrust(self):
        if self.get_key["ACCEL"]:
            if self.mvel < self.maxvel - 1:
                if not self.get_key["FORWARD_THRUST"]:
                    if self.fuel > 10:
                        self.pft.setActive(True)
                        self.thrust(+1)
        else:
            if self.get_key["FORWARD_THRUST"]:
                self.pft.setActive(False)
                self.unthrust(+1)
        if self.get_key["DECEL"]:
            if self.mvel > 0:
                if not self.get_key["REVERSE_THRUST"]:
                    if self.fuel > 10:
                        self.prt.setActive(True)
                        self.thrust(-1)
        else:
            if self.get_key["REVERSE_THRUST"]:
                self.prt.setActive(False)
                self.unthrust(-1)

    def events(self):
        self.accept("escape", self.quit)
        self.accept('mouse1', self.set_key, ["FIRE", True])
        self.accept('mouse1-up', self.set_key, ["FIRE", False])
        self.accept('mouse3', self.set_key, ["LOCK", True])
        self.accept('mouse3-up', self.set_key, ["LOCK", False])
        self.accept("w", self.set_key, ["ACCEL", True])
        self.accept("w-up", self.set_key, ["ACCEL", False])
        self.accept("s", self.set_key, ["DECEL", True])
        self.accept("s-up", self.set_key, ["DECEL", False])
        self.accept("a", self.set_key, ["ROLL_LEFT", True])
        self.accept("a-up", self.set_key, ["ROLL_LEFT", False])
        self.accept("d", self.set_key, ["ROLL_RIGHT", True])
        self.accept("d-up", self.set_key, ["ROLL_RIGHT", False])

    def update(self, task):
        self.pos()
        self.speed()
        if self.fuel > 0:
            self.to_roll()
            self.to_thrust()
            self.to_fire()
            self.to_lock()
        self.rehud()
        return task.cont

    def rehud(self):
        if self.target is not None:
            c = self.target.np.getPos(self.fighter)
            self.dist = c.length()
            c.normalize()
            self.d2 = c - Vec3(0, 1, 0)*c.dot(Vec3(0, 1, 0))
            self.target.radar.setPos(self.d2.getX(), 1, self.d2.getZ())

    def sounds(self):
        self.audio3d = Audio3DManager.Audio3DManager(self.sfxManagerList[0], self.camera)
        self.audio3d.setListenerVelocityAuto()
        self.snd_space = self.loader.loadSfx("./snd/space.flac")
        self.snd_space.setLoop(True)
        self.snd_thrust = self.loader.loadSfx("./snd/thrust.flac")
        self.snd_thrust.setLoop(True)
        self.snd_roller = self.loader.loadSfx("./snd/roller.flac")
        self.snd_roller.setLoop(True)
        self.snd_launch = self.loader.loadSfx("./snd/launch.flac")
        self.snd_lock = self.loader.loadSfx("./snd/lock.flac")
        self.snd_space.play()

    def quit(self):
        self.taskMgr.running = False

    def repos(self, x, y, d):
        player_q = self.fighter.getQuat()
        up = player_q.getUp()
        right = player_q.getRight()
        up.normalize()
        right.normalize()
        up_q = copy(player_q)
        right_q = copy(player_q)
        up_q.setFromAxisAngle(-(x * d), up)
        right_q.setFromAxisAngle(y * d, right)
        self.fighter.setQuat(player_q.multiply(up_q.multiply(right_q)))

    def move_end(self, x, y, task):
        if task.time <= 1:
            d = 0.002*(1 - task.time)
            self.repos(x, y, d)
            return task.cont
        return task.done

    def pos(self):
        if self.mouse:
            md = self.win.getPointer(0)
            x = md.getX()
            y = md.getY()
        else:
            x = self.joy_x
            y = self.joy_y
        if self.win.movePointer(0, self.center_x, self.center_y):
            x -= self.center_x
            y -= self.center_y
            if x != 0 or y != 0:
                self.taskMgr.add(self.move_end, 'task-move-end', extraArgs=[x, y], appendTask=True)

    def speed(self):
        fwd = self.fighter.getQuat().getForward()
        fwd.normalize()
        self.mvel = self.anpo.getVelocity().length()
        # speed control
        self.mvel = self.chk_speed(self.mvel)
        self.anpo.setVelocity(fwd * self.mvel)

    def ship(self):
        an = ActorNode()
        an.getPhysicsObject().setMass(100)
        self.fighter = self.render.attachNewNode(an)
        self.physicsMgr.attachPhysicalNode(an)
        self.anpo = an.getPhysicsObject()
        fn = ForceNode("force-node-fighter")
        self.fighter.attachNewNode(fn)
        self.pft = LinearVectorForce(Vec3(0, +1, 0) * 500)  # forward thrust
        self.prt = LinearVectorForce(Vec3(0, -1, 0) * 500)  # reverse thrust
        self.pft.setMassDependent(1)
        self.prt.setMassDependent(1)
        self.pft.setActive(False)
        self.prt.setActive(False)
        fn.addForce(self.pft)
        fn.addForce(self.prt)
        an.getPhysical(0).addLinearForce(self.pft)
        an.getPhysical(0).addLinearForce(self.prt)
        self.camera.reparentTo(self.fighter)
        from_obj = self.fighter.attachNewNode(CollisionNode('fighter'))
        from_obj.node().setFromCollideMask(BitMask32(0x1))
        from_obj.setCollideMask(BitMask32(0x1))
        from_obj.node().addSolid(CollisionSphere(0, 0, 0, 1))
        # from_obj.show()
        self.pusher.addCollider(from_obj, self.fighter)
        self.cTrav.addCollider(from_obj, self.pusher)

    def launch_bullet(self):
        speed = 500.
        scale = Vec3(0.05)
        color = Vec4(0, 1, 0, 1)
        mask = BitMask32(0x2)
        lookat = Vec3(0, 100, 0)
        Missile(self, "bullet", speed, scale, color, mask, self.fighter, Vec3(-0.5, 0, 0), self.fighter, lookat, 0.5)
        Missile(self, "bullet", speed, scale, color, mask, self.fighter, Vec3(+0.5, 0, 0), self.fighter, lookat, 0.5)
        self.snd_launch.play()

    def to_fire(self):
        if self.get_key["FIRE"]:
            if not self.get_key["FIRING"]:
                self.set_key("FIRING", True)
                self.taskMgr.doMethodLater(0.16, self.fire_bullet, "task-fire-bullet")
        else:
            if self.get_key["FIRING"]:
                self.set_key("FIRING", False)
                self.taskMgr.remove("task-fire-bullet")

    def fire_bullet(self, task):
        if self.fuel >= 5:
            self.fuel -= 5
            self.launch_bullet()
        return task.again

    def launch_missile(self):
        speed = 100
        scale = Vec3(0.2)
        color = Vec4(1, 0, 0, 1)
        mask = BitMask32(0x2)
        lookat = Vec3(0, 0, 0)
        self.missile = Missile(self, "missile", speed, scale, color, mask, self.fighter, Vec3(0, 0, -2), self.target.np, lookat, 3)
        self.snd_launch.play()
        self.taskMgr.add(self.guide_missile, "task-guide-missile")

    def guide_missile(self, task):
        try:
            quat = Quat()
            lookAt(quat, self.target.np.getPos() - self.missile.anp.getPos(), Vec3.up())
            self.missile.anp.setQuat(quat)
            fwd = quat.getForward()
            fwd.normalize()
            mvel = self.missile.anpo.getVelocity().length()
            self.missile.anpo.setVelocity(fwd*mvel)
        except:
            return task.done
        return task.cont

    def can_lock(self):
        if self.dist >= 30 and self.dist <= 300 and abs(self.d2.getX()) <= 0.1 and abs(self.d2.getZ()) <= 0.1:
            return True
        else:
            return False

    def remove_lock(self):
        if self.get_key["LOCKING"]:
            self.set_key("LOCKING", False)
            self.locker.hide()
            self.snd_lock.stop()
            self.taskMgr.remove("task-fire-missile")

    def to_lock(self):
        if self.get_key["LOCK"]:
            if self.can_lock():
                if self.fuel >= 100:
                    if not self.get_key["LOCKING"]:
                        self.set_key("LOCKING", True)
                        self.locker.setScale(0.12)
                        self.locker.setColor(1, 0, 0, 0.5)
                        self.locker.show()
                        self.snd_lock.play()
                        self.taskMgr.add(self.fire_missile, "task-fire-missile")
                else:
                    self.remove_lock()
            else:
                self.remove_lock()
        else:
            self.remove_lock()

    def fire_missile(self, task):
        if self.fuel >= 100:
            if task.time < 3.6:
                e = (3.6 - task.time)/3.6
                f = 0.02 + e*0.1
                self.locker.setScale(f)
                self.locker.setColor(e, 1-e, 0, 0.5)
                return task.cont
            else:
                self.fuel -= 100
                self.launch_missile()
                return task.done
Exemplo n.º 17
0
class Pokeperna(Personagem):
    def __init__(self,render, colisaoTerreno):
        self.nome = "Pokeperna"
        self.agi = 10
        self.hp = 10
        self.int = 5
        self.str = 1
        self.dano = 5
        self.bloqueio = False
        self.bloqueado = False
        self.velocAtaque = 0.5
        self.arma = None
        self.escudo = None
        self.armadura = None
        self.segueAlvo = None
        self.segue = False
        
        self.pokeperna = Actor('personagens/Modelos/Pokeperna/p1',
                       {"andar" :"personagens/Modelos/Pokeperna/p1-andar.egg",
                       "saltar" :"personagens/Modelos/Pokeperna/p1-saltar.egg",
                       "correr" : "personagens/Modelos/Pokeperna/p1-correr",
                       "abaixar" : "personagens/Modelos/Pokeperna/p1-abaixar"})
#        self.pokeperna = Actor('personagens/Modelos/Pokeperna/p1',
#                       {"atacar" : "personagens/Modelos/pokepernaTeste-atacar"})
        #self.pokeperna.setScale(0.2,0.2,0.2)
        
        self.render = render 
        self.pokeperna.setTag("Pokeperna","1")
                
        #self.pokeperna.reparentTo(self.noRobot)
        self.pokeperna.setPos(-10,-30.0,2.10)
        self.pokeperna.reparentTo(self.render)
        self.gerenciadorColisao = self.pokeperna.getPos()
        self.goForward = 0
        self.goBackwards = 0
        self.goLeft = 0
        self.goRight = 0
        self.saltar = 0
        self.abaixar = 0
        self.prevtime = 0
        self.correr = 0
        self.move = 0
        self.gerenciadorColisao = colisaoTerreno
        self.gerenciarSelecao = 0
        
        self.setAI()
        taskMgr.add(self.gerenciadorSelecao,"gerenciasSelecao")
    
    def pega(self):
        pass
    
    def abre(self):
        pass
    
    def defende(self):
        pass
    
    def calcDefesa(self):
        pass
    
    def atacar(self):
        self.pokeperna.play("saltar")
        
        #self.ataca = atacar

    def setGoLeft (self,value):
        self.goLeft = value
    
    def setGoRight (self,value):
        self.goRight = value
    
    def setGoForward (self,value):
        self.goForward = value
    
    def setMove (self,value):
        self.move = value
        self.aiBehaviors.pathFollow(01.0)
        self.aiBehaviors.addToPath(self.gerenciadorColisao.getEntry(0).getSurfacePoint(self.render))
        self.aiBehaviors.addToPath(self.pokeperna.getPos())
        
        self.pokeperna.loop("correr",)
        #print self.pokeperna.getAnimControl('andar').isPlaying()
        #print self.gerenciadorColisao.getEntry(0).getSurfacePoint(self.render)
        #print posicao
        if self.segue:
            self.aiBehaviors.seek(self.segueAlvo.pokemao)
            self.aiBehaviors.startFollow("actor")
            print "segue"
        else:
            self.aiBehaviors.startFollow("actor")
        #self.aiBehaviors.pathFindTo((self.gerenciadorColisao.getEntry(0).getSurfacePoint(self.render)),"addPath")
        
        #self.move = value
        
    def setGoBackwards (self,value):
        self.goBackwards = value
    
    def setSaltar(self,value):
        self.saltar = value
    
    def setAbaixar(self, value):
        self.abaixar = value
    
    def setCorrer(self, value):
        self.correr = value
    
    def getModel(self):
        return self.pokeperna
    
    def getPos(self):
        return self.pokeperna.getPos()
    
    
    def update (self, time,traverser,robotGroundHandler):
        elapsed = time - self.prevtime
        
        if self.goLeft:
            self.pokeperna.setH(self.pokeperna.getH() + elapsed * 300)
        if self.goRight:
            self.pokeperna.setH(self.pokeperna.getH() - elapsed * 300)


    # this code moves the avatar forward.
    # "forward" usually means "along the Y axis".  however, since the avatar can turn, 
    # it really means "along the Y axis relative to the direction I'm facing"
    # you can use the getRelativeVector () function to find out what that is
    
        forwardVec =  VBase3(0,-1,0)
        xformedVec = self.render.getRelativeVector(self.pokeperna,forwardVec)
        para = True
        oldPos = self.pokeperna.getPos()
       
        if self.goForward:
            para = False
            if not self.pokeperna.getAnimControl('andar').isPlaying() \
                and not self.pokeperna.getAnimControl('saltar').isPlaying() \
                and not self.abaixar:
                    self.pokeperna.loop("andar",restart = 0)  
            newPos = oldPos + xformedVec * elapsed * 5
            self.pokeperna.setPos(newPos)
      
        if self.goBackwards:
            newPos = oldPos - xformedVec * elapsed * 5
            self.pokeperna.setPos(newPos)   
        
        if self.correr:
            para = False
            if not self.pokeperna.getAnimControl('correr').isPlaying() \
                and not self.pokeperna.getAnimControl('saltar').isPlaying() \
                and not self.abaixar:
                    self.pokeperna.loop("correr",restart = 0)  
            newPos = oldPos + xformedVec * elapsed * 7
            self.pokeperna.setPos(newPos)
    
        if self.saltar:
            para = False
            if not self.pokeperna.getAnimControl('saltar').isPlaying():
                self.pokeperna.play("saltar")
                
        if self.abaixar:
            para = False
            if not self.pokeperna.getAnimControl('abaixar').isPlaying():
                self.pokeperna.play("abaixar")
        
        if para:
#            if not self.pokeperna.getAnimControl('saltar').isPlaying():
                self.pokeperna.stop()
        
        # do collisions
        traverser.traverse(self.render)

        startpos = self.pokeperna.getPos()
        
        entries = []
        for i in range(robotGroundHandler.getNumEntries()):
            entry = robotGroundHandler.getEntry(i)
            entries.append(entry)
        entries.sort(lambda x,y: cmp(y.getSurfacePoint(self.render).getZ(),
                                     x.getSurfacePoint(self.render).getZ()))
    
        if (len(entries)>0) and (entries[0].getIntoNode().getName() == "Grid"):
            self.pokeperna.setZ(entries[0].getSurfacePoint(self.render).getZ())
            #print entries[0].getSurfacePoint(self.render).getZ(),self.pokeperna.getPos()
        #self.pokeperna.setZ(1000)
        else:
            self.pokeperna.setPos(startpos)
      
        self.prevtime = time
        return Task.cont
    
    def setAI(self):
        #Creating AI World
        self.AIworld = AIWorld(self.render)
 
        self.AIchar = AICharacter("pokeperna",self.pokeperna, 60, 0.05, 5)
        self.AIworld.addAiChar(self.AIchar)
        self.aiBehaviors = self.AIchar.getAiBehaviors()
        #self.aiBehaviors.initPathFind("mapa/Modelos/cidade/navmesh.csv")
 
        #Path follow (note the order is reveresed)
        #AI World update
        taskMgr.add(self.AIUpdate,"AIUpdate")
    
    def gerenciadorSelecao(self, task):
        
        return Task.cont
    
    def AIUpdate(self,task):
        #print self.pokeperna.getAnimControl('andar').isPlaying()
        if self.move and self.aiBehaviors.behaviorStatus("pathfollow") == "done":
#            if not self.pokeperna.getAnimControl('andar').isPlaying():
#                print "anda"
#                self.pokeperna.loop("andar",restart = 0)
            #print "gerenciadorColisao",self.gerenciadorColisao.getEntry(0).getSurfacePoint(self.render)
            #print "pokeperna",self.pokeperna.getPos()
            self.pokeperna.stop()
            self.pokeperna.pose("andar",0)
            
            #print "andando"
        else:
            pass
            #print "parado", self.move
#            self.pokeperna.stop()
#            self.pokeperna.pose("andar",0)
        self.AIworld.update()            
        return Task.cont
Exemplo n.º 18
0
class CogAI(DirectObject):

    cancelStep = False

    def __init__(self, cog, spawn, support=False):
        self.cog = cog
        self.spawn = spawn
        self.attack = True
        self.support = support
        self.flyIn()

    def setAI(self):
        collisions = render.getPythonTag('WorldCollisions')
        collisions.addCogGroundCollision(self.cog)
        self.AIWorld = AIWorld(render)
        self.AIChar = AICharacter('Cog', self.cog.getCog(), -125, 90, -14)
        self.AIWorld.addAiChar(self.AIChar)
        self.AIBehaviors = self.AIChar.getAiBehaviors()
        if self.support == False:
            self.AIBehaviors.pathFollow(8)
            self.AIBehaviors.addToPath(VBase3(110.60, -0.32, 4.57))
            checkpoints = self.spawn.getPath().getCheckpoints()
            for checkpoint in xrange(len(checkpoints)):
                self.AIBehaviors.addToPath(checkpoints[checkpoint].getPos())
            self.AIBehaviors.startFollow()
        else:
            self.AIBehaviors.pursue(render.find('**/Toon'))
        self.cog.getCog().loop('walk')
        base.taskMgr.add(self.AIUpdate, "AIUpdate")

    def calcChance(self, percent):
        if (random.randint(0, 100) < percent):
            return True
        else:
            return False

    def toggleAttack(self):
        if (self.attack):
            self.attack = False
        else:
            self.attack = True

    def AIUpdate(self, task):
        if (self.AIBehaviors.behaviorStatus('pathfollow') == 'done'):
            self.cog.getCog().loop('neutral')
            self.AIBehaviors.removeAi('pathfollow')
            toonHall = render.getPythonTag("ToonHall")
            toonHall.startCogEnter(self.cog)
            return Task.done
        else:
            if (self.cog.getHealth() > 0):
                if (self.calcChance(40) and self.attack):

                    def resumeAI(task):
                        self.AIBehaviors.resumeAi('pathfollow')
                        self.cog.getCog().loop('walk')
                        return Task.done

                    def enableAttacks(task):
                        return Task.done

                    avatar = render.find('**/Toon')
                    if (self.cog.getCog().getDistance(avatar) <= 20):
                        self.AIBehaviors.pauseAi('pathfollow')
                        self.cog.getCog().stop()
                        self.attack = False
                        self.cog.getCog().lookAt(avatar)
                        self.cog.getCog().play('throw-object')
                        attack = CogAttacks().getRandomAttack(
                            self.cog.getLevel() * 2)
                        attack.execute(self.cog)
                        base.taskMgr.doMethodLater(10, enableAttacks,
                                                   'Toggle Attack')
                        base.taskMgr.doMethodLater(3, resumeAI, 'Resume AI')
                self.AIWorld.update()
                return Task.cont
            else:
                self.AIBehaviors.removeAi('pathfollow')
                return Task.done

    def flyIn(self):
        phase_4 = "phase_4/models/props"
        cog = self.cog.getCog()

        collisions = render.getPythonTag('WorldCollisions')
        collisions.addCogCollision(self.cog)
        self.propeller = Actor(
            loader.loadModel(phase_4 + "/propeller-mod.bam"),
            {'chan': loader.loadModel(phase_4 + "/propeller-chan.bam")})
        self.propeller.reparentTo(cog.find('**/joint_head'))
        propSound = SoundBank.getSound('propeller')
        propSound.setLoop(True)
        propSound.setVolume(0.8)
        propSound.play()
        pos = cog.getPos()
        cog.setPos(pos.getX(), pos.getY(), pos.getZ() + 20)
        cog.pose('landing', 1)
        cog.colorScaleInterval(4.8,
                               Vec4(1, 1, 1, 1),
                               startColorScale=Vec4(0.2509803921568627,
                                                    0.2509803921568627,
                                                    0.2509803921568627, 0.25),
                               blendType='easeInOut').start()
        path = cog.posInterval(5, pos, startPos=cog.getPos())
        path.start()
        self.propeller.loop('chan', fromFrame=0, toFrame=3)
        base.taskMgr.add(self.handleCogDead, 'Handle Cog Death')
        base.taskMgr.doMethodLater(4,
                                   self.playInSound,
                                   'Play In Sound',
                                   extraArgs=[propSound],
                                   appendTask=True)
        base.taskMgr.doMethodLater(5, self.landCog, 'Land Cog')

    def handleCogDead(self, task):
        if (self.cog.isDefeated):
            self.cancelStep = True
            collisions = render.getPythonTag('WorldCollisions')
            collisions.addCogGroundCollision(cog=self.cog)
            return Task.done
        else:
            return Task.cont

    def landCog(self, task):
        if not self.cancelStep:
            base.taskMgr.remove('Handle Cog Death')
            self.propeller.play('chan', fromFrame=35, toFrame=87)
            self.cog.getCog().play('landing')
            base.taskMgr.doMethodLater(3, self.removePropeller,
                                       'Remove Propeller')
        return Task.done

    def removePropeller(self, task):
        self.propeller.cleanup()
        self.propeller.removeNode()
        self.setAI()
        return Task.done

    def playInSound(self, sound, task):
        if not self.cancelStep:
            sound.stop()
            SoundBank.getSound('propeller_in').play()
        return Task.done
Exemplo n.º 19
0
class CogAI(DirectObject):
    
    cancelStep = False
    
    def __init__(self, cog, spawn, support = False):
        self.cog = cog
        self.spawn = spawn
        self.attack = True
        self.support = support
        self.flyIn()
        
    def setAI(self):
        collisions = render.getPythonTag('WorldCollisions')
        collisions.addCogGroundCollision(self.cog)
        self.AIWorld = AIWorld(render)
        self.AIChar = AICharacter('Cog', self.cog.getCog(), -125, 90, -14)
        self.AIWorld.addAiChar(self.AIChar)
        self.AIBehaviors = self.AIChar.getAiBehaviors()
        if self.support == False:
            self.AIBehaviors.pathFollow(8)
            self.AIBehaviors.addToPath(VBase3(110.60, -0.32, 4.57))
            checkpoints = self.spawn.getPath().getCheckpoints()
            for checkpoint in xrange(len(checkpoints)):
                self.AIBehaviors.addToPath(checkpoints[checkpoint].getPos())
            self.AIBehaviors.startFollow()
        else:
            self.AIBehaviors.pursue(render.find('**/Toon'))
        self.cog.getCog().loop('walk')
        base.taskMgr.add(self.AIUpdate, "AIUpdate")
        
    def calcChance(self, percent):
        if(random.randint(0, 100) < percent):
            return True
        else:
            return False
        
    def toggleAttack(self):
        if(self.attack):
            self.attack = False
        else:
            self.attack = True
        
    def AIUpdate(self, task):
        if(self.AIBehaviors.behaviorStatus('pathfollow') == 'done'):
            self.cog.getCog().loop('neutral')
            self.AIBehaviors.removeAi('pathfollow')
            toonHall = render.getPythonTag("ToonHall")
            toonHall.startCogEnter(self.cog)
            return Task.done
        else:
            if(self.cog.getHealth() > 0):
                if(self.calcChance(40) and self.attack):
                    def resumeAI(task):
                        self.AIBehaviors.resumeAi('pathfollow')
                        self.cog.getCog().loop('walk')
                        return Task.done
                    def enableAttacks(task):
                        return Task.done
                    avatar = render.find('**/Toon')
                    if(self.cog.getCog().getDistance(avatar) <= 20):
                        self.AIBehaviors.pauseAi('pathfollow')
                        self.cog.getCog().stop()
                        self.attack = False
                        self.cog.getCog().lookAt(avatar)
                        self.cog.getCog().play('throw-object')
                        attack = CogAttacks().getRandomAttack(self.cog.getLevel() * 2)
                        attack.execute(self.cog)
                        base.taskMgr.doMethodLater(10, enableAttacks, 'Toggle Attack')
                        base.taskMgr.doMethodLater(3, resumeAI, 'Resume AI')
                self.AIWorld.update()
                return Task.cont
            else:
                self.AIBehaviors.removeAi('pathfollow')
                return Task.done
        
    def flyIn(self):
        phase_4 = "phase_4/models/props"
        cog = self.cog.getCog()

        collisions = render.getPythonTag('WorldCollisions')
        collisions.addCogCollision(self.cog)
        self.propeller = Actor(loader.loadModel(phase_4 + "/propeller-mod.bam"), {'chan' : loader.loadModel(phase_4 + "/propeller-chan.bam")})
        self.propeller.reparentTo(cog.find('**/joint_head'))
        propSound = SoundBank.getSound('propeller')
        propSound.setLoop(True)
        propSound.setVolume(0.8)
        propSound.play()
        pos = cog.getPos()
        cog.setPos(pos.getX(), pos.getY(), pos.getZ() + 20)
        cog.pose('landing', 1)
        cog.colorScaleInterval(4.8, Vec4(1, 1, 1, 1), startColorScale=Vec4(0.2509803921568627, 0.2509803921568627, 0.2509803921568627, 0.25), blendType='easeInOut').start()
        path = cog.posInterval(5, pos, startPos = cog.getPos())
        path.start()
        self.propeller.loop('chan', fromFrame=0, toFrame=3)
        base.taskMgr.add(self.handleCogDead, 'Handle Cog Death')
        base.taskMgr.doMethodLater(4, self.playInSound, 'Play In Sound', extraArgs = [propSound], appendTask = True)
        base.taskMgr.doMethodLater(5, self.landCog, 'Land Cog')
        
    def handleCogDead(self, task):
        if(self.cog.isDefeated):
            self.cancelStep = True
            collisions = render.getPythonTag('WorldCollisions')
            collisions.addCogGroundCollision(cog = self.cog)
            return Task.done
        else:
            return Task.cont
        
        
    def landCog(self, task):
        if not self.cancelStep:
            base.taskMgr.remove('Handle Cog Death')
            self.propeller.play('chan', fromFrame=35, toFrame=87)
            self.cog.getCog().play('landing')
            base.taskMgr.doMethodLater(3, self.removePropeller, 'Remove Propeller')
        return Task.done
    
    def removePropeller(self, task):
        self.propeller.cleanup()
        self.propeller.removeNode()
        self.setAI()
        return Task.done
        
    def playInSound(self, sound, task):
        if not self.cancelStep:
            sound.stop()
            SoundBank.getSound('propeller_in').play()
        return Task.done
        
Exemplo n.º 20
0
class Alem(ShowBase):
    def __init__(self):

        ShowBase.__init__(self)

        base.setFrameRateMeter(True)

        set_app(self)

        app = self

        # Rocket Gui
        LoadFontFace("gui/Raleway.otf")
        self.region = RocketRegion.make('pandaRocket', app.win)
        self.region.setActive(1)
        self.context = self.region.getContext()
        self.hud = self.context.LoadDocument('gui/hud.rml')
        ih = RocketInputHandler()
        app.mouseWatcher.attachNewNode(ih)
        self.region.setInputHandler(ih)
        self.hud.Show()

        self.cTrav = CollisionTraverser('coltrav')
        #self.cTrav.showCollisions(self.render)
        self.ai_world = AIWorld(render)

        self.enableParticles()

        self.scene = []
        self.player = Player(self)
        self.scene.append(self.player)

        self.backgrounds = self.gen_background()

        self.enemy_manager = EnemyManager(self)
        self.enemies = self.gen_enemies(self.scene)

        self.bullet_manager = BulletManager(self)
        self.bullet_count = 0

        self.taskMgr.add(self.update, "update")

        self.mouse_pos = Point2(0,0)

        self.set_keys()

        self.music = self.loader.loadSfx('sounds/onegameamonthjan.ogg')
        self.music.setVolume(0.2)
        self.music.play()

        self.item_manager = ItemManager(self)

        self.tree_manager = TreeManager(self)
        self.trees = self.gen_trees()


    def camera_task(self):    
        self.camera.setPos(self.player.position.x, self.player.position.y , 400)
        self.camera.setHpr(0,-90,0)

    def get_cam(self):
        return self.camera.getPos()

    def set_keys(self):
        self.accept("a", self.player.move_left, [True])
        self.accept("a-up", self.player.move_left, [False])

        self.accept("d", self.player.move_right, [True])
        self.accept("d-up", self.player.move_right, [False])

        self.accept("w", self.player.move_up, [True])
        self.accept("w-up", self.player.move_up, [False])

        self.accept("s", self.player.move_down, [True])
        self.accept("s-up", self.player.move_down, [False])

        self.accept("mouse1", self.player.activate, [True])
        self.accept("mouse1-up", self.player.activate, [False])

        self.accept("mouse3", self.player.build, [True])
        self.accept("mouse3-up", self.player.build, [False])

        self.accept("escape", sys.exit)

    def update(self, task):
        if(self.mouseWatcherNode.hasMouse()):
            self.mouse_pos.x = self.mouseWatcherNode.getMouseX()
            self.mouse_pos.y = self.mouseWatcherNode.getMouseY()

        self.camera_task()
        # Bullet reaping
        self.bullet_manager.update(task.time)
        self.enemy_manager.update(task.time)
        self.ai_world.update()
        self.cTrav.traverse(self.render)
        for entity in self.scene:
            entity.update(task.time)
        self.camera_task()
        self.update_hud()
        return Task.cont


    def update_hud(self):
        self.hud.GetElementById("health").last_child.text = "%d" % self.player.hp
        self.hud.GetElementById("score").last_child.text = "%d" % self.player.score
        self.hud.GetElementById("souls").last_child.text = "%d" % self.player.souls


    # should move creation into the manager
    def gen_enemies(self, scene):
        enemies = []
        for i in range(randint(50,100)):
            self.enemy_manager.create_enemy(1.0)
        #for i in range(1):
        """
            x = uniform(-900, 900)
            if -100.0 < x < 100.0:
                if x < 0.0:
                    x = x - 200.0
                if x >= 0.0:
                    x = x + 200.0
            y = uniform(-900, 900)
            if -100.0 < y < 100.0:
                if y < 0.0:
                    y = y - 200.0
                if y >= 0.0:
                    y = y + 200.0
            enemy = Enemy(Point3(x, y, 0), i, self, self.enemy_manager, uniform(1,3), randint(1,4))
            #enemy = Enemy(Point3(30.0,30.0,0.0), i, self, self.enemy_manager, 1, 1)
            enemies.append(enemy)
            scene.append(enemy)
        """    
        return enemies    

    # make this configurable
    def gen_background(self):
        bg_x = 50
        bg_y = 50

        tile_count = 20

        backgrounds = []

        self.bgnp = self.render.attachNewNode("bg")

        for i in range(-tile_count,tile_count):
            for j in range(-tile_count,tile_count):
                backgrounds.append(load_object("grass", pos = Point2(i*bg_x, j*bg_y), transparency = False, scale = 50))
        for background in backgrounds:
            background.reparentTo(self.bgnp)

        self.bgnp.flattenStrong()    
        return backgrounds

    def gen_trees(self):
        for i in range(randint(10,20)):
            self.tree_manager.add_tree(Point3(uniform(-100,100), uniform(-100,100), 0), 1)