Beispiel #1
0
class HUD():
    def __init__(self):
        self.speedometer = OnscreenImage(image = 'img/speedometerDial.png', pos = (-1, 0, -.7) )
        self.speedometer.setScale(.25)
        self.speedometer.setTransparency(TransparencyAttrib.MAlpha)
        self.speedPin = OnscreenImage(image = 'img/speedometerNeedle.png', pos = (-1, 0, -.7))
        self.speedPin.setScale(.10)
        self.speedPin.setTransparency(TransparencyAttrib.MAlpha)
        self.speedPin.setHpr(0, 0, 0)
        
        self.minimap = OnscreenImage(image = 'img/minimap.png', pos = (1.05, 0, -.65))
        self.minimap.setScale(.19, .19, .3)
        self.dot = OnscreenImage(image = 'img/dot.png', pos = (1.01, 0, -.55))
        self.dot.setScale(.025)
        

        font1 = loader.loadFont('img/goodfish.ttf')
        self.lapText = OnscreenText(text = "0/10", font = font1, pos = (1, -.1, 0), fg = (1, 1, 1, 1) )
        self.lapText.setScale(.05)
        self.placeText = OnscreenText(text = "", font = font1, pos = (1, -.2, 0), fg = (1, 1, 1, 1))
        self.placeText.setScale(.05)
        self.timerText = OnscreenText(text = "Time: ", font = font1, pos = (1, -.3, 0), fg = (1, 1, 1, 1))

        
    def update(self, velocity, x, y, laps, place, time):
        if velocity < 0:
            velocity = -velocity


        self.dot.setPos(1.01+(x/4250), 0, -.55+(y/4250))
        self.lapText.setText("Laps: " + str(laps)+"/3")


        self.speedPin.setHpr(0, 0, 4*velocity)



        self.placeText.setText("Position: "+str(place))
        self.timerText.setText("Time: "+ str(round(time)))
    
    """def getDist(self, x, y, checkpoint):
        cx = checkpoint[0]
        cy = checkpoint[1]
        dist = math.sqrt((cx-x)**2 + (cy-y)**2)
        
        rotAngle = math.atan2(-y,x)
        
        newX = x*math.cos(rotAngle) - y*math.sin(rotAngle)
        
        dToCheckpoint = dist - newX
        return dToCheckpoint"""
    
    """def updateMiniMap(self, x, y):
        self.dot.setPos(1+(x/1000), 0, -.7+(y/1000))"""
        
        
Beispiel #2
0
class miniMap(object):
    
    def __init__(self, mainActor):
        
        self.teamMateImage = 'models/teamMate.png'
        self.heroImage = 'models/mainHero.png'
        self.miniMapImage = 'models/miniMapImage.png'
        
        self.map = OnscreenImage(image = self.miniMapImage, pos=(-1, 0, 0.6), 
                              scale=(0.3, 0.3, 0.3))
        
        self.map.setTransparency(1)

        self.hero = OnscreenImage(image=self.heroImage, pos=(mainActor.getX()/200, 0, mainActor.getY()/100), 
                                    scale=(0.045, 0.045, 0.045), 
                                    hpr=(0, 0, mainActor.getH()))
        self.hero.reparentTo(self.map)
        self.hero.setTransparency(1)
        
        self.npc = {}
        
        self.team = {}
                
    def setMap(self, mapScale, x, y):
        map = OnscreenImage(image = self.miniMapImage, pos=(x, 0, y), 
                              scale=(mapScale, mapScale, mapScale))
        return map
        
    def setHero(self, heroScale, x, y, h):
        hero = OnscreenImage(image=self.heroImage, pos=(x, 0, y), 
                                   scale=(heroScale, heroScale, heroScale), 
                                   hpr=(0, 0, h))
        return hero
    
    def setNpc(self, npcName, npcImage, npcScale, x, y):
        self.Nps = OnscreenImage(image=npcImage, pos=(x, 0, y), 
                                 scale=(npcScale, npcScale, npcScale))
        self.Nps.reparentTo(self.map)
        self.Nps.setTransparency(1)
        self.npc[npcName] = self.Nps

        return self.npc
        
    def delNpc(self, npcName):
        del self.npc[npcName]
        
    def setTeamMate(self, mateName, mateScale, getX, getY):
        ay = ((70+(getY))*100)/120
        y = -1+(ay*2)/100
        ax = ((127+(getX))*100)/172
        x = -1+(ax*2)/100
        self.teamMate = OnscreenImage(image=self.teamMateImage, 
                                      pos=(x, 0, y), 
                                      scale=(mateScale, mateScale, mateScale))
        self.teamMate.reparentTo(self.map)
        self.teamMate.setTransparency(1)
        self.team[mateName] = self.teamMate
        
        return self.team
        
    def delTeamMate(self, mateName):
        del self.team[mateName]
        
    def updateHeroPos(self, getX, getY):
        ay = ((70+(getY))*100)/120
        y = -1+(ay*2)/100
        ax = ((127+(getX))*100)/172
        x = -1+(ax*2)/100
        self.hero.setPos(x, 0, y) 
        
    def updateHeroHpr(self, getH):
        h = -getH
        self.hero.setHpr(0, 0, h)
        
    def updateTeamMatePos(self, mateName, getX, getY):
        ay = ((70+(getY))*100)/120
        y = -1+(ay*2)/100
        ax = ((127+(getX))*100)/172
        x = -1+(ax*2)/100
        self.team[mateName].setPos(x, 0, y) 
     
    def updateTeamMateHpr(self, mateName, getH):
        h = -getH
        self.team[mateName].setHpr(0, 0, h)   
    
    def changeTowerColor(self, npcName, toverImage):
        self.npc[npcName].setImage(toverImage)
            
Beispiel #3
0
class miniMap(object):
    def __init__(self, mainActor):

        self.teamMateImage = 'models/teamMate.png'
        self.heroImage = 'models/mainHero.png'
        self.miniMapImage = 'models/miniMapImage.png'

        self.map = OnscreenImage(image=self.miniMapImage,
                                 pos=(-1, 0, 0.6),
                                 scale=(0.3, 0.3, 0.3))

        self.map.setTransparency(1)

        self.hero = OnscreenImage(image=self.heroImage,
                                  pos=(mainActor.getX() / 200, 0,
                                       mainActor.getY() / 100),
                                  scale=(0.045, 0.045, 0.045),
                                  hpr=(0, 0, mainActor.getH()))
        self.hero.reparentTo(self.map)
        self.hero.setTransparency(1)

        self.npc = {}

        self.team = {}

    def setMap(self, mapScale, x, y):
        map = OnscreenImage(image=self.miniMapImage,
                            pos=(x, 0, y),
                            scale=(mapScale, mapScale, mapScale))
        return map

    def setHero(self, heroScale, x, y, h):
        hero = OnscreenImage(image=self.heroImage,
                             pos=(x, 0, y),
                             scale=(heroScale, heroScale, heroScale),
                             hpr=(0, 0, h))
        return hero

    def setNpc(self, npcName, npcImage, npcScale, x, y):
        self.Nps = OnscreenImage(image=npcImage,
                                 pos=(x, 0, y),
                                 scale=(npcScale, npcScale, npcScale))
        self.Nps.reparentTo(self.map)
        self.Nps.setTransparency(1)
        self.npc[npcName] = self.Nps

        return self.npc

    def delNpc(self, npcName):
        del self.npc[npcName]

    def setTeamMate(self, mateName, mateScale, getX, getY):
        ay = ((70 + (getY)) * 100) / 120
        y = -1 + (ay * 2) / 100
        ax = ((127 + (getX)) * 100) / 172
        x = -1 + (ax * 2) / 100
        self.teamMate = OnscreenImage(image=self.teamMateImage,
                                      pos=(x, 0, y),
                                      scale=(mateScale, mateScale, mateScale))
        self.teamMate.reparentTo(self.map)
        self.teamMate.setTransparency(1)
        self.team[mateName] = self.teamMate

        return self.team

    def delTeamMate(self, mateName):
        del self.team[mateName]

    def updateHeroPos(self, getX, getY):
        ay = ((70 + (getY)) * 100) / 120
        y = -1 + (ay * 2) / 100
        ax = ((127 + (getX)) * 100) / 172
        x = -1 + (ax * 2) / 100
        self.hero.setPos(x, 0, y)

    def updateHeroHpr(self, getH):
        h = -getH
        self.hero.setHpr(0, 0, h)

    def updateTeamMatePos(self, mateName, getX, getY):
        ay = ((70 + (getY)) * 100) / 120
        y = -1 + (ay * 2) / 100
        ax = ((127 + (getX)) * 100) / 172
        x = -1 + (ax * 2) / 100
        self.team[mateName].setPos(x, 0, y)

    def updateTeamMateHpr(self, mateName, getH):
        h = -getH
        self.team[mateName].setHpr(0, 0, h)

    def changeTowerColor(self, npcName, toverImage):
        self.npc[npcName].setImage(toverImage)
Beispiel #4
0
class Drive(ShowBase):
	def __init__(self):
		ShowBase.__init__(self)
		
		#Setup
		scene = BulletWorld()
		scene.setGravity(Vec3(0, 0, -9.81))
		base.setBackgroundColor(0.6,0.9,0.9)
		fog = Fog("The Fog")
		fog.setColor(0.9,0.9,1.0)
		fog.setExpDensity(0.003)
		render.setFog(fog)
		#Lighting
		
		#Sun light
		sun = DirectionalLight("The Sun")
		sun_np = render.attachNewNode(sun)
		sun_np.setHpr(0,-60,0)
		render.setLight(sun_np)
		
		#Ambient light
		amb = AmbientLight("The Ambient Light")
		amb.setColor(VBase4(0.39,0.39,0.39, 1))
		amb_np = render.attachNewNode(amb)
		render.setLight(amb_np)
		
		#Variables
		self.gear = 0
		
		self.start = 0
		
		self.Pbrake = 0
		
		self.terrain_var = 1
		
		self.time = 0
		
		self.headlight_var = 0
		
		self.RPM = 0
		
		self.clutch = 0
		
		self.carmaxspeed = 100 #KPH
		
		self.carmaxreversespeed = -40 #KPH
		
		self.steering = 0
		
		
		#Functions
		def V1():
			camera.setPos(0.25,-1.2,0.5)
			camera.setHpr(0,-13,0)
			
		def V2():
			camera.setPos(0,-15,3)
			camera.setHpr(0,-10,0)
			
		def V3():
			camera.setPos(0,0,9)
			camera.setHpr(0,-90,0)
			
		def up():
			self.gear = self.gear -1
			if self.gear < -1:
				self.gear = -1
				
		def down():
			self.gear = self.gear +1
			if self.gear > 1:
				self.gear = 1
				
		def start_function():
			self.start = 1
			self.start_sound.play()
			self.engine_idle_sound.play()
			self.RPM = 1000
			
		def stop_function():
			self.start = 0
			self.engine_idle_sound.stop()
				
		def parkingbrake():
			self.Pbrake = (self.Pbrake + 1) % 2
			
		def rotate():
			Car_np.setHpr(0, 0, 0)
			
		def horn():
			self.horn_sound.play()
			
		def set_time():
			if self.time == -1:
				sun.setColor(VBase4(0.4, 0.3, 0.3, 1))
				base.setBackgroundColor(0.8,0.7,0.7)
			if self.time == 0:
				sun.setColor(VBase4(0.7, 0.7, 0.7, 1))
				base.setBackgroundColor(0.6,0.9,0.9)
			if self.time == 1:
				sun.setColor(VBase4(0.2, 0.2, 0.2, 1))
				base.setBackgroundColor(0.55,0.5,0.5)
			if self.time == 2:
				sun.setColor(VBase4(0.02, 0.02, 0.05, 1))
				base.setBackgroundColor(0.3,0.3,0.3)
				
			if self.time == -2:
				self.time = -1
			if self.time == 3:
				self.time = 2
			
		def time_forward():
			self.time = self.time + 1
			
		def time_backward():
			self.time = self.time -1
			
		def set_terrain():
			if self.terrain_var == 1:
				self.ground_model.setTexture(self.ground_tex, 1)
				self.ground_model.setScale(3)
			if self.terrain_var == 2:
				self.ground_model.setTexture(self.ground_tex2, 1)
				self.ground_model.setScale(3)
			if self.terrain_var == 3:
				self.ground_model.setTexture(self.ground_tex3, 1)
				self.ground_model.setScale(4)
				
			if self.terrain_var == 4:
				self.terrain_var = 1
			if self.terrain_var == 0:
				self.terrain_var = 3
			
		def next_terrain():
			self.terrain_var = self.terrain_var + 1
			
		def previous_terrain():
			self.terrain_var = self.terrain_var - 1
			
		def show_menu():
			self.menu_win.show()
			self.a1.show()
			self.a2.show()
			self.a3.show()
			self.a4.show()
			self.t1.show()
			self.t2.show()
			self.ok.show()
			self.exit_button.show()
			
		def hide_menu():
			self.menu_win.hide()
			self.a1.hide()
			self.a2.hide()
			self.a3.hide()
			self.a4.hide()
			self.ok.hide()
			self.t1.hide()
			self.t2.hide()
			self.exit_button.hide()
		
		def Menu():
			self.menu_win = OnscreenImage(image = "Textures/menu.png", pos = (0.9,0,0), scale = (0.5))
			self.menu_win.setTransparency(TransparencyAttrib.MAlpha)
			
			#The Arrow Buttons
			self.a1 = DirectButton(text = "<", scale = 0.2, pos = (0.55,0,0.25), command = previous_terrain)
			self.a2 = DirectButton(text = ">", scale = 0.2, pos = (1.15,0,0.25), command = next_terrain)
			self.a3 = DirectButton(text = "<", scale = 0.2, pos = (0.55,0,0.0), command = time_backward)
			self.a4 = DirectButton(text = ">", scale = 0.2, pos = (1.15,0,0.0), command = time_forward)
			
			#The Text
			self.t1 = OnscreenText(text = "Terrain", pos = (0.85,0.25,0), scale = 0.1, fg = (0.4,0.4,0.5,1))
			self.t2 = OnscreenText(text = "Time", pos = (0.85,0,0), scale = 0.1, fg = (0.4,0.4,0.5,1))
			
			#The Buttons
			self.ok = DirectButton(text = "Okay", scale = 0.11, pos = (0.87,0,-0.25), command = hide_menu)
			self.exit_button = DirectButton(text = "Quit", scale = 0.11, pos = (0.87,0,-0.42), command = sys.exit)
			
		Menu()
		
		
		def take_screenshot():
			base.screenshot("Screenshot")
			
		def set_headlights():
			if self.headlight_var == 1:
				Headlight1.setColor(VBase4(9.0,8.9,8.9,1))
				Headlight2.setColor(VBase4(9.0,8.9,8.9,1))
			if self.headlight_var == 0:
				Headlight1.setColor(VBase4(0,0,0,1))
				Headlight2.setColor(VBase4(0,0,0,1))
			
		def headlights():
			self.headlight_var = (self.headlight_var + 1) % 2
			
		def update_rpm():
			
			#Simulate RPM
			if self.start == 1:
				if self.gear == 0:
					self.RPM = self.RPM - self.RPM / 400
				else:
					self.RPM = self.RPM + self.carspeed / 9
					self.RPM = self.RPM - self.RPM / 200
			
			#Reset RPM to 0 when engine is off
			if self.start == 0:
				if self.RPM > 0.0:
					self.RPM = self.RPM - 40
				if self.RPM < 10:
					self.RPM = 0.0
								
			#Idle RPM power
			if self.start == 1:
				if self.RPM < 650:
					self.RPM = self.RPM + 4
				if self.RPM < 600:
					self.clutch = 1
				else:
					self.clutch = 0
					
			#RPM limit		
			if self.RPM > 6000:
				self.RPM = 6000
				

		#Controls 
		inputState.watchWithModifiers("F", "arrow_up")
		inputState.watchWithModifiers("B", "arrow_down")
		inputState.watchWithModifiers("L", "arrow_left")
		inputState.watchWithModifiers("R", "arrow_right")
		
		do = DirectObject()
		
		do.accept("escape", show_menu)
		do.accept("1", V1)
		do.accept("2", V2)
		do.accept("3", V3)
		do.accept("page_up", up)
		do.accept("page_down", down)
		do.accept("x-repeat", start_function)
		do.accept("x", stop_function)
		do.accept("p", parkingbrake)
		do.accept("backspace", rotate)
		do.accept("enter", horn)
		do.accept("f12", take_screenshot)
		do.accept("h", headlights)
		
		#The ground
		self.ground = BulletPlaneShape(Vec3(0, 0, 1,), 1)
		self.ground_node = BulletRigidBodyNode("The ground")
		self.ground_node.addShape(self.ground)
		self.ground_np = render.attachNewNode(self.ground_node)
		self.ground_np.setPos(0, 0, -2)
		scene.attachRigidBody(self.ground_node)
		
		self.ground_model = loader.loadModel("Models/plane.egg")
		self.ground_model.reparentTo(render)
		self.ground_model.setPos(0,0,-1)
		self.ground_model.setScale(3)
		self.ground_tex = loader.loadTexture("Textures/ground.png")
		self.ground_tex2 = loader.loadTexture("Textures/ground2.png")
		self.ground_tex3 = loader.loadTexture("Textures/ground3.png")
		self.ground_model.setTexture(self.ground_tex, 1)
		
		#The car
		Car_shape = BulletBoxShape(Vec3(1, 2.0, 1.0))
		Car_node = BulletRigidBodyNode("The Car")
		Car_node.setMass(1200.0)
		Car_node.addShape(Car_shape)
		Car_np = render.attachNewNode(Car_node)
		Car_np.setPos(0,0,3)
		Car_np.setHpr(0,0,0)
		Car_np.node().setDeactivationEnabled(False)
		scene.attachRigidBody(Car_node)
		
		Car_model = loader.loadModel("Models/Car.egg")
		Car_model.reparentTo(Car_np)
		Car_tex = loader.loadTexture("Textures/Car1.png")
		Car_model.setTexture(Car_tex, 1)
		
		self.Car_sim = BulletVehicle(scene, Car_np.node())
		self.Car_sim.setCoordinateSystem(ZUp)
		scene.attachVehicle(self.Car_sim)
		
		#The inside of the car
		Car_int = loader.loadModel("Models/inside.egg")
		Car_int.reparentTo(Car_np)
		Car_int_tex = loader.loadTexture("Textures/inside.png")
		Car_int.setTexture(Car_int_tex, 1)
		Car_int.setTransparency(TransparencyAttrib.MAlpha)
		
		#The steering wheel
		Sw = loader.loadModel("Models/Steering wheel.egg")
		Sw.reparentTo(Car_np)
		Sw.setPos(0.25,0,-0.025)
		
		#The first headlight
		Headlight1 = Spotlight("Headlight1")
		lens = PerspectiveLens()
		lens.setFov(180)
		Headlight1.setLens(lens)
		Headlight1np = render.attachNewNode(Headlight1)
		Headlight1np.reparentTo(Car_np)
		Headlight1np.setPos(-0.8,2.5,-0.5)
		Headlight1np.setP(-15)
		render.setLight(Headlight1np)
		
		#The second headlight
		Headlight2 = Spotlight("Headlight2")
		Headlight2.setLens(lens)
		Headlight2np = render.attachNewNode(Headlight2)
		Headlight2np.reparentTo(Car_np)
		Headlight2np.setPos(0.8,2.5,-0.5)
		Headlight2np.setP(-15)
		render.setLight(Headlight2np)
		
		#Sounds
		self.horn_sound = loader.loadSfx("Sounds/horn.ogg")
		self.start_sound = loader.loadSfx("Sounds/enginestart.ogg")
		self.engine_idle_sound = loader.loadSfx("Sounds/engineidle.ogg")
		self.engine_idle_sound.setLoop(True)
		self.accelerate_sound = loader.loadSfx("Sounds/enginethrottle.ogg")
				
		#Camera
		base.disableMouse()
		camera.reparentTo(Car_np)
		camera.setPos(0,-15,3)
		camera.setHpr(0,-10,0)
		
		#Wheel function
		def Wheel(pos, np, r, f):
			w = self.Car_sim.createWheel()
			w.setNode(np.node())
			w.setChassisConnectionPointCs(pos)
			w.setFrontWheel(f)
			w.setWheelDirectionCs(Vec3(0, 0, -1))
			w.setWheelAxleCs(Vec3(1, 0, 0))
			w.setWheelRadius(r)
			w.setMaxSuspensionTravelCm(40)
			w.setSuspensionStiffness(120)
			w.setWheelsDampingRelaxation(2.3)
			w.setWheelsDampingCompression(4.4)
			w.setFrictionSlip(50)
			w.setRollInfluence(0.1)
		
		#Wheels	
		w1_np = loader.loadModel("Models/Lwheel")
		w1_np.reparentTo(render)
		w1_np.setColorScale(0,6)
		Wheel(Point3(-1,1,-0.6), w1_np, 0.4, False)
		
		w2_np = loader.loadModel("Models/Rwheel")
		w2_np.reparentTo(render)
		w2_np.setColorScale(0,6)
		Wheel(Point3(-1.1,-1.2,-0.6), w2_np, 0.4, True)
		
		w3_np = loader.loadModel("Models/Lwheel")
		w3_np.reparentTo(render)
		w3_np.setColorScale(0,6)
		Wheel(Point3(1.1,-1,-0.6), w3_np, 0.4, True)
		
		w4_np = loader.loadModel("Models/Rwheel")
		w4_np.reparentTo(render)
		w4_np.setColorScale(0,6)
		Wheel(Point3(1,1,-0.6), w4_np, 0.4, False)
		

		
		#The engine and steering
		def processInput(dt):
			
			#Vehicle properties
			self.steeringClamp = 35.0
			self.steeringIncrement = 70
			engineForce = 0.0
			brakeForce = 0.0
			
			
			#Get the vehicle's current speed
			self.carspeed = self.Car_sim.getCurrentSpeedKmHour()
			
			
			#Engage clutch when in gear 0
			if self.gear == 0:
				self.clutch = 1
			
			
			#Slow the steering when at higher speeds
			self.steeringIncrement = self.steeringIncrement - self.carspeed / 1.5
			
			
			#Reset the steering
			if not inputState.isSet("L") and not inputState.isSet("R"):
				
				if self.steering < 0.00:
					self.steering = self.steering + 0.6
				if self.steering > 0.00:
					self.steering = self.steering - 0.6
					
				if self.steering < 1.0 and self.steering > -1.0:
					self.steering = 0
			
			
			#Slow the car down while it's moving
			if self.clutch == 0:
				brakeForce = brakeForce + self.carspeed / 5
			else:
				brakeForce = brakeForce + self.carspeed / 15
		
			
			#Forward
			if self.start == 1:
				if inputState.isSet("F"):
					self.RPM = self.RPM + 35
					self.accelerate_sound.play()
				if self.clutch == 0:
					
					if self.gear == -1:
						if self.carspeed > self.carmaxreversespeed:	
							engineForce = -self.RPM / 3
							
					if self.gear == 1:
						if self.carspeed < self.carmaxspeed:
							engineForce = self.RPM / 1

			
			#Brake	
			if inputState.isSet("B"):
				engineForce = 0.0
				brakeForce = 12.0
				if self.gear != 0 and self.clutch == 0:
					self.RPM = self.RPM - 20
				
			#Left	
			if inputState.isSet("L"):
				if self.steering < 0.0:
					#This makes the steering reset at the correct speed when turning from right to left
					self.steering += dt * self.steeringIncrement + 0.6
					self.steering = min(self.steering, self.steeringClamp)
				else:
					#Normal steering
					self.steering += dt * self.steeringIncrement
					self.steering = min(self.steering, self.steeringClamp)
			
			#Right	
			if inputState.isSet("R"):
				if self.steering > 0.0:
					#This makes the steering reset at the correct speed when turning from left to right
					self.steering -= dt * self.steeringIncrement + 0.6
					self.steering = max(self.steering, -self.steeringClamp)
				else:
					#Normal steering
					self.steering -= dt * self.steeringIncrement
					self.steering = max(self.steering, -self.steeringClamp)
			
			#Park
			if self.Pbrake == 1:
				brakeForce = 10.0
				if self.gear != 0 and self. clutch == 0:
					self.RPM = self.RPM - 20
				
				
			#Apply forces to wheels	
			self.Car_sim.applyEngineForce(engineForce, 0);
			self.Car_sim.applyEngineForce(engineForce, 3);
			self.Car_sim.setBrake(brakeForce, 1);
			self.Car_sim.setBrake(brakeForce, 2);
			self.Car_sim.setSteeringValue(self.steering, 0);
			self.Car_sim.setSteeringValue(self.steering, 3);
			
			#Steering wheel
			Sw.setHpr(0,0,-self.steering*10)
		
		
		#The HUD
		self.gear_hud = OnscreenImage(image = "Textures/gear_hud.png", pos = (-1,0,-0.85), scale = (0.2))
		self.gear_hud.setTransparency(TransparencyAttrib.MAlpha)
		
		self.gear2_hud = OnscreenImage(image = "Textures/gear2_hud.png", pos = (-1,0,-0.85), scale = (0.2))
		self.gear2_hud.setTransparency(TransparencyAttrib.MAlpha)
		
		self.starter = OnscreenImage(image = "Textures/starter.png", pos = (-1.2,0,-0.85), scale = (0.15))
		self.starter.setTransparency(TransparencyAttrib.MAlpha)
		
		self.park = OnscreenImage(image = "Textures/pbrake.png", pos = (-0.8,0,-0.85), scale = (0.1))
		self.park.setTransparency(TransparencyAttrib.MAlpha)
		
		self.rev_counter = OnscreenImage(image = "Textures/dial.png", pos = (-1.6, 0.0, -0.70), scale = (0.6,0.6,0.4))
		self.rev_counter.setTransparency(TransparencyAttrib.MAlpha)
		
		self.rev_needle = OnscreenImage(image = "Textures/needle.png", pos = (-1.6, 0.0, -0.70), scale = (0.5))
		self.rev_needle.setTransparency(TransparencyAttrib.MAlpha)
		
		self.rev_text = OnscreenText(text = " ", pos = (-1.6, -0.90, 0), scale = 0.05)
		
		self.speedometer = OnscreenImage(image = "Textures/dial.png", pos = (-1.68, 0.0, -0.10), scale = (0.7,0.7,0.5))
		self.speedometer.setTransparency(TransparencyAttrib.MAlpha)
		
		self.speedometer_needle = OnscreenImage(image = "Textures/needle.png", pos = (-1.68, 0.0, -0.10), scale = (0.5))
		self.speedometer_needle.setTransparency(TransparencyAttrib.MAlpha)
		
		self.speedometer_text = OnscreenText(text = " ", pos = (-1.68, -0.35, 0), scale = 0.05)
		
		
		#Update the HUD
		def Update_HUD():
			
			#Move gear selector
			if self.gear == -1:
				self.gear2_hud.setPos(-1,0,-0.785)
			if self.gear == 0:
				self.gear2_hud.setPos(-1,0,-0.85)
			if self.gear == 1:
				self.gear2_hud.setPos(-1,0,-0.91)
				
			#Rotate starter
			if self.start == 0:
				self.starter.setHpr(0,0,0)
			else:
				self.starter.setHpr(0,0,45)	
				
			#Update the parking brake light
			if self.Pbrake == 1:
				self.park.setImage("Textures/pbrake2.png")
				self.park.setTransparency(TransparencyAttrib.MAlpha)
			else:
				self.park.setImage("Textures/pbrake.png")
				self.park.setTransparency(TransparencyAttrib.MAlpha)	
				
			#Update the rev counter
			self.rev_needle.setR(self.RPM/22)	
			rev_string = str(self.RPM)[:4]
			self.rev_text.setText(rev_string+" RPM")
			
			#Update the speedometer
			if self.carspeed > 0.0:
				self.speedometer_needle.setR(self.carspeed*2.5)
			if self.carspeed < 0.0:
				self.speedometer_needle.setR(-self.carspeed*2.5)
			speed_string = str(self.carspeed)[:3]
			self.speedometer_text.setText(speed_string+" KPH")
					
					
						
		#Update the program
		def update(task):
			dt = globalClock.getDt() 
			processInput(dt)
			Update_HUD()
			set_time()
			set_terrain()
			set_headlights()
			update_rpm()
			scene.doPhysics(dt, 5, 1.0/180.0)
			return task.cont
			
		taskMgr.add(update, "Update")
Beispiel #5
0
class Jugador(DirectObject):
    # Les variables que tinguin un # son canviables, i les que tinguin ## depenen de la nau
    WIN_WIDTH = 800  #
    H_WIDTH = WIN_WIDTH / 2
    WIN_HEIGHT = 600  #
    H_HEIGHT = WIN_HEIGHT / 2

    CAM_FOV = 51.0
    CAM_FOV_RAD = radians(CAM_FOV) / 2
    CAM_FOV_RAD_TAN = tan(CAM_FOV_RAD)

    VEL_MAX_AVIO = 100  ##
    VEL_MIN_AVIO = 30  ##
    VEL_AVIO_RECTE = 40.0  ##
    VEL_TOMBA_AVIO = 90.0  ##
    VEL_COSTAT = 30.0  ##
    ACCELERACIO = 35  ##
    CAMERA_Y = -9  ##
    BALA_VEL_BASE = 500  ##

    QUIT_KEY = "escape"  #
    ACCELERATE_KEY = "w"  #
    DECELERATE_KEY = "s"  #
    RIGHT_KEY = "d"  #
    LEFT_KEY = "a"  #
    CENTRA_RATA_KEY = "c"  #
    SHOOT_KEYS = ["mouse1", "e"]  #
    SHOOT_TIME = 0.15  ##

    def __init__(self, base, ini_pos=Point3(0, 100, 100), tipus="kamikaze", wwidth=None, wheight=None):
        DirectObject.__init__(self)

        if wwidth and wheight:
            self.WIN_WIDTH = wwidth
            self.H_WIDTH = self.WIN_WIDTH / 2
            self.WIN_HEIGHT = wheight
            self.H_HEIGHT = self.WIN_HEIGHT / 2

        self.keyMap = {"shoot": 0, "centerPointer": 0, "turn": 0}
        self.bulletClock = 0.0
        self.overheatClock = 0.0

        self.BALA_VEL = self.BALA_VEL_BASE + self.VEL_MIN_AVIO

        ambient = AmbientLight("alight")
        ambientNp = render.attachNewNode(ambient)
        ambient.setColor(VBase4(0.3, 0.3, 0.3, 1.0))

        self.avio = render.attachNewNode("avio")
        self.avio.setHpr(randint(0, 359), randint(0, 359), randint(0, 359))
        self.avio.setPos(ini_pos)

        self.avioR = self.avio.attachNewNode("avioDum2")
        if tipus == "kamikaze":
            self.modelAvio = base.loader.loadModel("prova/avio1blend")
        else:
            self.modelAvio = base.loader.loadModel("prova/avio1blend")

        self.modelAvio.reparentTo(self.avioR)
        self.avioVel = self.VEL_MIN_AVIO
        self.balaDreta = self.modelAvio.find("**/BalaDreta")
        self.balaEsquerra = self.modelAvio.find("**/BalaEsquerra")
        self.avio.setLight(ambientNp)
        self.avio.setAntialias(AntialiasAttrib.MMultisample)

        self.modelAvio.setColor(1, 1, 0, 1)
        self.modelAvio.setScale(0.51)

        lightBales = AmbientLight("dlight")
        self.lightBalesNp = base.camera.attachNewNode(lightBales)
        self.lightBalesNp.setHpr(0, 0, 0)

        # -#-#-#-configuracio de camara
        base.disableMouse()
        # ~ self.oobe()
        base.camera.reparentTo(self.avio)
        base.camera.setHpr(self.avio, 0, 0, 0)
        base.camera.setPos(self.avio, 0, self.CAMERA_Y, 1.5)
        base.camLens.setFov(self.CAM_FOV * (4.0 / 3.0), self.CAM_FOV)

        self.mirilla2 = OnscreenImage(image="prova/textures/areatir2.png", parent=pixel2d)
        self.mirilla2.setScale(128)
        self.mirilla2.setTransparency(1)
        self.mirilla2.setPos(self.H_WIDTH, 0, -self.H_HEIGHT)

        self.mirilla = base.loader.loadModel("prova/textures/fixador.egg")
        self.mirilla.reparentTo(pixel2d)
        self.mirilla.setScale(64.0)
        self.mirilla.setPos(0, 0, 0)
        self.mirilla.find("**/+SequenceNode").node().pose(0)

        self.cursorGirar = pixel2d.attachNewNode("cursorGirar")
        self.cursorGirarImage = OnscreenImage(image="prova/textures/fletxa.png", parent=self.cursorGirar)
        self.cursorGirarImage.setScale(16.0 / 2, 1.0, 32.0 / 2)
        self.cursorGirarImage.setPos(0, 0, 0)
        self.cursorGirarImage.setHpr(-90, 0, -90)
        self.cursorGirarImage.setTransparency(1)

        cursorGirarEffect = BillboardEffect.make(
            up_vector=Vec3(0, 0, 1),
            eye_relative=False,
            axial_rotate=False,
            offset=0.0,
            look_at=self.mirilla2,
            look_at_point=Point3(0, 0, 0),
        )
        self.cursorGirar.setEffect(cursorGirarEffect)

        self.overheats = []
        for i in range(8):
            if i % 2 == 0:
                self.overheats.append(OnscreenImage(image="prova/textures/overheat1.png", parent=pixel2d))
            else:
                self.overheats.append(OnscreenImage(image="prova/textures/overheat2.png", parent=pixel2d))
            self.overheats[i].setScale(32.0, 1.0, 32.0)
            self.overheats[i].setTransparency(1)
            self.overheats[i].hide()
        self.overheats[0].setPos(self.H_WIDTH + 36, 0, -self.H_HEIGHT + 36)
        self.overheats[0].setHpr(0, 0, 0)
        self.overheats[1].setPos(self.H_WIDTH + 36, 0, -self.H_HEIGHT + 36)
        self.overheats[1].setHpr(0, 0, 0)
        self.overheats[2].setPos(self.H_WIDTH + 36, 0, -self.H_HEIGHT - 36)
        self.overheats[2].setHpr(0, 0, 90)
        self.overheats[3].setPos(self.H_WIDTH + 36, 0, -self.H_HEIGHT - 36)
        self.overheats[3].setHpr(0, 0, 90)
        self.overheats[4].setPos(self.H_WIDTH - 36, 0, -self.H_HEIGHT - 36)
        self.overheats[4].setHpr(0, 0, 180)
        self.overheats[5].setPos(self.H_WIDTH - 36, 0, -self.H_HEIGHT - 36)
        self.overheats[5].setHpr(0, 0, 180)
        self.overheats[6].setPos(self.H_WIDTH - 36, 0, -self.H_HEIGHT + 36)
        self.overheats[6].setHpr(0, 0, -90)
        self.overheats[7].setPos(self.H_WIDTH - 36, 0, -self.H_HEIGHT + 36)
        self.overheats[7].setHpr(0, 0, -90)

        # PARTICLE SYSTEM SETUP
        self.particlesDummy = render.attachNewNode("particlesDummy")
        self.particlesDummy.setPosHprScale(0, 0, 0, 0, 0, 0, 1, 1, 1)
        self.particlesDummy.clearLight(render.find("dlight"))
        self.particlesDummy.setLight(self.lightBalesNp)
        base.enableParticles()

        # COLLISIONS
        base.cTrav = CollisionTraverser()
        base.cTrav.setRespectPrevTransform(True)
        self.balaCol = CollisionNode("balaCol")
        self.balaCol.setIntoCollideMask(BitMask32.allOff())
        self.balaCol.setFromCollideMask(BitMask32(0x00000001))
        balaColSolid = CollisionSphere(0.0, 0.0, 0.0, 0.2)
        self.balaCol.addSolid(balaColSolid)

        self.pickRay = CollisionNode("pickRay")
        self.pickRayNp = base.camera.attachNewNode(self.pickRay)
        self.pickRay.setIntoCollideMask(BitMask32.allOff())
        self.pickRay.setFromCollideMask(BitMask32(0x00000002))
        self.pickRayCHandler = CollisionHandlerQueue()

        self.mouseRay = CollisionRay()
        self.pickRay.addSolid(self.mouseRay)
        self.mouseRay.setOrigin(0, 0, 0)

        base.cTrav.addCollider(self.pickRayNp, self.pickRayCHandler)

        # ~ self.nearPlane = CollisionNode("nearPlane")
        # ~ self.nearPlaneNp = base.camera.attachNewNode(self.nearPlane)
        # ~ base.camRays.setIntoCollideMask(BitMask32(0x00000001))
        # ~ self.nearPlaneNp.setPos(0, 1, 0)
        # ~ self.nearPlaneColSolid = CollisionPlane(Plane(Vec3(0, -1, 0), Point3(0, 1, 0)))
        # ~ self.nearPlane.addSolid(self.nearPlaneColSolid)
        def giraAvio(task):
            timeVar = globalClock.getDt()
            point = base.win.getPointer(0)
            pointerx = point.getX()
            pointery = point.getY()
            self.mouseRay.setFromLens(base.camNode, pointerx, pointery)
            # Cursors de la pantalla
            self.mirilla.setPos(pointerx, 0, -pointery)
            self.cursorGirar.setPos(pointerx, 0, -pointery)
            r = pow(abs(pointery - self.H_HEIGHT), 2) + pow(abs(pointerx - self.H_WIDTH), 2)
            if r > 8000:
                self.mirilla.hide()
                self.cursorGirar.show()
            else:
                self.mirilla.show()
                self.cursorGirar.hide()
                # 3D
            pointerx = pointerx - self.H_WIDTH
            pointery = pointery - self.H_HEIGHT

            self.avioR.setX(self.avio, -pointerx * 3.0 / float(self.WIN_WIDTH))
            self.avioR.setZ(self.avio, pointery * 3.0 / (self.WIN_HEIGHT))

            self.avio.setH(self.avio, -pointerx * 256.0 / self.WIN_WIDTH * timeVar)
            self.avio.setP(self.avio, -pointery * 256.0 / self.WIN_HEIGHT * timeVar)

            self.avioR.setR(self.avio, pointerx / 10.0)
            self.avioR.setP(self.avio, pointery / 70.0)
            self.avioR.setH(self.avio, -pointerx / 50.0)

            # ~ self.avioVel += self.avioAcc*timeVar
            # ~ self.avio.setPos(self.avio, self.avioVel*timeVar)
            return task.cont

        def propulsaAvio(acceleracio, task):
            self.avioVel += acceleracio * globalClock.getDt()
            if self.avioVel < self.VEL_MIN_AVIO:
                self.avioVel = self.VEL_MIN_AVIO
            elif self.avioVel > self.VEL_MAX_AVIO:
                self.avioVel = self.VEL_MAX_AVIO
            self.BALA_VEL = self.BALA_VEL_BASE + self.avioVel
            # MOSTRA LA VELOCITAT
            pos = float(self.avioVel - self.VEL_MIN_AVIO) / (self.VEL_MAX_AVIO - self.VEL_MIN_AVIO)
            base.camera.setY(self.CAMERA_Y - pos * 4)
            # ~ self.marcaVelocitat.setX(MARCAVEL_INI_X+pos*137.)
            return task.cont

        self.haCremat = False

        def mouAvio(task):
            timeVar = globalClock.getDt()
            self.avio.setPos(self.avio, 0, self.avioVel * timeVar, 0)

            if self.keyMap["shoot"] == 1:
                if self.bulletClock <= 0.0:
                    self.bulletClock = self.SHOOT_TIME
                    if not self.haCremat:
                        if self.overheatClock > 16:
                            self.haCremat = True
                            self.overheatClock = 18
                        else:
                            self.overheatClock += self.SHOOT_TIME
                            shoot()

                else:
                    self.bulletClock -= timeVar
            else:
                self.bulletClock = 0.0
                self.overheatClock -= timeVar
            if self.overheatClock < 16:
                self.haCremat = False
            if self.haCremat:
                self.overheatClock -= timeVar

            if self.overheatClock < 0:
                self.overheatClock = 0
            elif self.overheatClock < 2:
                self.overheats[0].hide()
            elif self.overheatClock < 4:
                self.overheats[1].hide()
                self.overheats[0].show()
            elif self.overheatClock < 6:
                self.overheats[2].hide()
                self.overheats[1].show()
            elif self.overheatClock < 8:
                self.overheats[3].hide()
                self.overheats[2].show()
            elif self.overheatClock < 10:
                self.overheats[4].hide()
                self.overheats[3].show()
            elif self.overheatClock < 12:
                self.overheats[5].hide()
                self.overheats[4].show()
            elif self.overheatClock < 14:
                self.overheats[6].hide()
                self.overheats[5].show()
                self.overheats[7].hide()
            elif self.overheatClock < 16:
                self.overheats[7].hide()
                self.overheats[6].show()
            else:
                self.overheats[7].show()

            if self.keyMap["turn"] == 1:
                self.avio.setX(self.avio, -self.VEL_COSTAT * timeVar)
            elif self.keyMap["turn"] == -1:
                self.avio.setX(self.avio, self.VEL_COSTAT * timeVar)

            return task.cont

        def avioRecte(task):
            p = self.avio.getP(render)
            if p > 170 or p < -170:
                return task.cont
            timeVar = globalClock.getDt()
            roll = self.avio.getR(render)
            if roll < -self.VEL_AVIO_RECTE * timeVar:
                self.avio.setR(render, roll + self.VEL_AVIO_RECTE * timeVar)
            elif roll <= self.VEL_AVIO_RECTE * timeVar:
                self.avio.setR(render, 0)
            else:
                self.avio.setR(render, roll - self.VEL_AVIO_RECTE * timeVar)
            return task.cont

        self.balaPositiu = True

        def shoot():
            bala = self.particlesDummy.attachNewNode("balaDummy")
            balaImage = OnscreenImage(image="prova/textures/bala.png", parent=bala)
            balaImage.setTransparency(1)
            balaImage.setScale(0.1, 1.0, 0.2)
            balaImage.setBillboardPointEye()
            bala.setQuat(self.modelAvio.getQuat(render))
            if self.balaPositiu:
                bala.setPos(self.balaDreta.getPos(render))
                self.balaPositiu = False
            else:
                bala.setPos(self.balaEsquerra.getPos(render))
                self.balaPositiu = True
            balaSphere = bala.attachNewNode(self.balaCol)
            balaColHandler = CollisionHandlerQueue()
            base.cTrav.addCollider(balaSphere, balaColHandler)
            # ~ if type(self.shootPoint) == 'libpanda.Point3':
            # ~ bala.lookAt(self.shootPoint)
            # ~ else: bala.setH(bala, 180.)
            taskMgr.add(mouBala, "moubala", extraArgs=[bala, balaImage, self.BALA_VEL, balaColHandler], appendTask=True)

        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

        def suprimir(bala, expbala):
            bala.detachNode()
            expbala.cleanup()
            expbala.detachNode()

        def setKey(key, value):
            self.keyMap[key] = value

        def centraRatoli():
            point = base.win.getPointer(0)
            x = point.getX()
            y = point.getY()
            x -= self.H_WIDTH
            y -= self.H_HEIGHT
            r = sqrt(pow(abs(y), 2) + pow(abs(x), 2))

            def centra(t, x, y):
                base.win.movePointer(0, trunc(x * t) + self.H_WIDTH, trunc(y * t) + self.H_HEIGHT)

            i = LerpFunc(
                centra,
                fromData=1.0,
                toData=0.0,
                duration=r / 700.0,
                blendType="easeInOut",
                extraArgs=[x, y],
                name="centraRata",
            )
            i.start()

        self.previousPos = 0
        self.interval01 = LerpPosHprInterval(
            self.modelAvio,
            0.5,
            Point3(3, 0, 0),
            VBase3(0, 0, 70),
            Point3(0, 0, 0),
            VBase3(0, 0, 0),
            blendType="easeInOut",
        )
        self.interval10 = LerpPosHprInterval(
            self.modelAvio,
            0.5,
            Point3(0, 0, 0),
            VBase3(0, 0, 0),
            Point3(-3, 0, 0),
            VBase3(0, 0, -70),
            blendType="easeInOut",
        )
        self.interval02 = LerpPosHprInterval(
            self.modelAvio,
            0.5,
            Point3(-3, 0, 0),
            VBase3(0, 0, -70),
            Point3(0, 0, 0),
            VBase3(0, 0, 0),
            blendType="easeInOut",
        )
        self.interval20 = LerpPosHprInterval(
            self.modelAvio,
            0.5,
            Point3(0, 0, 0),
            VBase3(0, 0, 0),
            Point3(3, 0, 0),
            VBase3(0, 0, 70),
            blendType="easeInOut",
        )
        self.interval12 = LerpPosHprInterval(
            self.modelAvio,
            1.0,
            Point3(-3, 0, 0),
            VBase3(0, 0, -70),
            Point3(3, 0, 0),
            VBase3(0, 0, 70),
            blendType="easeInOut",
        )
        self.interval21 = LerpPosHprInterval(
            self.modelAvio,
            1.0,
            Point3(3, 0, 0),
            VBase3(0, 0, 70),
            Point3(-3, 0, 0),
            VBase3(0, 0, -70),
            blendType="easeInOut",
        )

        def allIntervalsStopped():
            if (
                self.interval01.isStopped()
                and self.interval10.isStopped()
                and self.interval02.isStopped()
                and self.interval20.isStopped()
                and self.interval12.isStopped()
                and self.interval21.isStopped()
            ):
                return True
            else:
                return False

        def tombaAvio(task):
            if self.keyMap["turn"] == 0 and self.previousPos != 0 and allIntervalsStopped():
                if self.previousPos == 1:
                    self.interval10.start()
                else:
                    self.interval20.start()
                self.previousPos = 0
            elif self.keyMap["turn"] == -1 and self.previousPos != -1 and allIntervalsStopped():
                if self.previousPos == 0:
                    self.interval01.start()
                else:
                    self.interval21.start()
                self.previousPos = -1
            elif self.keyMap["turn"] == 1 and self.previousPos != 1 and allIntervalsStopped():
                if self.previousPos == 0:
                    self.interval02.start()
                else:
                    self.interval12.start()
                self.previousPos = 1
            return task.cont

        def anim1():
            self.mirilla.find("**/+SequenceNode").node().setPlayRate(1.0)
            self.mirilla.find("**/+SequenceNode").node().play(0, 3)

        def anim2():
            self.mirilla.find("**/+SequenceNode").node().setPlayRate(1.0)
            self.mirilla.find("**/+SequenceNode").node().play(4, 8)

        def anim3():
            self.mirilla.find("**/+SequenceNode").node().setPlayRate(-1.0)
            self.mirilla.find("**/+SequenceNode").node().play(0, 3)

        def anim4():
            self.mirilla.find("**/+SequenceNode").node().setPlayRate(-1.0)
            self.mirilla.find("**/+SequenceNode").node().play(3, 8)
            # events

        self.accept(self.QUIT_KEY, sysExit, [0])
        self.accept(
            self.ACCELERATE_KEY,
            taskMgr.add,
            [propulsaAvio, "propulsaAvio1", None, [self.ACCELERACIO], None, None, True],
        )
        self.accept(self.ACCELERATE_KEY + "-up", taskMgr.remove, ["propulsaAvio1"])

        self.accept(
            self.DECELERATE_KEY,
            taskMgr.add,
            [propulsaAvio, "propulsaAvio2", None, [-self.ACCELERACIO], None, None, True],
        )
        self.accept(self.DECELERATE_KEY + "-up", taskMgr.remove, ["propulsaAvio2"])

        for key in self.SHOOT_KEYS:
            self.accept(key, setKey, ["shoot", 1])
            self.accept(key + "-up", setKey, ["shoot", 0])

        self.accept(self.RIGHT_KEY, setKey, ["turn", -1])
        self.accept(self.LEFT_KEY, setKey, ["turn", 1])
        self.accept(self.RIGHT_KEY + "-up", setKey, ["turn", 0])
        self.accept(self.LEFT_KEY + "-up", setKey, ["turn", 0])

        self.accept(self.CENTRA_RATA_KEY, centraRatoli)

        self.accept("n", anim1)
        self.accept("m", anim2)
        self.accept("v", anim3)
        self.accept("b", anim4)

        taskMgr.add(giraAvio, "GiraAvio")
        taskMgr.add(mouAvio, "MouAvio")
        taskMgr.add(avioRecte, "avioRecte")
        taskMgr.add(tombaAvio, "tombaAvio")
Beispiel #6
0
class miniMap(object):
    
    def __init__(self, mainActor):
        
        self.teamMateImage = 'models/hexahedron_blue.png'
        self.heroImage = 'models/mainHero2.png'
        self.miniMapImage = 'models/miniMap000.png'
        self.towerImage = 'models/tower_neitral.png'
        
        self.map = OnscreenImage(image = self.miniMapImage, pos=(-0.7, 0, 0.8), 
                              scale=(MAP_SCALEX, 0, MAP_SCALEY))
        
        self.map.setTransparency(1)
        #self.map.reparentTo(rander)

        self.hero = OnscreenImage(image=self.heroImage, pos=(mainActor.getX()/525, 0, mainActor.getY()/160), 
                                    scale=(HERO_SCALE, 1, HERO_SCALE), 
                                    hpr=(0, 0, mainActor.getH()))
        self.hero.reparentTo(self.map)
        self.hero.setTransparency(1)
        
        self.npc = {}
        
        self.tower = {}
        
        self.team = {}
    
    def resizeScreen(self, x, y):
        if x != 800 and y != 600:
            self.map.setPos(-1.4, 0, 0.8)
        else:
            self.map.setPos(-0.7, 0, 0.8)   
            
        return self.map
                
    def setMap(self, mapScale, x, y):
        self.map = OnscreenImage(image = self.miniMapImage, pos=(x, 0, y), 
                              scale=(mapScale, mapScale, mapScale))
        return self.map
        
    def setHero(self, heroScale, x, y, h):
        self.hero = OnscreenImage(image=self.heroImage, pos=(x, 0, y), 
                                   scale=(heroScale, 1, heroScale), 
                                   hpr=(0, 0, h))
        return self.hero
    
    def updateHeroPos(self, getX, getY):
        if getX <= 0 and getY <= 0:
            ay = (MAP_AY + (getY))/MAP_AY
            y = MAP_SCALEY-(ay*MAP_SCALEY)
            ax = (MAP_AX + (getX))/MAP_AX
            x = MAP_SCALEX-(ax*MAP_SCALEX)
        elif getX > 0 and getY < 0:
            ay = (MAP_AY + (getY))/MAP_AY
            y = MAP_SCALEY-(ay*MAP_SCALEY)
            ax = (MAP_BX - (getX))/MAP_BX
            x = -MAP_SCALEX+(ax*MAP_SCALEX)   
        elif getX < 0 and getY > 0:
            ay = (MAP_BY - (getY))/MAP_BY
            y = -MAP_SCALEY+(ay*MAP_SCALEY)
            ax = (MAP_AX + (getX))/MAP_AX
            x = MAP_SCALEX-(ax*MAP_SCALEX)
        else:
            ay = (MAP_BY - (getY))/MAP_BY
            y = -MAP_SCALEY+(ay*MAP_SCALEY)
            ax = (MAP_BX - (getX))/MAP_BX
            x = -MAP_SCALEX+(ax*MAP_SCALEX)      
            
        self.hero.setPos(x, 0, y) 
        
    def updateHeroHpr(self, getH):
        h = -getH
        self.hero.setHpr(0, 0, h)  
    
    def setNpc(self, npcName, npcImage, npcScale, x, y):
        self.Nps = OnscreenImage(image=npcImage, pos=(x, 0, y), 
                                 scale=(npcScale*MAP_SCALEY, 1, npcScale*MAP_SCALEX))
        self.Nps.reparentTo(self.map)
        self.Nps.setTransparency(1)
        self.npc[npcName] = self.Nps

        return self.npc
        
    def delNpc(self, npcName):
        del self.npc[npcName]
    
    def setTower(self, towerName, towerScale, x, y):
        self.tower_ = OnscreenImage(image=self.towerImage, pos=(x, 0, y), 
                                 scale=(towerScale*MAP_SCALEY, 1, towerScale*MAP_SCALEX))
        self.tower_.reparentTo(self.map)
        self.tower_.setTransparency(1)
        self.tower[towerName] = self.tower_

        return self.tower
    
    def changeTowerColor(self, towerName, towerImage):
        self.tower[towerName].setImage(towerImage)
        
    def delTower(self, towerName):
        del self.tower[towerName]
        
    def setTeamMate(self, mateName, mateScale, getX, getY):
        if getX <= 0 and getY <= 0:
            ay = (MAP_AY + (getY))/MAP_AY
            y = MAP_SCALEY-(ay*MAP_SCALEY)
            ax = (MAP_AX + (getX))/MAP_AX
            x = MAP_SCALEX-(ax*MAP_SCALEX)
        elif getX > 0 and getY < 0:
            ay = (MAP_AY + (getY))/MAP_AY
            y = MAP_SCALEY-(ay*MAP_SCALEY)
            ax = (MAP_BX - (getX))/MAP_BX
            x = -MAP_SCALEX+(ax*MAP_SCALEX)   
        elif getX < 0 and getY > 0:
            ay = (MAP_BY - (getY))/MAP_BY
            y = -MAP_SCALEY+(ay*MAP_SCALEY)
            ax = (MAP_AX + (getX))/MAP_AX
            x = MAP_SCALEX-(ax*MAP_SCALEX)
        else:
            ay = (MAP_BY - (getY))/MAP_BY
            y = -MAP_SCALEY+(ay*MAP_SCALEY)
            ax = (MAP_BX - (getX))/MAP_BX
            x = -MAP_SCALEX+(ax*MAP_SCALEX)
            
        self.teamMate = OnscreenImage(image=self.teamMateImage, 
                                      pos=(x, 0, y), 
                                      scale=(mateScale*MAP_SCALEY, 1, mateScale*MAP_SCALEX))
        self.teamMate.reparentTo(self.map)
        self.teamMate.setTransparency(1)
        self.team[mateName] = self.teamMate
        
        return self.team
    
    def updateTeamMatePos(self, mateName, getX, getY):
        if getX <= 0 and getY <= 0:
            ay = (MAP_AY + (getY))/MAP_AY
            y = MAP_SCALEY-(ay*MAP_SCALEY)
            ax = (MAP_AX + (getX))/MAP_AX
            x = MAP_SCALEX-(ax*MAP_SCALEX)
        elif getX > 0 and getY < 0:
            ay = (MAP_AY + (getY))/MAP_AY
            y = MAP_SCALEY-(ay*MAP_SCALEY)
            ax = (MAP_BX - (getX))/MAP_BX
            x = -MAP_SCALEX+(ax*MAP_SCALEX)   
        elif getX < 0 and getY > 0:
            ay = (MAP_BY - (getY))/MAP_BY
            y = -MAP_SCALEY+(ay*MAP_SCALEY)
            ax = (MAP_AX + (getX))/MAP_AX
            x = MAP_SCALEX-(ax*MAP_SCALEX)
        else:
            ay = (MAP_BY - (getY))/MAP_BY
            y = -MAP_SCALEY+(ay*MAP_SCALEY)
            ax = (MAP_BX - (getX))/MAP_BX
            x = -MAP_SCALEX+(ax*MAP_SCALEX)
            
        self.team[mateName].setPos(x, 0, y) 
     
    def updateTeamMateHpr(self, mateName, getH):
        h = -getH
        self.team[mateName].setHpr(0, 0, h) 
        
    def delTeamMate(self, mateName):
        del self.team[mateName]

            
Beispiel #7
0
class MyApp(ShowBase):
    def __init__(self,
                 rows,
                 cols,
                 instance=0,
                 picturesConcentration=5,
                 trial=0):
        self.trial = trial
        ShowBase.__init__(self)
        self.setIntitalValues(rows, cols, instance, picturesConcentration)

    def initPictures(self):
        self.pictures = listFiles()
        self.pictures.remove('pictures/.DS_Store')  #???
        for i in range(len(self.pictures)):
            self.pictures[i] = picToAscii(self.pictures[i], 'foo.txt')

    def splashScreenCreate(self, number):
        text1a = " Urgent message from ur PC:"
        text1b = "XyzBugz234VirusThingamajig, a very competent virus has taken over your computer..."
        text1c = " It has also managed to put you in a virtual ASCII maze in your computer! "
        text1d = " (because thats a thing that can happen) "
        text2a = "But dont worry, the antivirus software installed on your computer 'BFREE4EVR' will help you escape..."
        text2b = "Drag your favorite pictures (preferably jpeg) to the 'pictures' folder in the directory of the game. "
        text2c = "You'll see these pictures in ASCII format in the maze. BFREE4EVR will add messages in these pictures to help guide you."
        text2d = "Look for the hidden message in each picture you see; it will tell you whether you're om the right track or not."
        text2e = "if you're not on the right track, you should 'backtrack' to the last turn (hint ;) )"
        text3a = "Find the flag to complete the maze! (the flag is the only object thats not in black and white)"
        text3b = "Press 'h' at any time to toggle the help mini-sreen once the game starts."
        text3c = "There is also a helpful mini-map in the bottom right corner of ur screen, that shows the cells of the maze you've visited"
        text3d = "Be sure to solve the maze within the time limit indicated in the top left corner, or ur pc will b compromised."
        text3e = "However, the first level does not have a timer, so you can get comfortable with the controls"
        text3f = "The pictures may look glitchy because of the virus. You have to search them from a close distance. Good luck!"
        subtext = "[press q to continue]"
        text4a = "This is a buffer screen. Please dont panic. 'BFREE4EVR' is doing its thing. "
        text4b = "This may take anywhere from 30 seconds (regular case) to an eternity depending on how shitty ur pc is."
        text4d = "Oh! Almost forgot, policy requires that u provide BFREE4EVR consent to run on ur pc "
        text4c = "...\n...\n...\n...\n...\n...\n..."
        text4e = "[press q to provide consent and agree to terms and conditions etc and continue with loading game]"
        text4f = "...................This is another buffer screen................."
        text4g = "press q to start loading model, and then wait  a while"

        if number == 1:
            splashText = "\n".join([text1a, text1b, text1c, text1d, subtext])
        if number == 2:
            splashText = "\n".join(
                [text2a, text2b, text2c, text2d, text2e, subtext])
        if number == 3:
            splashText = "\n".join(
                [text3a, text3b, text3c, text3d, text3e, text3f, subtext])
        #if number ==4:splashText = "\n".join([text4a,text4b])
        if number == 4:
            if self.instance == 0:
                splashText = "\n".join(
                    [text4a, text4b, text4c, text4d, text4e])
            else:
                splashText = "\n".join([text4f, text4g])
        text = TextNode('meh')
        text.setCardColor(1, 1, 1, 1)  # white
        text.setCardAsMargin(0.2, 0.2, 20, 0.2)
        text.setCardDecal(True)
        text.setText(splashText)
        text.setAlign(TextNode.ALeft)
        text.setFrameColor(0, 0, 0, 1)  # black, and not transparent
        text.setTextColor(0, 0, 0, 1)  # black, and not transparent
        text.setFrameAsMargin(0.2, 0.2, 20, 0.2)  #specifying margins for frame
        text.setShadow(0.05, 0.05)
        text.setShadowColor(0, 0, 0, 1)
        textNodePath = self.aspect2d.attachNewNode(text)
        self.splashTextObject = textNodePath
        textNodePath.setPos(-1.1, 0, 0.8)
        textNodePath.setScale(0.1)
        text.setWordwrap(22)

    def setIntitalValues(self, rows, cols, instance, picturesConcentration):
        self.picturesConcentration = picturesConcentration
        self.rows, self.cols = rows, cols
        self.instance = instance
        if instance == 0:
            self.splashScreen = 1
            self.splashScreenCreate(1)
        else:
            self.splashScreenCreate(4)
            self.splashScreen = 4
        self.mode = "splashScreen"
        #some key mapping
        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "backward": 0,
            "stop": False,
            "camLeft": 0,
            "camRight": 0,
            "camForward": 0,
            "camBackward": 0
        }
        self.keyMap["up"], self.keyMap["down"] = [
            0, 0
        ]  # only for debugging purposes, will be removed from actual game
        self.keyMap["createNewGame"] = 0
        self.keyMap["nextScreen"] = 0
        self.createKeyControls()
        timer = 0.2
        taskMgr.doMethodLater(timer, self.move, "move")

        #self.setMazeValues(self.rows, self.cols)

    def setMazeValues(self, rows, cols):
        self.gameWon = False
        if self.instance > 0:  #timer stuff
            secondsTimer = 1  #(measures seconds)
            self.time = 46
            if self.instance == 2:
                self.time = 61  # bigger maze, more time.. :/
            taskMgr.doMethodLater(secondsTimer, self.timer, "timer")
            self.timerText = TextNode('time?')
            self.timerText.setAlign(TextNode.ALeft)
            self.timerText.setFrameColor(0, 1, 0,
                                         1)  # black, and not transparent
            self.timerText.setTextColor(0, 1, 0,
                                        1)  # black, and not transparent
            self.timerText.setFrameAsMargin(0.2, 0.2, 0.2,
                                            0.2)  #specifying margins for frame
            self.timerText.setShadow(0.05, 0.05)
            self.timerText.setShadowColor(0, 0, 0, 1)
            timeTextNodePath = self.aspect2d.attachNewNode(self.timerText)
            timeTextNodePath.setPos(-1.3, 0, 0.75)
            timeTextNodePath.setScale(0.06)
        self.initPictures()
        self.gameOver = False
        # Load the environment model.
        self.scene = self.loader.loadModel("box.egg")
        # Reparent the model to render.
        self.scene.reparentTo(self.render)
        #self.buffer = OnscreenImage(image = 'out2.jpg', pos = (0, 0, 0)) # adding buffer image
        #building the maze:
        self.randMaze, self.solution = maze.generateDifficultMaze(rows, cols)
        # The mickey picture I'm using was taken from: https://s-media-cache-ak0.pinimg.com/236x/9b/a2/57/9ba25796112cad616be27e473ae1e149.jpg
        #self.buffer.destroy()
        self.boxWidth = 200.0  #550
        self.boxHeight = 200.0  #550
        self.wallHeight = 30.0
        # above values found by trial and error. I think this gives the best user experience
        min, max = self.scene.getTightBounds()
        size = max - min
        (self.width,
         self.height) = (self.boxWidth * cols, self.boxHeight * rows
                         )  # calculating dimesions of scene
        # Apply scale and position transforms on the model.
        self.scene.setPos(self.width / 2, self.height / 2,
                          0)  # so that left bottom corner is (0,0)
        self.scene.setScale(self.width / size[0], self.height / size[1], 1)
        self.xWallBounds = []
        self.yWallBounds = []

        self.buildMaze(rows, cols)
        self.taskMgr.add(self.CameraView, "CameraView")

        #initalizing some more values
        self.CamOreintX, self.CamOreintY = 0, 0
        self.angleRadians = 0
        self.camZpos = self.wallHeight * 2
        self.moveUnit = 5.0
        self.deltaAngle = 1
        self.text1a = "use (W,A,S,D) to change camera orientation (up, left, down, right)"
        self.text1b = "use arrow keys to move camera forward, backward, left or right"
        self.text1c = "press z to move camera up, x to move camera down."
        self.text1d = "press h to toggle these annoying instructions"
        self.text1 = "\n".join(
            [self.text1a, self.text1b, self.text1c, self.text1d])

        #show instructions on screen
        self.showInstructions = False
        if self.instance == 0: self.Instructions()
        y = self.height
        #creating image shown at bootom left corner
        self.cellsVisited = set()
        self.imageWidth = 200
        self.imageHeight = 200
        self.imageMap = Image.new('RGB', (self.imageWidth, self.imageHeight),
                                  "lightGrey")
        self.imageMap.save("out0.jpg")
        self.imageObject = OnscreenImage(image='out0.jpg', pos=(0, 0, 0))
        maze.colourCell(self.imageMap, "darkGrey", 0, 0,
                        self.imageWidth / cols, self.imageHeight / rows,
                        self.imageHeight)
        self.count = 0
        self.oldRow, self.oldCol = 0, 0
        self.updateImage()
        self.hasImageObject = True
        # Add the CameraView procedure to the task manager.
        self.taskMgr.add(self.CameraView, "CameraView")

    def updateImage(self):
        currRow = int(self.camYpos // self.boxHeight)
        currCol = int(self.camXpos // self.boxWidth)
        (rows, cols) = (len(self.randMaze), len(self.randMaze[0]))
        boxWidth = self.imageWidth / cols
        boxHeight = self.imageHeight / rows
        imageName = "out" + str(self.count) + "trial" + str(
            self.trial) + ".jpg"
        r = self.angleRadians * (180.0 / pi)
        if self.oldRow != currRow or self.oldCol != currCol:
            maze.colourCell(self.imageMap, "white", self.oldRow, self.oldCol,
                            boxWidth, boxHeight, self.imageHeight)
            maze.colourCell(self.imageMap, "darkGrey", currRow, currCol,
                            boxWidth, boxHeight, self.imageHeight)
            self.imageMap.save(imageName)
            self.imageObject.destroy()
            self.oldRow, self.oldCol = currRow, currCol
            self.imageObject = OnscreenImage(image=imageName,
                                             pos=(0.85, 0, -0.65),
                                             scale=(0.25, 1, 0.25),
                                             hpr=(0, 0, r))
            self.count += 1
            imageName = "out" + str(self.count) + "trial" + str(
                self.trial) + ".jpg"

        if (currRow, currCol) not in self.cellsVisited:
            self.cellsVisited.add((currRow, currCol))
            maze.drawCell(self.imageMap, self.randMaze, currRow, currCol,
                          boxWidth, boxHeight, self.imageHeight)
            self.imageMap.save(imageName)
            self.imageObject.destroy()
            self.imageObject = OnscreenImage(image=imageName,
                                             pos=(0.85, 0, -0.65),
                                             scale=(0.25, 1, 0.25),
                                             hpr=(0, 0, r))
            self.count += 1

    def gameWonOrLost(self):
        if self.gameWon:
            if self.instance == 0:
                text = "U WON THE GAME !!1!1!!1\n lol just kidding. You won level one!\n press P to go to the next level\n(Fewer pictures, bigger maze) "
            if self.instance == 1:
                text = "GoOd JoB 1!!!1!1!! YOu KnoW tHE drILl! neXT leVEl comiNg up.\n press P to go to the next level"
            if self.instance == 2:
                text = "U WON THE GAME !!1!1!!1 YOu escaped the virus.\n(for realz this time YAY!)\nPress P to play again! "
        else:
            text = "You just lost the level you noob.\nLuckily, you get infinite chances.\nPress P to try again."

        self.text = TextNode('bleh')
        self.text.setAlign(TextNode.ACenter)
        self.text.setText(text)
        textNodePath = aspect2d.attachNewNode(self.text)
        textNodePath.setScale(0.09)
        self.text.setCardColor(0, 0, 0, 1)
        self.text.setCardAsMargin(20, 20, 20, 20)
        self.text.setCardDecal(True)
        self.gameOver = True
        self.imageObject.destroy()
        self.hasImageObject = False

        #print("gameOver is "+str(self.gameOver))

    def newGame(self):
        self.text.clearText()
        self.deleteAll()
        taskMgr.remove('move')
        taskMgr.remove('CameraView')
        taskMgr.remove('timer')
        self.destroy()
        self.deleteImages()
        if self.gameWon:  # next level or restart
            if self.instance == 2:
                self.__init__(5, 5, 0, 5, self.trial + 1)  #reset
            else:
                self.__init__(self.rows + 2, self.cols + 2, self.instance + 1,
                              self.picturesConcentration + 2, self.trial + 1)
        else:
            self.__init__(self.rows, self.cols, self.instance,
                          self.picturesConcentration,
                          self.trial + 1)  # same level

    def deleteAll(self):
        for m in render.getChildren():
            m.removeNode()

    def deleteImages(self):
        for i in range(self.count):
            filename = "out" + str(i) + "trial" + str(self.trial) + ".jpg"
            os.remove(filename)

    def addPicture(self, x, y, h, row, col):
        if not probability(self.picturesConcentration): return
        i = random.randint(0, len(self.pictures) - 1)
        pictureText = self.pictures[i]
        if (row, col) in self.solution:
            pictureText = addMessage(pictureText, "you're on the right track!")
        else:
            pictureText = addMessage(pictureText,
                                     "looks like you took a wrong turn!")
        z = 66
        text = TextNode('node name')
        text.setCardColor(1, 1, 1, 1)  # white
        text.setCardAsMargin(0, 0, 0, 0)
        text.setCardDecal(True)
        #contentsRead = readFile("mickeyText.txt")
        text.setText(pictureText)
        text.setAlign(TextNode.ALeft)
        font = loader.loadFont(
            'Menlo.ttf'
        )  # font dowloaded from : "http://www.onlinewebfonts.com"
        text.setFont(font)
        text.setFrameColor(0, 0, 0, 1)  # black, and not transparent
        text.setTextColor(0, 0, 0, 1)  # black, and not transparent
        text.setFrameAsMargin(0.2, 0.2, 0.1,
                              0.1)  #specifying margins for frame
        text.setShadow(0.05, 0.05)
        text.setShadowColor(0, 0, 0, 1)
        textNodePath = self.render.attachNewNode(text)
        textNodePath.setPos(x, y, z)
        textNodePath.setHpr(h, 0, 0)
        textNodePath.setScale(0.6)

    def buildMaze(self, rows, cols):
        randMaze, solution = self.randMaze, self.solution
        maze.createImage(randMaze, 400, 400)
        self.endPoints = solution[-1]
        self.winXbounds = []
        boxWidth = self.boxWidth
        boxHeight = self.boxHeight
        wallWidth = self.wallWidth = 5.0
        print(boxWidth, boxHeight, wallWidth)
        wallHeight = self.wallHeight
        wall = loader.loadModel("box.egg")
        min, max = wall.getTightBounds()
        size = max - min
        (initialWidth, intialHeight) = (size[0], size[1])  # of box.egg
        k = wallWidth  # added to wall length to guarantee smooth corners

        for row in range(rows):
            for col in range(cols):
                walls = randMaze[row][col]
                #creating walls:
                if (walls[0] == 1):  #Nwall
                    (startX, startY, endX,
                     endY) = (col * boxWidth, row * boxHeight,
                              (col + 1) * boxWidth, row * boxHeight)
                    self.addWall(startX, startY, endX, endY, True, boxWidth,
                                 boxHeight, wallWidth, wallHeight,
                                 initialWidth, intialHeight, k)
                    self.addPicture(startX + wallWidth + boxWidth / 2,
                                    endY + 0.8 * wallWidth, 180, row, col)

                if (walls[1] == 1):
                    (startX, startY, endX,
                     endY) = ((col + 1) * boxWidth, row * boxHeight,
                              (col + 1) * boxWidth, (row + 1) * boxHeight)
                    if col == cols - 1:  #Ewall
                        self.addWall(startX, startY, endX, endY, False,
                                     boxWidth, boxHeight, wallWidth,
                                     wallHeight, initialWidth, intialHeight, k)
                    self.addPicture(endX - 0.8 * wallWidth,
                                    startY + wallWidth + boxHeight / 2, 270,
                                    row, col)

                if (walls[2] == 1):
                    (startX, startY, endX,
                     endY) = (col * boxWidth, (row + 1) * boxHeight,
                              (col + 1) * boxWidth, (row + 1) * boxHeight)
                    if row == rows - 1:  #Swall
                        self.addWall(startX, startY, endX, endY, True,
                                     boxWidth, boxHeight, wallWidth,
                                     wallHeight, initialWidth, intialHeight, k)
                    self.addPicture(startX + wallWidth + boxWidth / 2,
                                    endY - 0.8 * wallWidth, 0, row, col)

                if (walls[3] == 1):  #Wwall
                    (startX, startY, endX,
                     endY) = (col * boxWidth, row * boxHeight, col * boxWidth,
                              (row + 1) * boxHeight)  # vertical
                    self.addWall(startX, startY, endX, endY, False, boxWidth,
                                 boxHeight, wallWidth, wallHeight,
                                 initialWidth, intialHeight, k)
                    self.addPicture(endX + 0.8 * wallWidth,
                                    startY + wallWidth + boxHeight / 2, 90,
                                    row, col)

        for row in range(rows + 1):
            for col in range(cols + 1):
                (x, y, z) = (col * boxWidth, row * boxHeight, 0)
                model = loader.loadModel("box.egg")
                model.setScale(wallWidth, wallWidth, wallHeight)
                model.reparentTo(render)
                model.setPos(x, y, z)
                MyApp.applyRandomTexture(model, 0)
                (min, max) = model.getTightBounds()
                (minX, minY, maxX, maxY) = (min[0], min[1], max[0], max[1])
                k = 2  # panda renders weirdly at certain viewpoints if one gets too close to model :?
                self.xWallBounds += [(minX - k, maxX + k)]
                self.yWallBounds += [(minY - k, maxY + k)]

        self.initializeStartAndEnd(boxWidth, boxHeight, wallHeight,
                                   self.endPoints)
        self.splashTextObject.removeNode()
        #self.addFlag() #adds flag to end position

    def initializeStartAndEnd(self, boxWidth, boxHeight, wallHeight,
                              endPoints):
        #initializing start position of camera:
        self.camXpos = boxWidth / 2
        self.camYpos = boxHeight / 2
        # adding flag to end of maze as recored by the solution
        model = loader.loadModel(
            "banner/banner.egg"
        )  # model from http://alice.org/pandagallery/Medieval/index.html
        model.reparentTo(render)
        lo, hi = model.getTightBounds()
        size = hi - lo
        intialHeight = size[0]
        (endRow, endCol) = endPoints
        model.setPos(endCol * boxWidth + boxWidth / 2,
                     endRow * boxHeight + boxHeight / 2, 0)
        scaleFactor = wallHeight * 0.7 / intialHeight
        model.setScale(scaleFactor, scaleFactor, scaleFactor)
        tex = loader.loadTexture('banner/bannero_3_-_Default_CL.tif')
        model.setTexture(tex)

    def addWall(self, startX, startY, endX, endY, isHorizontal, boxWidth,
                boxHeight, wallWidth, wallHeight, initialWidth, intialHeight,
                k):
        model = loader.loadModel("box.egg")
        if isHorizontal:
            model.setScale(boxWidth / initialWidth - k, wallWidth,
                           wallHeight)  #horizontalWall
        else:
            model.setScale(wallWidth, boxHeight / intialHeight - k,
                           wallHeight)  #verticallWall
        self.addModel(startX, startY, endX, endY, model, wallWidth, True)
        MyApp.applyRandomTexture(model, 1)

    @staticmethod
    def applyRandomTexture(model, i):
        textures = ['blackWhite1.jpeg', 'blackWhite2.jpg']
        # blacWhite2 from http://cdn.pcwallart.com/images/gradient-black-to-white-square-wallpaper-4.jpg
        # blackWhite1 from http://cdn.pcwallart.com/images/gradient-black-to-white-wallpaper-2.jpg
        tex = loader.loadTexture(textures[i])
        model.setTexture(tex)

    def addModel(self, startX, startY, endX, endY, model, wallWidth,
                 isHorizontal):
        x = (startX + endX) / 2
        y = (startY + endY) / 2
        z = 0
        #print(self.xWallBounds, self.yWallBounds)
        #print(self.width, self.height, self.boxWidth, self.boxHeight, wallWidth)
        model.reparentTo(render)
        model.setPos(x, y, z)
        (min, max) = model.getTightBounds()
        (minX, minY, maxX, maxY) = (min[0], min[1], max[0], max[1])
        k = 2  # panda renders weirdly at certain viewpoints if one gets too close to model :?
        self.xWallBounds += [(minX - k, maxX + k)]
        self.yWallBounds += [(minY - k, maxY + k)]

    def setKey(self, key, value):
        self.keyMap[key] = value

    def createKeyControls(self):
        self.accept("r", self.setKey, ["stop", not self.keyMap["stop"]])
        self.accept("h", self.Instructions)
        self.accept("z", self.setKey, ["up", 1])
        self.accept("x", self.setKey, ["down", 1])
        self.accept("q", self.nextSplashScreen)
        self.accept("p", self.setKey, ["createNewGame", 1])

        self.accept("arrow_up", self.setKey, ["forward", 1])
        self.accept("arrow_down", self.setKey, ["backward", 1])
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_right", self.setKey, ["right", 1])

        self.accept("arrow_up-up", self.setKey, ["forward", 0])
        self.accept("arrow_down-up", self.setKey, ["backward", 0])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right-up", self.setKey, ["right", 0])

        self.accept("w", self.setKey, ["camForward", 1])
        self.accept("s", self.setKey, ["camBackward", 1])
        self.accept("a", self.setKey, ["camLeft", 1])
        self.accept("d", self.setKey, ["camRight", 1])

        self.accept("w-up", self.setKey, ["camForward", 0])
        self.accept("s-up", self.setKey, ["camBackward", 0])
        self.accept("a-up", self.setKey, ["camLeft", 0])
        self.accept("d-up", self.setKey, ["camRight", 0])

        self.accept("z-up", self.setKey, ["up", 0])
        self.accept("x-up", self.setKey, ["down", 0])

    def nextSplashScreen(self):
        self.splashTextObject.removeNode()
        self.splashScreen += 1
        if self.splashScreen > 5: self.splashScreen = 5
        print(self.splashScreen)
        if self.splashScreen == 5 and self.mode == "splashScreen":
            self.mode = "game"
            self.setMazeValues(self.rows, self.cols)
        elif self.mode == "splashScreen":
            self.splashScreenCreate(self.splashScreen)

    def cameraMove(self, dy, dx):
        self.camYpos += dy
        self.camXpos += dx
        for i in range(len(self.xWallBounds)):
            xInterval = self.xWallBounds[i]
            (xLow, xHigh) = (xInterval[0], xInterval[1])
            yInterval = self.yWallBounds[i]
            (yLow, yHigh) = (yInterval[0], yInterval[1])
            if (xLow <= self.camXpos <= xHigh
                    and yLow <= self.camYpos <= yHigh) or self.camZpos <= 1:
                self.camXpos -= dx
                self.camYpos -= dy
                #print(self.camXpos,self.camYpos, xLow, xHigh, yLow, yHigh)
                return
        (winRow, winCol) = self.endPoints
        k = 30  # you must go into winning cell
        (winXlow, winXhigh) = (winCol * self.boxWidth + k,
                               (winCol + 1) * self.boxWidth - k)
        (winYlow, winYhigh) = (winRow * self.boxHeight + k,
                               (winRow + 1) * self.boxHeight - k)
        if winXlow < self.camXpos < winXhigh and winYlow < self.camYpos < winYhigh:
            self.gameWon = True
            self.gameWonOrLost()
        self.updateImage()

    def Instructions(self):
        if self.showInstructions:
            self.textObject1.removeNode()
            self.showInstructions = False
        else:
            text = TextNode('eh')
            text.setCardColor(1, 1, 1, 1)  # white
            text.setCardAsMargin(0, 0, 0, 0)
            text.setCardDecal(True)
            text.setText(self.text1)
            text.setAlign(TextNode.ALeft)
            text.setFrameColor(0, 0, 0, 1)  # black, and not transparent
            text.setTextColor(0, 0, 0, 1)  # black, and not transparent
            text.setFrameAsMargin(0, 0, 0, 0)  #specifying margins for frame
            text.setShadow(0.05, 0.05)
            text.setShadowColor(0, 0, 0, 1)
            textNodePath = self.aspect2d.attachNewNode(text)
            self.textObject1 = textNodePath
            textNodePath.setPos(-1.3, 0, -0.5)
            textNodePath.setScale(0.06)
            self.showInstructions = True

    def timer(self, task):
        self.time -= 1
        self.timerText.setText("time left: " + str(self.time) + " seconds")
        if self.time == 5:
            self.timerText.setFrameColor(1, 0, 0, 1)  # red
            self.timerText.setTextColor(1, 0, 0, 1)  # red
        if self.time == 0:
            self.gameWonOrLost()
            return None  # end task
        return task.again

    def move(self, task):  #direction = (dx, dy, dz)

        if self.mode == "game" and not self.gameOver:

            # since I want to be able move left/right/forward/backwards relative to the current direction,
            # I had to use cos and sin to change the x and y positions
            if self.keyMap["left"] > 0:
                self.cameraMove(-sin(self.angleRadians) * self.moveUnit,
                                -cos(self.angleRadians) * self.moveUnit)
                # bc math lol
            if self.keyMap["right"] > 0:
                self.cameraMove(+sin(self.angleRadians) * self.moveUnit,
                                +cos(self.angleRadians) * self.moveUnit)

            if self.keyMap["forward"] > 0:
                self.cameraMove(
                    cos(self.angleRadians) * self.moveUnit,
                    -sin(self.angleRadians) * self.moveUnit)

            if self.keyMap["backward"] > 0:
                self.cameraMove(-cos(self.angleRadians) * self.moveUnit,
                                +sin(self.angleRadians) * self.moveUnit)

            if self.keyMap["camLeft"] > 0:
                self.CamOreintX += self.deltaAngle

            if self.keyMap["camRight"] > 0:
                self.CamOreintX -= self.deltaAngle

            if self.keyMap["camForward"] > 0:
                self.CamOreintY += self.deltaAngle

            if self.keyMap["camBackward"] > 0:
                self.CamOreintY -= self.deltaAngle

            #for debugging purposes!!!
            if self.keyMap["up"] > 0:
                self.camZpos += self.moveUnit
                if self.camZpos >= self.wallHeight * 2:
                    self.camZpos -= self.moveUnit

            if self.keyMap["down"] > 0:
                self.camZpos -= self.moveUnit
                if self.camZpos <= 1: self.camZpos += self.moveUnit
        if self.mode == "game" and self.gameOver:
            print("here")
            if self.keyMap["createNewGame"] > 0:
                self.newGame()

        if self.keyMap["nextScreen"] > 0 and self.mode == "splash":
            print(self.splashScreen)

        return task.cont

    def CameraView(self, task):
        spinConstant = 0  # makes camera  spin
        angleDegrees = task.time * spinConstant + self.CamOreintX  # spin about the x axis
        self.angleRadians = angleDegrees * (pi / 180.0)
        self.camera.setPos(0 * sin(self.angleRadians) + self.camXpos,
                           -0 * cos(self.angleRadians) + self.camYpos,
                           self.camZpos)
        self.camera.setHpr(angleDegrees, self.CamOreintY, 0)
        if self.hasImageObject: self.imageObject.setHpr(0, 0, angleDegrees)
        return Task.cont
Beispiel #8
0
class Timer:

    def __init__(self, style):
        """
        Timer class with fun pictures
        @param style: 0 = SUN, 1 = MOON, 2 = GUN
        @type style: int
        """
        self.style = style
        VirtualFileSystem.getGlobalPtr().mount(Filename("mf/timer.mf"), ".", VirtualFileSystem.MFReadOnly)
        self.egg = loader.loadModel("timer.egg")
        self.img = None
        self.interval = None

        self.types[style](self)

    def create_sun(self):
        """
        Creates the sun timer
        """

        # load image
        self.img = OnscreenImage(image=self.egg.find('**/sun'), pos=(1.15, 0, 0.75),
                                 color=(255, 255, 0, 1), scale=0.25)

        # interval
        self.interval = LerpFunc(self.run_interval, fromData=1, toData=0, duration=TIME)
        self.interval.start()

        return

    def create_moon(self):
        """
        Creates the moon timer
        """

        # load image
        self.img = OnscreenImage(image=self.egg.find('**/moon-quarter'), pos=(0, 0, 0),
                                 color=(1, 1, 1, 1), scale=0.25)

        # interval
        self.interval = LerpFunc(self.run_interval, fromData=1, toData=0, duration=TIME)
        self.interval.start()

        return

    def create_gun(self):
        """
        Creates the gun timer
        """

        # load image
        self.img = OnscreenImage(image=self.egg.find('**/gun-0'), pos=(1.05, 0, 0.75), scale=0.25)

        # interval
        self.interval = LerpFunc(self.run_interval, fromData=1, toData=0, duration=TIME)
        self.interval.start()

        return

    def run_interval(self, c):
        if self.style == SUN:
            self.img.setColor((1, c, 0, 1))
            self.img.setPos(1.15-(c/4), 0, 0.75+(math.sin(math.pi*c)/10))
        elif self.style == MOON:
            self.img.setColor((1, c, c, 1))
            self.img.setPos(0.9+(c/4), 0, 0.75+(math.sin(math.pi*c)/10))
        elif self.style == GUN:
            self.img.setHpr(0, 0, 360*(1-c)-60)

            if c % (1 / 6) < 0.05:
                if c % (1 / 6) > 0.025:
                    self.img.setColor((1, 40*(c % (1 / 6)), 40*(c % (1 / 6)), 1))
                else:
                    self.img.setImage(self.egg.find('**/gun-{}'.format(6 - (round(c / (1 / 6))))))
                    self.img.setColor((1, 1-40*(c % (1 / 6)), 1-40*(c % (1 / 6)), 1))
            else:
                self.img.setColor((1, 1, 1, 1))

    def annihilate(self):
        self.interval.finish()
        self.img.destroy()
        loader.unloadModel(self.egg)
        VirtualFileSystem.getGlobalPtr().unmount("mf/timer.mf")
        del self

    types = {
        SUN: create_sun,
        MOON: create_moon,
        GUN: create_gun
    }
Beispiel #9
0
class miniMap(object):
    
    def __init__(self, mainActor):
        
        self.teamMateImage = 'models/hexahedron.png'
        self.heroImage = 'models/mainHero2.png'
        self.miniMapImage = 'models/miniMap000.png'
        self.towerImage = 'models/tower_neitral.png'
        self.towerRed = 'models/tower_red.png'
        self.towerBlue = 'models/tower_blue.png'
        
        self.map = OnscreenImage(image = self.miniMapImage, pos=(-0.7, 0, 0.8), 
                              scale=(MAP_SCALEX, 0, MAP_SCALEY))
        
        self.map.setTransparency(1)
        #self.map.reparentTo(rander)

        self.hero = OnscreenImage(image=self.heroImage, pos=(mainActor.getX()/525, 0, mainActor.getY()/160), 
                                    scale=(HERO_SCALE, 1, HERO_SCALE), 
                                    hpr=(0, 0, mainActor.getH()))
        self.hero.reparentTo(self.map)
        self.hero.setTransparency(1)
        
        self.npc = {}
        
        self.tower = {}
        
        self.team = {}
    
    def resizeScreen(self, x, y):
        if x != 800 and y != 600:
		self.map.setPos(-1.4, 0, 0.8)
        else:
		self.map.setPos(-0.7, 0, 0.8)
                
    def setMap(self, mapScale, x, y):
        self.map = OnscreenImage(image = self.miniMapImage, pos=(x, 0, y), 
                              scale=(mapScale, mapScale, mapScale))
        return self.map
        
    def setHero(self, heroScale, x, y, h):
        self.hero = OnscreenImage(image=self.heroImage, pos=(x, 0, y), 
                                   scale=(heroScale, 1, heroScale), 
                                   hpr=(0, 0, h))
        return self.hero
    
    def updateHeroPos(self, getX, getY):
        if getX <= 0 and getY <= 0:
            ay = (MAP_AY + (getY))/MAP_AY
            y = MAP_SCALEY-(ay*MAP_SCALEY)
            ax = (MAP_AX + (getX))/MAP_AX
            x = MAP_SCALEX-(ax*MAP_SCALEX)
        elif getX > 0 and getY < 0:
            ay = (MAP_AY + (getY))/MAP_AY
            y = MAP_SCALEY-(ay*MAP_SCALEY)
            ax = (MAP_BX - (getX))/MAP_BX
            x = -MAP_SCALEX+(ax*MAP_SCALEX)   
        elif getX < 0 and getY > 0:
            ay = (MAP_BY - (getY))/MAP_BY
            y = -MAP_SCALEY+(ay*MAP_SCALEY)
            ax = (MAP_AX + (getX))/MAP_AX
            x = MAP_SCALEX-(ax*MAP_SCALEX)
        else:
            ay = (MAP_BY - (getY))/MAP_BY
            y = -MAP_SCALEY+(ay*MAP_SCALEY)
            ax = (MAP_BX - (getX))/MAP_BX
            x = -MAP_SCALEX+(ax*MAP_SCALEX)      
            
        self.hero.setPos(x, 0, y) 
        
    def updateHeroHpr(self, getH):
        h = -getH
        self.hero.setHpr(0, 0, h)  
    
    def setNpc(self, npcName, npcImage, npcScale, x, y):
        self.Nps = OnscreenImage(image=npcImage, pos=(x, 0, y), 
                                 scale=(npcScale*MAP_SCALEY, 1, npcScale*MAP_SCALEX))
        self.Nps.reparentTo(self.map)
        self.Nps.setTransparency(1)
        self.npc[npcName] = self.Nps

        return self.npc
        
    def delNpc(self, npcName):
        del self.npc[npcName]
    
    def setTower(self, towerName, towerScale, getX, getY):
	if getX <= 0 and getY <= 0:
            ay = (MAP_AY + (getY))/MAP_AY
            y = MAP_SCALEY-(ay*MAP_SCALEY)
            ax = (MAP_AX + (getX))/MAP_AX
            x = MAP_SCALEX-(ax*MAP_SCALEX)
        elif getX > 0 and getY < 0:
            ay = (MAP_AY + (getY))/MAP_AY
            y = MAP_SCALEY-(ay*MAP_SCALEY)
            ax = (MAP_BX - (getX))/MAP_BX
            x = -MAP_SCALEX+(ax*MAP_SCALEX)   
        elif getX < 0 and getY > 0:
            ay = (MAP_BY - (getY))/MAP_BY
            y = -MAP_SCALEY+(ay*MAP_SCALEY)
            ax = (MAP_AX + (getX))/MAP_AX
            x = MAP_SCALEX-(ax*MAP_SCALEX)
        else:
            ay = (MAP_BY - (getY))/MAP_BY
            y = -MAP_SCALEY+(ay*MAP_SCALEY)
            ax = (MAP_BX - (getX))/MAP_BX
            x = -MAP_SCALEX+(ax*MAP_SCALEX)

        self.tower_ = OnscreenImage(image=self.towerImage, pos=(x, 0, y), 
                                 scale=(towerScale*MAP_SCALEY, 1, towerScale*MAP_SCALEX))
        self.tower_.reparentTo(self.map)
        self.tower_.setTransparency(1)
        self.tower[towerName] = self.tower_

        return self.tower
    
    def changeTowerColor(self, towerName, towerImage):
        self.tower[towerName].setImage(towerImage)
        
    def delTower(self, towerName):
        del self.tower[towerName]
        
    def setTeamMate(self, mateName, mateScale, getX, getY):
        if getX <= 0 and getY <= 0:
            ay = (MAP_AY + (getY))/MAP_AY
            y = MAP_SCALEY-(ay*MAP_SCALEY)
            ax = (MAP_AX + (getX))/MAP_AX
            x = MAP_SCALEX-(ax*MAP_SCALEX)
        elif getX > 0 and getY < 0:
            ay = (MAP_AY + (getY))/MAP_AY
            y = MAP_SCALEY-(ay*MAP_SCALEY)
            ax = (MAP_BX - (getX))/MAP_BX
            x = -MAP_SCALEX+(ax*MAP_SCALEX)   
        elif getX < 0 and getY > 0:
            ay = (MAP_BY - (getY))/MAP_BY
            y = -MAP_SCALEY+(ay*MAP_SCALEY)
            ax = (MAP_AX + (getX))/MAP_AX
            x = MAP_SCALEX-(ax*MAP_SCALEX)
        else:
            ay = (MAP_BY - (getY))/MAP_BY
            y = -MAP_SCALEY+(ay*MAP_SCALEY)
            ax = (MAP_BX - (getX))/MAP_BX
            x = -MAP_SCALEX+(ax*MAP_SCALEX)
            
        self.teamMate = OnscreenImage(image=self.teamMateImage, 
                                      pos=(x, 0, y), 
                                      scale=(mateScale*MAP_SCALEY, 1, mateScale*MAP_SCALEX))
        self.teamMate.reparentTo(self.map)
        self.teamMate.setTransparency(1)
        self.team[mateName] = self.teamMate
        
        return self.team
    
    def updateTeamMatePos(self, mateName, getX, getY):
        if getX <= 0 and getY <= 0:
            ay = (MAP_AY + (getY))/MAP_AY
            y = MAP_SCALEY-(ay*MAP_SCALEY)
            ax = (MAP_AX + (getX))/MAP_AX
            x = MAP_SCALEX-(ax*MAP_SCALEX)
        elif getX > 0 and getY < 0:
            ay = (MAP_AY + (getY))/MAP_AY
            y = MAP_SCALEY-(ay*MAP_SCALEY)
            ax = (MAP_BX - (getX))/MAP_BX
            x = -MAP_SCALEX+(ax*MAP_SCALEX)   
        elif getX < 0 and getY > 0:
            ay = (MAP_BY - (getY))/MAP_BY
            y = -MAP_SCALEY+(ay*MAP_SCALEY)
            ax = (MAP_AX + (getX))/MAP_AX
            x = MAP_SCALEX-(ax*MAP_SCALEX)
        else:
            ay = (MAP_BY - (getY))/MAP_BY
            y = -MAP_SCALEY+(ay*MAP_SCALEY)
            ax = (MAP_BX - (getX))/MAP_BX
            x = -MAP_SCALEX+(ax*MAP_SCALEX)
            
        self.team[mateName].setPos(x, 0, y) 
     
    def updateTeamMateHpr(self, mateName, getH):
        h = -getH
        self.team[mateName].setHpr(0, 0, h) 
        
    def delTeamMate(self, mateName):
        del self.team[mateName]
Beispiel #10
0
class Car(DirectObject):
    def __init__(self, base, world, track):
        super().__init__()

        self.world = world
        self.track = track

        self.steering = 0
        self.accelerator = 0
        self.brake = 0

        self.gear_ratios = [-4, 0, 3.9, 2.9, 2.3, 1.87, 1.68, 1.54, 1.46]
        self.gear = 1
        self.differential_ratio = 4.5
        self.transmission_efficiency = 0.95
        self.wheel_radius = 0.4
        self.drag_coefficient = 0.48
        self.engine_torque_curve = [
            (0, 466),
            (564, 469),
            (1612, 469),
            (2822, 518),
            (3870, 517),
            (4516, 597),
            (5000, 613),
            (5564, 600),
            (6048, 655),
            (6693, 681),
            (7177, 716),
            (7822, 696),
            (8306, 696),
            (11048, 569),
            (13951, 391),
            (15000, 339),
            (15483, 301),
            (16612, 247),
            (17177, 65),
            (18306, 55)
        ]
        self.fw_wingspan = 0.64
        self.fw_cord = 1.01
        self.fw_clift = 0.7
        self.rw_wingspan = 0.64
        self.rw_cord = 0.51
        self.rw_clift = 0.2

        self.car_node = None
        self.car = None

        dial_scale = 0.2

        speed_dial = OnscreenImage(image='tex/speed360.rgb', pos=(-dial_scale, 0, dial_scale),
                                   scale=(dial_scale, 1, dial_scale),
                                   parent=base.a2dBottomCenter)
        speed_dial.setTransparency(TransparencyAttrib.MAlpha)
        self.speed_dial = OnscreenImage(image='tex/dial.rgb', parent=speed_dial)

        rpm_dial = OnscreenImage(image='tex/rpm20000.rgb', pos=(dial_scale, 0, dial_scale),
                                 scale=(dial_scale, 1, dial_scale),
                                 parent=base.a2dBottomCenter)
        rpm_dial.setTransparency(TransparencyAttrib.MAlpha)
        self.rpm_dial = OnscreenImage(image='tex/dial.rgb', parent=rpm_dial)
        self.gear_text = OnscreenText(text='N', pos=(-0.02, -0.67), scale=0.4, parent=rpm_dial, fg=(255, 0, 0, 1))

        self.reset()
        taskMgr.add(self.update, 'update')

    def make_wheel(self, pos, front, np):
        wheel = self.car.createWheel(0.02)

        wheel.setNode(np.node())
        wheel.setChassisConnectionPointCs(pos)
        wheel.setFrontWheel(front)
        wheel.setWheelDirectionCs(Vec3(0, 0, -1))
        wheel.setWheelAxleCs(Vec3(1, 0, 0))
        wheel.setWheelRadius(self.wheel_radius)
        wheel.setSuspensionStiffness(200)
        wheel.setWheelsDampingRelaxation(23)
        wheel.setWheelsDampingCompression(44)
        wheel.setRollInfluence(0.1)
        wheel.setMaxSuspensionTravelCm(10)
        wheel.setFrictionSlip(1.2)
        # wheel.setMaxSuspensionForce(1000)

    def reset(self):
        car = loader.loadModel("models/car.egg")
        car.flattenLight()
        car_bounds = car.getTightBounds()
        car_shape = BulletBoxShape(Vec3((car_bounds[1].x - car_bounds[0].x) / 2,
                                        (car_bounds[1].y - car_bounds[0].y) / 2,
                                        (car_bounds[1].z - car_bounds[0].z) / 2))
        car_ts = TransformState.makePos(Point3(0, 0, 0.5))

        if self.car_node is not None:
            self.car_node.removeNode()

        self.car_node = render.attachNewNode(BulletRigidBodyNode('Car'))
        self.car_node.node().setDeactivationEnabled(False)
        self.car_node.node().setMass(600)
        self.car_node.node().addShape(car_shape, car_ts)
        self.world.attachRigidBody(self.car_node.node())
        car.reparentTo(self.car_node)
        self.car_node.setPos(0, 6, 1)

        self.car = BulletVehicle(self.world, self.car_node.node())
        self.car.setCoordinateSystem(ZUp)
        self.world.attachVehicle(self.car)

        self.car_node.setPos(0, 6, 1)
        self.car_node.setHpr(0, 0, 0)
        self.car.resetSuspension()
        self.car_node.node().clearForces()

        wheel_fl = loader.loadModel("models/wheelL")
        wheel_fl.reparentTo(render)
        self.make_wheel(Point3(-0.4, 1.28, 0), True, wheel_fl)

        wheel_fr = loader.loadModel("models/wheelR")
        wheel_fr.reparentTo(render)
        self.make_wheel(Point3(0.4, 1.28, 0), True, wheel_fr)

        wheel_rl = loader.loadModel("models/wheelL")
        wheel_rl.reparentTo(render)
        self.make_wheel(Point3(-0.4, -1.35, 0), False, wheel_rl)

        wheel_rr = loader.loadModel("models/wheelR")
        wheel_rr.reparentTo(render)
        self.make_wheel(Point3(0.4, -1.35, 0), False, wheel_rr)

    def get_engine_torque(self, rpm):
        min_rpm = min(self.engine_torque_curve, key=lambda p: p[0])
        max_rpm = max(self.engine_torque_curve, key=lambda p: p[0])

        if rpm <= min_rpm[0]:
            return min_rpm[1]
        elif rpm >= max_rpm[0]:
            return 0

        less_rpm = filter(lambda p: p[0] <= rpm, self.engine_torque_curve)
        more_rpm = filter(lambda p: p[0] >= rpm, self.engine_torque_curve)
        max_less_rpm = max(less_rpm, key=lambda p: p[0])
        min_more_rpm = min(more_rpm, key=lambda p: p[0])

        rpm_diff = min_more_rpm[0] - max_less_rpm[0]
        torque_diff = min_more_rpm[1] - max_less_rpm[1]
        slope = torque_diff / rpm_diff
        diff = rpm - max_less_rpm[0]

        return max_less_rpm[1] + (slope * diff)

    @property
    def pos(self):
        return self.car_node.getPos()

    @property
    def forward_vector(self):
        return self.car.getForwardVector()

    def update(self, task):
        car_pos = self.pos
        car_vec = self.forward_vector
        track_bounds = self.track.tight_bounds

        if car_pos.x < track_bounds[0].x or \
                car_pos.x > track_bounds[1].x or \
                car_pos.y < track_bounds[0].y or \
                car_pos.y > track_bounds[1].y or \
                car_pos.z < track_bounds[0].z:
            self.reset()
            return task.cont

        car_speed = self.car.getCurrentSpeedKmHour()
        car_speed_ms = car_speed * 1000 / 3600
        car_speed_abs = abs(car_speed)

        self.car_node.node().clearForces()

        self.apply_wing_force(car_speed_ms)
        self.apply_drag_force(car_speed_ms, car_vec)
        rpm = self.apply_engine_force(car_speed_ms)
        self.apply_brake_force()
        self.apply_steering_moment(car_speed_abs)
        self.update_dials(rpm, car_speed_abs)

        return task.cont

    def apply_wing_force(self, car_speed_ms):
        fw_downforce = 0.5 * self.fw_cord * self.fw_wingspan * self.fw_clift * 1.29 * car_speed_ms ** 2
        rw_downforce = 0.5 * self.rw_cord * self.rw_wingspan * self.rw_clift * 1.29 * car_speed_ms ** 2

        self.car_node.node().applyForce(Vec3(0, 0, -fw_downforce), Point3(-0.61, 2.32, 0.23))
        self.car_node.node().applyForce(Vec3(0, 0, -fw_downforce), Point3(0.61, 2.32, 0.23))
        self.car_node.node().applyForce(Vec3(0, 0, -rw_downforce), Point3(-0.61, -2.47, 1.2))
        self.car_node.node().applyForce(Vec3(0, 0, -rw_downforce), Point3(0.61, -2.47, 1.2))

    def apply_drag_force(self, car_speed_ms, car_vec):
        drag_coefficient = 0.5 * self.drag_coefficient * 1.29 * 5
        drag_force = drag_coefficient * car_speed_ms ** 2
        rr_force = drag_coefficient * 30 * car_speed_ms
        if car_speed_ms < 0:
            drag_force = -drag_force

        self.car_node.node().applyCentralForce(car_vec * -drag_force)
        self.car_node.node().applyCentralForce(car_vec * -rr_force)

    def apply_engine_force(self, car_speed_ms):
        angular_velocity = car_speed_ms / self.wheel_radius
        rpm = angular_velocity * self.gear_ratios[self.gear] * self.differential_ratio * 60 / (2 * math.pi)
        rpm = max(0, rpm)
        engine_torque = self.get_engine_torque(rpm)

        max_engine_force = engine_torque * self.gear_ratios[self.gear] * self.differential_ratio * \
                           self.transmission_efficiency / self.wheel_radius
        engine_force = max_engine_force * (self.accelerator / 128)

        self.car.applyEngineForce(engine_force, 2)
        self.car.applyEngineForce(engine_force, 3)
        return rpm

    def apply_brake_force(self):
        brake_adj = 5
        self.car.setBrake(self.brake * brake_adj, 0)
        self.car.setBrake(self.brake * brake_adj, 1)
        self.car.setBrake(self.brake * brake_adj, 2)
        self.car.setBrake(self.brake * brake_adj, 3)

    def apply_steering_moment(self, car_speed_abs):
        steering_ratio = max((car_speed_abs / 3), 30)
        self.car.setSteeringValue(self.steering / steering_ratio, 0)
        self.car.setSteeringValue(self.steering / steering_ratio, 1)

    def update_dials(self, rpm, car_speed_abs):
        min_rpm = min(self.engine_torque_curve, key=lambda p: p[0])[0]
        if self.gear == 1:
            min_rpm = max(self.engine_torque_curve, key=lambda p: p[0])[0]

        self.speed_dial.setHpr(0, 0, car_speed_abs * (270 / 360))
        self.rpm_dial.setHpr(0, 0, max(rpm, min_rpm) * (270 / 20000) * (self.accelerator / 128))

    def update_gear_text(self):
        if self.gear >= 2:
            text = str(self.gear - 1)
        elif self.gear == 0:
            text = "R"
        elif self.gear == 1:
            text = "N"
        else:
            text = ""
        self.gear_text.setText(text)

    def down_gear(self):
        self.gear -= 1
        if self.gear < 0:
            self.gear = 0
        self.update_gear_text()

    def up_gear(self):
        self.gear += 1
        if self.gear >= len(self.gear_ratios):
            self.gear = len(self.gear_ratios) - 1
        self.update_gear_text()
Beispiel #11
0
class Jugador(DirectObject):
    #Les variables que tinguin un # son canviables, i les que tinguin ## depenen de la nau
    WIN_WIDTH = 800  #
    H_WIDTH = WIN_WIDTH / 2
    WIN_HEIGHT = 600  #
    H_HEIGHT = WIN_HEIGHT / 2

    CAM_FOV = 51.
    CAM_FOV_RAD = radians(CAM_FOV) / 2
    CAM_FOV_RAD_TAN = tan(CAM_FOV_RAD)

    VEL_MAX_AVIO = 100  ##
    VEL_MIN_AVIO = 30  ##
    VEL_AVIO_RECTE = 40.  ##
    VEL_TOMBA_AVIO = 90.  ##
    VEL_COSTAT = 30.  ##
    ACCELERACIO = 35  ##
    CAMERA_Y = -9  ##
    BALA_VEL_BASE = 500  ##

    QUIT_KEY = "escape"  #
    ACCELERATE_KEY = "w"  #
    DECELERATE_KEY = "s"  #
    RIGHT_KEY = "d"  #
    LEFT_KEY = "a"  #
    CENTRA_RATA_KEY = "c"  #
    SHOOT_KEYS = ["mouse1", "e"]  #
    SHOOT_TIME = .15  ##

    def __init__(self,
                 base,
                 ini_pos=Point3(0, 100, 100),
                 tipus="kamikaze",
                 wwidth=None,
                 wheight=None):
        DirectObject.__init__(self)

        if wwidth and wheight:
            self.WIN_WIDTH = wwidth
            self.H_WIDTH = self.WIN_WIDTH / 2
            self.WIN_HEIGHT = wheight
            self.H_HEIGHT = self.WIN_HEIGHT / 2

        self.keyMap = {"shoot": 0, "centerPointer": 0, "turn": 0}
        self.bulletClock = 0.
        self.overheatClock = 0.

        self.BALA_VEL = self.BALA_VEL_BASE + self.VEL_MIN_AVIO

        ambient = AmbientLight("alight")
        ambientNp = render.attachNewNode(ambient)
        ambient.setColor(VBase4(.3, .3, .3, 1.))

        self.avio = render.attachNewNode("avio")
        self.avio.setHpr(randint(0, 359), randint(0, 359), randint(0, 359))
        self.avio.setPos(ini_pos)

        self.avioR = self.avio.attachNewNode("avioDum2")
        if tipus == "kamikaze":
            self.modelAvio = base.loader.loadModel('prova/avio1blend')
        else:
            self.modelAvio = base.loader.loadModel('prova/avio1blend')

        self.modelAvio.reparentTo(self.avioR)
        self.avioVel = self.VEL_MIN_AVIO
        self.balaDreta = self.modelAvio.find("**/BalaDreta")
        self.balaEsquerra = self.modelAvio.find("**/BalaEsquerra")
        self.avio.setLight(ambientNp)
        self.avio.setAntialias(AntialiasAttrib.MMultisample)

        self.modelAvio.setColor(1, 1, 0, 1)
        self.modelAvio.setScale(.51)

        lightBales = AmbientLight('dlight')
        self.lightBalesNp = base.camera.attachNewNode(lightBales)
        self.lightBalesNp.setHpr(0, 0, 0)

        #-#-#-#-configuracio de camara
        base.disableMouse()
        #~ self.oobe()
        base.camera.reparentTo(self.avio)
        base.camera.setHpr(self.avio, 0, 0, 0)
        base.camera.setPos(self.avio, 0, self.CAMERA_Y, 1.5)
        base.camLens.setFov(self.CAM_FOV * (4. / 3.), self.CAM_FOV)

        self.mirilla2 = OnscreenImage(image="prova/textures/areatir2.png",
                                      parent=pixel2d)
        self.mirilla2.setScale(128)
        self.mirilla2.setTransparency(1)
        self.mirilla2.setPos(self.H_WIDTH, 0, -self.H_HEIGHT)

        self.mirilla = base.loader.loadModel("prova/textures/fixador.egg")
        self.mirilla.reparentTo(pixel2d)
        self.mirilla.setScale(64.)
        self.mirilla.setPos(0, 0, 0)
        self.mirilla.find('**/+SequenceNode').node().pose(0)

        self.cursorGirar = pixel2d.attachNewNode("cursorGirar")
        self.cursorGirarImage = OnscreenImage(
            image="prova/textures/fletxa.png", parent=self.cursorGirar)
        self.cursorGirarImage.setScale(16. / 2, 1., 32. / 2)
        self.cursorGirarImage.setPos(0, 0, 0)
        self.cursorGirarImage.setHpr(-90, 0, -90)
        self.cursorGirarImage.setTransparency(1)

        cursorGirarEffect = BillboardEffect.make(up_vector=Vec3(0, 0, 1),
                                                 eye_relative=False,
                                                 axial_rotate=False,
                                                 offset=0.,
                                                 look_at=self.mirilla2,
                                                 look_at_point=Point3(0, 0, 0))
        self.cursorGirar.setEffect(cursorGirarEffect)

        self.overheats = []
        for i in range(8):
            if i % 2 == 0:
                self.overheats.append(
                    OnscreenImage(image="prova/textures/overheat1.png",
                                  parent=pixel2d))
            else:
                self.overheats.append(
                    OnscreenImage(image="prova/textures/overheat2.png",
                                  parent=pixel2d))
            self.overheats[i].setScale(32., 1., 32.)
            self.overheats[i].setTransparency(1)
            self.overheats[i].hide()
        self.overheats[0].setPos(self.H_WIDTH + 36, 0, -self.H_HEIGHT + 36)
        self.overheats[0].setHpr(0, 0, 0)
        self.overheats[1].setPos(self.H_WIDTH + 36, 0, -self.H_HEIGHT + 36)
        self.overheats[1].setHpr(0, 0, 0)
        self.overheats[2].setPos(self.H_WIDTH + 36, 0, -self.H_HEIGHT - 36)
        self.overheats[2].setHpr(0, 0, 90)
        self.overheats[3].setPos(self.H_WIDTH + 36, 0, -self.H_HEIGHT - 36)
        self.overheats[3].setHpr(0, 0, 90)
        self.overheats[4].setPos(self.H_WIDTH - 36, 0, -self.H_HEIGHT - 36)
        self.overheats[4].setHpr(0, 0, 180)
        self.overheats[5].setPos(self.H_WIDTH - 36, 0, -self.H_HEIGHT - 36)
        self.overheats[5].setHpr(0, 0, 180)
        self.overheats[6].setPos(self.H_WIDTH - 36, 0, -self.H_HEIGHT + 36)
        self.overheats[6].setHpr(0, 0, -90)
        self.overheats[7].setPos(self.H_WIDTH - 36, 0, -self.H_HEIGHT + 36)
        self.overheats[7].setHpr(0, 0, -90)

        #PARTICLE SYSTEM SETUP
        self.particlesDummy = render.attachNewNode("particlesDummy")
        self.particlesDummy.setPosHprScale(0, 0, 0, 0, 0, 0, 1, 1, 1)
        self.particlesDummy.clearLight(render.find("dlight"))
        self.particlesDummy.setLight(self.lightBalesNp)
        base.enableParticles()

        #COLLISIONS
        base.cTrav = CollisionTraverser()
        base.cTrav.setRespectPrevTransform(True)
        self.balaCol = CollisionNode("balaCol")
        self.balaCol.setIntoCollideMask(BitMask32.allOff())
        self.balaCol.setFromCollideMask(BitMask32(0x00000001))
        balaColSolid = CollisionSphere(0., 0., 0., .2)
        self.balaCol.addSolid(balaColSolid)

        self.pickRay = CollisionNode("pickRay")
        self.pickRayNp = base.camera.attachNewNode(self.pickRay)
        self.pickRay.setIntoCollideMask(BitMask32.allOff())
        self.pickRay.setFromCollideMask(BitMask32(0x00000002))
        self.pickRayCHandler = CollisionHandlerQueue()

        self.mouseRay = CollisionRay()
        self.pickRay.addSolid(self.mouseRay)
        self.mouseRay.setOrigin(0, 0, 0)

        base.cTrav.addCollider(self.pickRayNp, self.pickRayCHandler)

        #~ self.nearPlane = CollisionNode("nearPlane")
        #~ self.nearPlaneNp = base.camera.attachNewNode(self.nearPlane)
        #~ base.camRays.setIntoCollideMask(BitMask32(0x00000001))
        #~ self.nearPlaneNp.setPos(0, 1, 0)
        #~ self.nearPlaneColSolid = CollisionPlane(Plane(Vec3(0, -1, 0), Point3(0, 1, 0)))
        #~ self.nearPlane.addSolid(self.nearPlaneColSolid)
        def giraAvio(task):
            timeVar = globalClock.getDt()
            point = base.win.getPointer(0)
            pointerx = point.getX()
            pointery = point.getY()
            self.mouseRay.setFromLens(base.camNode, pointerx, pointery)
            #Cursors de la pantalla
            self.mirilla.setPos(pointerx, 0, -pointery)
            self.cursorGirar.setPos(pointerx, 0, -pointery)
            r = pow(abs(pointery - self.H_HEIGHT), 2) + pow(
                abs(pointerx - self.H_WIDTH), 2)
            if r > 8000:
                self.mirilla.hide()
                self.cursorGirar.show()
            else:
                self.mirilla.show()
                self.cursorGirar.hide()
            #3D
            pointerx = (pointerx - self.H_WIDTH)
            pointery = (pointery - self.H_HEIGHT)

            self.avioR.setX(self.avio, -pointerx * 3. / float(self.WIN_WIDTH))
            self.avioR.setZ(self.avio, pointery * 3. / (self.WIN_HEIGHT))

            self.avio.setH(self.avio,
                           -pointerx * 256. / self.WIN_WIDTH * timeVar)
            self.avio.setP(self.avio,
                           -pointery * 256. / self.WIN_HEIGHT * timeVar)

            self.avioR.setR(self.avio, pointerx / 10.)
            self.avioR.setP(self.avio, pointery / 70.)
            self.avioR.setH(self.avio, -pointerx / 50.)

            #~ self.avioVel += self.avioAcc*timeVar
            #~ self.avio.setPos(self.avio, self.avioVel*timeVar)
            return task.cont

        def propulsaAvio(acceleracio, task):
            self.avioVel += acceleracio * globalClock.getDt()
            if self.avioVel < self.VEL_MIN_AVIO:
                self.avioVel = self.VEL_MIN_AVIO
            elif self.avioVel > self.VEL_MAX_AVIO:
                self.avioVel = self.VEL_MAX_AVIO
            self.BALA_VEL = self.BALA_VEL_BASE + self.avioVel
            #MOSTRA LA VELOCITAT
            pos = float(self.avioVel - self.VEL_MIN_AVIO) / (
                self.VEL_MAX_AVIO - self.VEL_MIN_AVIO)
            base.camera.setY(self.CAMERA_Y - pos * 4)
            #~ self.marcaVelocitat.setX(MARCAVEL_INI_X+pos*137.)
            return task.cont

        self.haCremat = False

        def mouAvio(task):
            timeVar = globalClock.getDt()
            self.avio.setPos(self.avio, 0, self.avioVel * timeVar, 0)

            if self.keyMap["shoot"] == 1:
                if self.bulletClock <= 0.:
                    self.bulletClock = self.SHOOT_TIME
                    if not self.haCremat:
                        if self.overheatClock > 16:
                            self.haCremat = True
                            self.overheatClock = 18
                        else:
                            self.overheatClock += self.SHOOT_TIME
                            shoot()

                else:
                    self.bulletClock -= timeVar
            else:
                self.bulletClock = 0.
                self.overheatClock -= timeVar
            if self.overheatClock < 16: self.haCremat = False
            if self.haCremat: self.overheatClock -= timeVar

            if self.overheatClock < 0:
                self.overheatClock = 0
            elif self.overheatClock < 2:
                self.overheats[0].hide()
            elif self.overheatClock < 4:
                self.overheats[1].hide()
                self.overheats[0].show()
            elif self.overheatClock < 6:
                self.overheats[2].hide()
                self.overheats[1].show()
            elif self.overheatClock < 8:
                self.overheats[3].hide()
                self.overheats[2].show()
            elif self.overheatClock < 10:
                self.overheats[4].hide()
                self.overheats[3].show()
            elif self.overheatClock < 12:
                self.overheats[5].hide()
                self.overheats[4].show()
            elif self.overheatClock < 14:
                self.overheats[6].hide()
                self.overheats[5].show()
                self.overheats[7].hide()
            elif self.overheatClock < 16:
                self.overheats[7].hide()
                self.overheats[6].show()
            else:
                self.overheats[7].show()

            if self.keyMap["turn"] == 1:
                self.avio.setX(self.avio, -self.VEL_COSTAT * timeVar)
            elif self.keyMap["turn"] == -1:
                self.avio.setX(self.avio, self.VEL_COSTAT * timeVar)

            return task.cont

        def avioRecte(task):
            p = self.avio.getP(render)
            if p > 170 or p < -170: return task.cont
            timeVar = globalClock.getDt()
            roll = self.avio.getR(render)
            if roll < -self.VEL_AVIO_RECTE * timeVar:
                self.avio.setR(render, roll + self.VEL_AVIO_RECTE * timeVar)
            elif roll <= self.VEL_AVIO_RECTE * timeVar:
                self.avio.setR(render, 0)
            else:
                self.avio.setR(render, roll - self.VEL_AVIO_RECTE * timeVar)
            return task.cont

        self.balaPositiu = True

        def shoot():
            bala = self.particlesDummy.attachNewNode("balaDummy")
            balaImage = OnscreenImage(image="prova/textures/bala.png",
                                      parent=bala)
            balaImage.setTransparency(1)
            balaImage.setScale(.1, 1., .2)
            balaImage.setBillboardPointEye()
            bala.setQuat(self.modelAvio.getQuat(render))
            if self.balaPositiu:
                bala.setPos(self.balaDreta.getPos(render))
                self.balaPositiu = False
            else:
                bala.setPos(self.balaEsquerra.getPos(render))
                self.balaPositiu = True
            balaSphere = bala.attachNewNode(self.balaCol)
            balaColHandler = CollisionHandlerQueue()
            base.cTrav.addCollider(balaSphere, balaColHandler)
            #~ if type(self.shootPoint) == 'libpanda.Point3':
            #~ bala.lookAt(self.shootPoint)
            #~ else: bala.setH(bala, 180.)
            taskMgr.add(
                mouBala,
                "moubala",
                extraArgs=[bala, balaImage, self.BALA_VEL, balaColHandler],
                appendTask=True)

        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

        def suprimir(bala, expbala):
            bala.detachNode()
            expbala.cleanup()
            expbala.detachNode()

        def setKey(key, value):
            self.keyMap[key] = value

        def centraRatoli():
            point = base.win.getPointer(0)
            x = point.getX()
            y = point.getY()
            x -= self.H_WIDTH
            y -= self.H_HEIGHT
            r = sqrt(pow(abs(y), 2) + pow(abs(x), 2))

            def centra(t, x, y):
                base.win.movePointer(0,
                                     trunc(x * t) + self.H_WIDTH,
                                     trunc(y * t) + self.H_HEIGHT)

            i = LerpFunc(centra,
                         fromData=1.,
                         toData=0.,
                         duration=r / 700.,
                         blendType='easeInOut',
                         extraArgs=[x, y],
                         name="centraRata")
            i.start()

        self.previousPos = 0
        self.interval01 = LerpPosHprInterval(self.modelAvio,
                                             .5,
                                             Point3(3, 0, 0),
                                             VBase3(0, 0, 70),
                                             Point3(0, 0, 0),
                                             VBase3(0, 0, 0),
                                             blendType='easeInOut')
        self.interval10 = LerpPosHprInterval(self.modelAvio,
                                             .5,
                                             Point3(0, 0, 0),
                                             VBase3(0, 0, 0),
                                             Point3(-3, 0, 0),
                                             VBase3(0, 0, -70),
                                             blendType='easeInOut')
        self.interval02 = LerpPosHprInterval(self.modelAvio,
                                             .5,
                                             Point3(-3, 0, 0),
                                             VBase3(0, 0, -70),
                                             Point3(0, 0, 0),
                                             VBase3(0, 0, 0),
                                             blendType='easeInOut')
        self.interval20 = LerpPosHprInterval(self.modelAvio,
                                             .5,
                                             Point3(0, 0, 0),
                                             VBase3(0, 0, 0),
                                             Point3(3, 0, 0),
                                             VBase3(0, 0, 70),
                                             blendType='easeInOut')
        self.interval12 = LerpPosHprInterval(self.modelAvio,
                                             1.,
                                             Point3(-3, 0, 0),
                                             VBase3(0, 0, -70),
                                             Point3(3, 0, 0),
                                             VBase3(0, 0, 70),
                                             blendType='easeInOut')
        self.interval21 = LerpPosHprInterval(self.modelAvio,
                                             1.,
                                             Point3(3, 0, 0),
                                             VBase3(0, 0, 70),
                                             Point3(-3, 0, 0),
                                             VBase3(0, 0, -70),
                                             blendType='easeInOut')

        def allIntervalsStopped():
            if self.interval01.isStopped() and self.interval10.isStopped(
            ) and self.interval02.isStopped() and self.interval20.isStopped(
            ) and self.interval12.isStopped() and self.interval21.isStopped():
                return True
            else:
                return False

        def tombaAvio(task):
            if self.keyMap[
                    "turn"] == 0 and self.previousPos != 0 and allIntervalsStopped(
                    ):
                if self.previousPos == 1: self.interval10.start()
                else: self.interval20.start()
                self.previousPos = 0
            elif self.keyMap[
                    "turn"] == -1 and self.previousPos != -1 and allIntervalsStopped(
                    ):
                if self.previousPos == 0: self.interval01.start()
                else: self.interval21.start()
                self.previousPos = -1
            elif self.keyMap[
                    "turn"] == 1 and self.previousPos != 1 and allIntervalsStopped(
                    ):
                if self.previousPos == 0: self.interval02.start()
                else: self.interval12.start()
                self.previousPos = 1
            return task.cont

        def anim1():
            self.mirilla.find('**/+SequenceNode').node().setPlayRate(1.)
            self.mirilla.find('**/+SequenceNode').node().play(0, 3)

        def anim2():
            self.mirilla.find('**/+SequenceNode').node().setPlayRate(1.)
            self.mirilla.find('**/+SequenceNode').node().play(4, 8)

        def anim3():
            self.mirilla.find('**/+SequenceNode').node().setPlayRate(-1.)
            self.mirilla.find('**/+SequenceNode').node().play(0, 3)

        def anim4():
            self.mirilla.find('**/+SequenceNode').node().setPlayRate(-1.)
            self.mirilla.find('**/+SequenceNode').node().play(3, 8)

        #events
        self.accept(self.QUIT_KEY, sysExit, [0])
        self.accept(self.ACCELERATE_KEY, taskMgr.add, [
            propulsaAvio, "propulsaAvio1", None, [self.ACCELERACIO], None,
            None, True
        ])
        self.accept(self.ACCELERATE_KEY + "-up", taskMgr.remove,
                    ["propulsaAvio1"])

        self.accept(self.DECELERATE_KEY, taskMgr.add, [
            propulsaAvio, "propulsaAvio2", None, [-self.ACCELERACIO], None,
            None, True
        ])
        self.accept(self.DECELERATE_KEY + "-up", taskMgr.remove,
                    ["propulsaAvio2"])

        for key in self.SHOOT_KEYS:
            self.accept(key, setKey, ["shoot", 1])
            self.accept(key + "-up", setKey, ["shoot", 0])

        self.accept(self.RIGHT_KEY, setKey, ["turn", -1])
        self.accept(self.LEFT_KEY, setKey, ["turn", 1])
        self.accept(self.RIGHT_KEY + "-up", setKey, ["turn", 0])
        self.accept(self.LEFT_KEY + "-up", setKey, ["turn", 0])

        self.accept(self.CENTRA_RATA_KEY, centraRatoli)

        self.accept("n", anim1)
        self.accept("m", anim2)
        self.accept("v", anim3)
        self.accept("b", anim4)

        taskMgr.add(giraAvio, "GiraAvio")
        taskMgr.add(mouAvio, "MouAvio")
        taskMgr.add(avioRecte, "avioRecte")
        taskMgr.add(tombaAvio, "tombaAvio")