Beispiel #1
0
def init():
	global cont, own, obj_list, options_items, mouse_move, mouse_over, mouse_click, enter_key, up_key, down_key, all_keys, back_key, right_click
	cont = logic.getCurrentController()
	own = cont.owner

	obj_list = logic.getCurrentScene().objects
	film_option = logic.getCurrentScene().objects['film_option']
	
	options_items = []

	for ob in obj_list:
		if 'ID' in ob:
			options_items.append(ob)
			#print (options_items)
	
	include_film = xml_parse.readXML('menu.xml', ['include_film'], False)
	if include_film == 'False':
		film_option['selectable'] = False
		for i in film_option.children:
			i.visible = 0
		options_items.pop()
	else:
		pass
	
	mouse_move = own.sensors['mouse_move']
	mouse_over = own.sensors['mouse_over']
	mouse_click = own.sensors['mouse_click']
	right_click = own.sensors['right_click']
	enter_key = own.sensors['enter_key']
	back_key = own.sensors['back_key']
	up_key = own.sensors['up_key']
	down_key = own.sensors['down_key']
Beispiel #2
0
	def draw_map(self):
		for y in range(self.height):
			for x in range(self.width):
				self.sys.own.worldPosition = [x*S,y*S,0]
				if self.map[x][y].block:
					index = self.map[x][y].block_index
					try:
						mesh = self.map[x][y].block+str(index)
						tile = logic.getCurrentScene().addObject(mesh,self.sys.own)
						self.map[x][y].block = tile
					except ValueError:
						raise Exception("**********\nStairs at {} {} are reested! \nCorrect block for index {} not found!\n**********".format(x,y,index))
						logic.endGame()
		
				#draw props
				if self.map[x][y].prop:
					p = self.map[x][y].prop
					self.sys.own.worldPosition = [(x*S)+rand(-1,1),(y*S)+rand(-1,1), 2]
					if p == 'LifePotion':
						self.sys.own.worldPosition.z = 0
					prop = logic.getCurrentScene().addObject(p, self.sys.own)
					ori = prop.worldOrientation.to_euler()
					ori.z = rand(0,628)*0.01
					prop.worldOrientation = ori
					if p == 'Zombie':
						self.monsters.append(prop)
					elif p == 'LifePotion':
						self.items.append(prop)
    def __init__(self, sock, sock_size, dbg = False):
        """
        Ray manager constructor.

        :param sock: socket with which the ray manager communicates with the EVERTims client.
        :param sock_size: size of packet read every pass (sock.recv(sock_size))
        :param dbg: enable debug (print log in console)
        :type sock: Socket
        :type sock_size: Integer
        :type dbg: Boolean
        """
        self.sock = sock
        self.sock_size = sock_size
        self.dbg = dbg
        self.rayDict = {}
        self.missedRayCounter = 0

        # define bpy handle
        self._draw_handler_handle = None

        # add local pre_draw method to to scene callback
        if BLENDER_MODE == 'BGE':
            gl.getCurrentScene().pre_draw.append(self._pre_draw_bge)
        elif BLENDER_MODE == 'BPY':
            self._draw_handler_handle = bpy.types.SpaceView3D.draw_handler_add(self._draw_handler, (None,None), 'WINDOW', 'PRE_VIEW')
            if self.dbg: print('added evertims module raytracing callback to draw_handler')
Beispiel #4
0
def Level3():
	cont = logic.getCurrentController()
	obj = cont.owner
	scene = logic.getCurrentScene()
	dict = logic.globalDict
	level = dict['level']
	scene = logic.getCurrentScene()
	enemyID = str(obj)[len(str(obj))-4:len(str(obj))]
		
	if 'level' in dict:
		enemy = EnemyTemp(10, 120, 'regular')
		if 'enemy' in obj:
			if not 'init' in obj:
				obj['init'] = 1
				scene.objects['CamMain']['enemies'] += 1.0
			if not 'Tank' in scene.objects:
				pass
			else:
				enemy.Pathing()
			enemy.Health()	
		elif 'gun' in obj:
			enemy.Gun()
			if not 'Tank' in scene.objects:
				pass
			else:
				enemy.Aim()
		else:
			enemy.RocketInit()
Beispiel #5
0
def save():
	#Start by saving the current level name
	try:
		LEVEL_MAIN = logic.getCurrentScene().objects['LEVEL_MAIN']
		logic.globalDict['level_name'] = LEVEL_MAIN['level_name']
		logic.globalDict['Load_Next'] = LEVEL_MAIN['level_name']
		#save all of the level's properties
		for prop in LEVEL_MAIN.getPropertyNames():
			logic.globalDict['LEVEL_MAIN',prop] = LEVEL_MAIN[prop]
			print (logic.globalDict['LEVEL_MAIN',prop])
	except:
		print ('LEVEL_MAIN not found. Current level will not be saved.')
		logic.globalDict['level_name'] = 'default'
	
	
	#Now for player information
	player = logic.getCurrentScene().objects['sintel_col']
	player_stats = logic.getCurrentScene().objects['player_stats']
	
	#position
	logic.globalDict['player_pos'] = list(player.worldPosition)
	logic.globalDict['player_ori'] = list(player.worldOrientation[0]),list(player.worldOrientation[1]),list(player.worldOrientation[2])

	#stats
	#logic.globalDict['player_lvl'] = player_stats['lvl']
	#logic.globalDict['player_max_hp'] = player_stats['mhp']
	#logic.globalDict['player_current_hp'] = player_stats['chp']
	logic.globalDict['player_hp'] = player_stats['hp']

	#Save
	logic.saveGlobalDict()
	#print('Saved Game')
	logic.globalDict['game_notifications'].append('Saved Game')
Beispiel #6
0
 def endCondition(self) :            
     if self.timer < 0 :
         #close socket
         SocketUDPClose.main()
         
         #replace scene
         gl.getCurrentScene().replace('GameOverScene')
Beispiel #7
0
def Level7():
	cont = logic.getCurrentController()
	obj = cont.owner
	scene = logic.getCurrentScene()
	dict = logic.globalDict
	level = dict['level']
	scene = logic.getCurrentScene()
	enemyID = str(obj)[len(str(obj))-4:len(str(obj))]
	
	if 'level' in dict:
		regular = EnemyTemp(10, 120, 'regular')
		kamikaze = EnemyTemp(10, 520, 'kamikaze')
		artillery = EnemyTemp(10,120, 'artillery')
		if obj['type'] == 'regular':
			if 'enemy' in obj:
				if not 'init' in obj:
					obj['init'] = 1
					scene.objects['CamMain']['enemies'] += 1.0
				if not 'Tank' in scene.objects:
					pass
				else:
					regular.Pathing()
				regular.Health()	
			elif 'gun' in obj:
				regular.Gun()
				if not 'Tank' in scene.objects:
					pass
				else:
					regular.Aim()
			else:
				regular.RocketInit()
		elif obj['type'] == 'kamikaze':
			if 'enemy' in obj:
				if not 'init' in obj:
					obj['init'] = 1
					scene.objects['CamMain']['enemies'] += 1.0
				if 'Tank' in scene.objects:
					kamikaze.Pathing()
				kamikaze.Health()	
			elif 'gun' in obj:
				kamikaze.Gun()	
		elif obj['type'] == 'artillery':
			if 'enemy' in obj:
				if not 'init' in obj:
					obj['init'] = 1
					scene.objects['CamMain']['enemies'] += 1.0
				if not 'Tank' in scene.objects:
					pass
				else:
					artillery.Pathing()
				artillery.Health()	
			elif 'gun' in obj:
				artillery.Gun()
				if not 'Tank' in scene.objects:
					pass
				else:
					artillery.Aim()
			else:
				artillery.RocketInit()
Beispiel #8
0
	def shoot(self):
		
		joy_vect = self.joystick.values(4, 3)
		
		if joy_vect.magnitude and self.tick():
			logic.getCurrentScene().addObject(self.bullet_obj, self.empty, 50)
			handle = self.device.play(self.factory)
			handle.volume = 0.3
Beispiel #9
0
 def _render(self):
     try:
         super().render()
     except:
         # If there was a problem with rendering, stop so we don't spam the console
         import traceback
         traceback.print_exc()
         logic.getCurrentScene().post_draw.remove(self._render)
Beispiel #10
0
	def reflect(self):
		if self.collision.positive:

			hit_list =  [b for b in self.collision.hitObjectList if "bullet" in b and\
						not b["bullet"]]
			if len(hit_list):
				logic.getCurrentScene().addObject("r_bullet", self.gobj.empty, 50)
				handle = self.device.play(self.factory)
				handle.volume = 0.3
Beispiel #11
0
def set_body_position(co):
    """
    During grabbing the head moves. The 'Head_Empty' needs to follow.
    """
    ow = co.owner

    head = logic.getCurrentScene().objects['Head']
    human = logic.getCurrentScene().objects['Human']


    if human['Manipulate']:
        ow.worldPosition = head.worldPosition
Beispiel #12
0
def collision():
    """
    Detect camera collision and place the camera accordingly
    """
    co =  logic.getCurrentController()
    ow = co.owner
    ray = co.sensors['collision']
    right = co.sensors['RIGHT']
    left = co.sensors['LEFT']
    human =   logic.getCurrentScene().objects['POS_EMPTY']
    Orig_Pos = logic.getCurrentScene().objects['POS_3P_Camera_Orig']
    distance = 0.05     # the distance the camera keeps to Objects

    # if near an object, place the camera slightly in front of it
    if ray.positive and not human['Manipulate'] and not (right.positive or
                                                         left.positive):
        hitPos = ray.hitPosition
        ow.worldPosition = (Vector(hitPos) -
                            Vector(ray.rayDirection).normalized()*distance)
        ow['prop_collision'] = True
        
    elif ray.positive and not human['Manipulate'] and right.positive:
        hitPos = (Vector(ray.hitPosition) + Vector(right.hitPosition))/2
        ow.worldPosition = (hitPos -
                            (Vector(ray.rayDirection) +
                             Vector(right.rayDirection)).normalized()*distance)
        ow['prop_collision'] = True
        
    elif ray.positive and not human['Manipulate'] and left.positive:
        hitPos = (Vector(ray.hitPosition) + Vector(left.hitPosition))/2
        ow.worldPosition = (hitPos -
                            (Vector(ray.rayDirection) +
                             Vector(left.rayDirection)).normalized()*distance)
        ow['prop_collision'] = True
        
    elif left.positive and not human['Manipulate'] and not (right.positive or
                                                            ray.positive):
        hitPos = left.hitPosition
        ow.worldPosition = (Vector(hitPos) -
                            Vector(left.rayDirection).normalized()*distance)
        ow['prop_collision'] = True
        
    elif right.positive and not human['Manipulate'] and not (left.positive or
                                                             ray.positive):
        hitPos = right.hitPosition
        ow.worldPosition = (Vector(hitPos) -
                            Vector(right.rayDirection).normalized()*distance)
        ow['prop_collision'] = True

    else:
        ow['prop_collision'] = False
        ow.worldPosition = Orig_Pos.worldPosition
Beispiel #13
0
def sensor(a):
    hole   = (logic.getCurrentScene()).objects["hl{}_sensor".format(a)]
    object = (logic.getCurrentScene()).objects["l{}".format(a)]
    h_pos  = hole.worldPosition
    o_pos  = object.worldPosition
    dist = sqrt((h_pos[0] - o_pos[0])**2 + (h_pos[1] - o_pos[1])**2)
    object['dist'] = dist
    if dist < 0.2:
        object['solved'] = 1
        object.worldPosition = h_pos
        r = (logic.getCurrentScene()).objects["Robot"]
        r['Grab'] = False
        r['Target'] = ''
        object.suspendDynamics()
Beispiel #14
0
def set_body_position(co):
    """
    During grabbing the head moves. The 'Head_Empty' needs to follow.
    """
    ow = co.owner

    # get the suffix of the human to reference the right objects
    suffix = ow.name[-4:] if ow.name[-4] == "." else ""

    head = logic.getCurrentScene().objects['Head' + suffix]
    human = logic.getCurrentScene().objects['Human' + suffix]


    if human['Manipulate']:
        ow.worldPosition = head.worldPosition
Beispiel #15
0
def initApp():
	'''Called at start of app'''

	scene = logic.getCurrentScene()
	scene.post_draw = [postDraw]
	scene.pre_draw = [preDraw]

	# make GEKit library as a discoverable path
	base = logic.expandPath('//')
	sys.path.append(os.path.join(base, 'library'))
	os.chdir(base)
	
	# global alias
	logic.scene = logic.getCurrentScene()
	initSession()
Beispiel #16
0
    def __init__(self, obname, imgname):
        if obname is None or imgname is None:
            raise ValueError('no object name or image name given')
        if not obname in logic.getCurrentScene().objects:
            raise IndexError('requested object not found')

        self.__state = 'STOP'
        gameobject = logic.getCurrentScene().objects[obname]

        # -- Get the material that is using our texture
        img = "IM{0}".format(imgname)
        matID = texture.materialID(gameobject, img)

        # -- Create the video texture
        self._texture = texture.Texture(gameobject, matID)
 def startClientSimulation(self):
     """
     Start EVERTims simulation: sent '/facefinished' message to EVERTims client
     to start acoustic calculation, add local pre_draw method to BGE scene stack.
     """
     # send room, listener, source info to EVERTims client
     self.updateClient()
     # send '/facefinished' to EVERTims client (start calculations)
     self._sendOscMsg(self.connect['ip_raytracing'],self.connect['port_w_raytracing'],'/facefinished')
     # add local pre_draw method to to scene callback
     if BLENDER_MODE == 'BGE':
         gl.getCurrentScene().pre_draw.append(self._pre_draw_bge)
     elif BLENDER_MODE == 'BPY':
         self.bpy_handle_callback = bpy.types.SpaceView3D.draw_handler_add(self._pre_draw_bpy, (None,None), 'WINDOW', 'PRE_VIEW')
         if self.dbg: print('added evertims module callback to draw_handler')
def calculateGrids():

    # recalculate grid after movement
    global firstparent
    global firstShard
    global ground
    global children

    print("In Calculate Grids")

    for o in scene.objects:
        if isGroundConnectivity(o):  # or (isGround(o) and not isDestructor(o)):
            print("ISGROUNDCONN")

            #  bbox = getFloats(o["gridbbox"])
            #    dim = getInts(o["griddim"])
            gridbbox = bpy.context.scene.objects[o.name].destruction.gridBBox
            griddim = bpy.context.scene.objects[o.name].destruction.gridDim

            bbox = (gridbbox[0], gridbbox[1], gridbbox[2])
            dim = (griddim[0], griddim[1], griddim[2])

            grounds = getGrounds(o)
            groundObjs = [logic.getCurrentScene().objects[g.name] for g in grounds]

            for fp in firstparent:
                # fp = scene.objects[f]
                if o.name in fp.name:
                    [g.setParent(fp, False, False) for g in groundObjs]

                    oldRot = Matrix(fp.worldOrientation)
                    fp.worldOrientation = Vector((0, 0, 0))
                    for g in grounds:
                        g.pos = Vector(logic.getCurrentScene().objects[g.name].worldPosition)
                        print(g.pos)

                    childs = [scene.objects[c] for c in children[o.name]]
                    grid = dd.Grid(dim, o.worldPosition, bbox, childs, grounds)
                    grid.buildNeighborhood()
                    grid.findGroundCells()
                    dd.DataStore.grids[o.name] = grid

                    fp.worldOrientation = oldRot
                    [g.removeParent() for g in groundObjs]

        # ground = groundObjs[0]

    print("Grids: ", dd.DataStore.grids)
Beispiel #19
0
def init():
    """
    Sets the camera on load
    """
    co =  logic.getCurrentController()
    ow = co.owner
    camAct = co.actuators['Set_Camera']
    sobList =  logic.getCurrentScene().objects
    humCam = sobList['Human_Camera']
    
    try:
        worldCam = sobList['CameraFP']
        #check if there is a Camera displaying the world in the scene
    except KeyError:
        worldCam = None

    if ow['WorldCamera'] and worldCam:
        camAct.camera = worldCam
    else:
        camAct.camera = humCam
        logic.mouse.visible = False
    # set Camera following the human or displaying the world
    
    
    co.activate(camAct)
Beispiel #20
0
def Timer(): #Instantiates the timer in the corner of the screen.
	
	cont = logic.getCurrentController()
	obj = cont.owner
	scene = logic.getCurrentScene()
	dict = logic.globalDict
	
	def Init():
		if not 'init' in obj:
			obj['init'] = 1
			dict['levelClock'] = 0
			dict['score'] = 0
			obj['digit']= 0.0
			
	
	def Update():
		if dict['paused'] == True:
			scene.suspend()
		
		#The timer doesn't use the built in text system. Instead I modelled my own pixelated font and use this for loop
		#to determine which model to pull in for each digit.
		for i in range(1,4): 
			if 'Digit%s' % i in obj and dict['levelClock'] >= 10**(3-i):
				scene.addObject('Num_%s' % (str(int(dict['levelClock']))[len(str(int(dict['levelClock'])))-(4-i)]),obj,1)
			if int(dict['levelClock']) == 0:
				if 'Digit3' in obj:
					scene.addObject('Num_0', obj,1)
		dict['levelClock'] += 1.0/(10*logic.getLogicTicRate())
	Init()
	Update()
Beispiel #21
0
def Level0(): 
#These level functions are mainly for debugging purposes, giving default values to to score and stuff so the game doesn't throw up errors if I start the game at level 3 instead of at the start.
#They also keep track of the  current level for the rest of the code. These are run by the ground objects of each level.
	
	cont = logic.getCurrentController()
	obj = cont.owner
	scene = logic.getCurrentScene()
	dict = logic.globalDict
	scenes = logic.getSceneList()
	
	def Init():
		if not 'init' in obj:
			obj['init'] = 1
			dict['level'] = 0
			if not 'Score' in scenes:
				logic.addScene('Score')
			logic.addScene('Controls')
			if not 'score' in dict:
				dict['score'] = 0
			if not 'levelscore' in dict:
				dict['levelScore'] = 0
			if not 'levelClock' in dict:
				dict['levelClock']= 0
			if not 'tank_kills' in dict:
				dict['tank_kills'] = 0
			if not 'rocket_kills' in dict:
				dict['rocket_kills'] = 0
			dict['breakable'] = False
	
	def Update():
		pass
	
	Init()
	Update()	
Beispiel #22
0
def Level7():
	
	cont = logic.getCurrentController()
	obj = cont.owner
	scene = logic.getCurrentScene()
	dict = logic.globalDict
	scenes = logic.getSceneList()
	
	def Init():
		if not 'init' in obj:
			obj['init'] = 1
			dict['level'] = 7
			if not 'Score' in scenes:
				logic.addScene('Score')
			if not 'score' in dict:
				dict['score'] = 0
			dict['levelScore'] = 0
			dict['levelClock']= 0
			dict['tank_kills'] = 0
			dict['rocket_kills'] = 0
			scene.objects['CamMain']['enemies'] = 1
			dict['breakable'] = False
	
	def Update():
		pass
	
	Init()
	Update()		
Beispiel #23
0
def Level1():
	
	cont = logic.getCurrentController()
	obj = cont.owner
	scene = logic.getCurrentScene()
	dict = logic.globalDict
	scenes = logic.getSceneList()
	
	def Init():
		if not 'init' in obj:
			obj['init'] = 1
			dict['level'] = 1
			dict['score'] = 0
			for i in scenes:
				if 'Controls' in i.name:
					i.end()
			if not 'Score' in scenes:
				logic.addScene('Score')
			dict['levelScore'] = 0
			dict['levelClock']= 0
			dict['tank_kills'] = 0
			dict['rocket_kills'] = 0
			dict['breakable'] = False
	
	def Update():
		pass
	
	Init()
	Update()
Beispiel #24
0
def Explosion(): #This function controls the explosion animation and makes sure it's destroyed when the animation is over.
	
	cont = logic.getCurrentController()
	obj = cont.owner
	scene = logic.getCurrentScene()
	tank_explosion = cont.sensors['Message1'] #Receives messages from rockets and tanks when they are destroyed.
	rocket_explosion = cont.sensors['Message2']
	
	def Init():
		if not 'init' in obj:
			obj['init'] = 1
			obj['time'] = 0.0
	
	def Update():
		if obj['time'] > 37.0: #Length of the explosion animation
			obj.endObject()
		obj['time'] += 1.0
		if tank_explosion.positive:
			cont.activate(cont.actuators['Tank'])
		if rocket_explosion.positive:
			cont.activate(cont.actuators['Rocket'])
		
	
	Init()
	Update()
Beispiel #25
0
def CountdownAction(): #Pauses the game when countdown is happening and resumes when it should be over.
	
	cont = logic.getCurrentController()
	obj = cont.owner
	scene = logic.getCurrentScene()
	action = cont.actuators['Action']
	scenes = logic.getSceneList()
	dict = logic.globalDict
	level = dict['level']
	
	def Init():
		if not 'init' in obj:
			obj['init'] = 1
			obj['time'] = 0.0
	
	def Update():
		cont.activate(action)
		for i in scenes:
			if 'Score' in i.name:
				i.suspend()
		if obj['time'] > 130.0: #Time it takes for the countdown animation to complete.
			for i in scenes:
				if 'Level%s' % level in i.name: #finds current level scene an resumes it
					i.resume()
			for i in scenes:
				if 'Score' in i.name:
					i.resume()
			for i in scenes:
				if 'Menu' in i.name: #This makes sure the main menu scene was removed and isn't hiding behind everything else.
					i.end()
			scene.end()
		obj['time'] += 1.0
			
	Init()
	Update()
Beispiel #26
0
def write():
    """write on screen"""
    # retrieve timer
    global game_timer
    scene = logic.getCurrentScene()
    game_timer = int(active_camera["Timer"])
    catched = bamboo_counter["catched"]
    total = bamboo_counter["total"]
    vortex = panda.power
    width = render.getWindowWidth()
    height = render.getWindowHeight()

    # OpenGL setup
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, width, 0, height)
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glLoadIdentity()
    
    bgl.glColor4f(1, 1, 1, 1)
    
    # BLF drawing routine
    font_id = logic.font_id
    blf.size(font_id, int(18 * (width/dpi) * 0.06), dpi)
    blf.position(font_id, width*0.02, height*0.95, 0)
    if game_timer < 60:
        blf.draw(font_id, "{0} : {1:02d}".format(l_timer,game_timer))
    else:
        blf.draw(font_id, "{0} : {1}:{2:02d}".format(l_timer,game_timer//60,game_timer%60))
    blf.position(font_id, width*0.02, height*0.90, 0)
    blf.draw(font_id, "{0} : {1}".format(l_level, level))
    blf.position(font_id, width*0.02, height*0.85, 0)
    blf.draw(font_id, "{0} : {1} / {2}".format(l_score, catched, total))
    blf.position(font_id, width*0.02, height*0.80, 0)
    blf.draw(font_id, "{0} : {1}".format(l_vortex, vortex))
Beispiel #27
0
def hide(contr):
    """
    Delete all descriptions (Property '_tooltip')
    """
    for obj in logic.getCurrentScene().objects:
        if "_tooltip" in obj:
            obj.endObject()
Beispiel #28
0
def Paused(): #Simple Pause function
	
	cont = logic.getCurrentController()
	obj = cont.owner
	scene = logic.getCurrentScene()
	pause = cont.sensors['Keyboard']
	dict = logic.globalDict
	level = dict['level']
	scenes = logic.getSceneList()
	
	def Init():
		if not 'init' in obj:
			obj['init'] = 1
	
	def Update():
		for i in scenes:
			if 'Score' in i.name:
				i.suspend()
		if pause.positive:
			dict['paused'] = False
			for i in scenes:
					if 'Score' in i.name:
						i.resume()
					if 'Level%s' % level in i.name:
						i.resume()
			scene.end()
	
	Init()
	Update()	
def  select_inside(a, b):
    cont = logic.getCurrentController()
    shift = cont.sensors["Keyboard"]
    
    p1 = Vector((a.x, a.y))
    p2 = Vector((b.x, a.y))
    p3 = Vector((b.x, b.y))
    p4 = Vector((a.x, b.y))

    scene = logic.getCurrentScene()
    cam = scene.active_camera

    for obj in scene.objects:
        if "ant" in obj:
            
            # if both points are in the same place, deselect everything
            if a == b:
                obj["selected"] = False
            else:
                # remove existing selection unless shift is held
                if not shift.positive:
                    if obj.get("selected", False):
                        obj["selected"] = False
                
                if geometry.intersect_point_quad_2d(obj.worldPosition.xy, p1, p2, p3, p4):
                    print("selected", obj)
                    obj["selected"] = True
Beispiel #30
0
def init():
	#Get Scenes
	sc1 = G.getSceneList()[1]
	sc2 = G.getCurrentScene()

	#Get ObjectScenes
	scn1 = sc1.objects
	scn2 = sc2.objects

	#Get Cameras
	cam1 = sc1.active_camera
	cam2 = scn2['SkyCam']
	
	#Get Objects
	sempty = scn2['SunEmpty']
	lempty = scn1['LightsEmpty']
	shadlamp = scn1['Shadow_lamp']
	sun = scn1['Sun_lamp']
	hemi1 = scn1['Hemi1']
	hemi2 = scn1['Hemi2']
	sky = scn2['Sky']
	clouds = scn2['clouds']
	sun_ob = scn2['Sonne']
	moon = scn2['Moon']
	slamp = scn2['SkyShade']
	
	#Get Class
	global class_sky
	class_sky = class_sky(cam1, cam2, lempty, sempty, shadlamp, sun, hemi1, hemi2, sky, clouds, sun_ob, moon, slamp, sc1, sc2)
def isInScene(obj_name):
    for objs in logic.getCurrentScene():
        if objs.name == obj.name:
            return True
    return False
Beispiel #32
0
def Level4():
	cont = logic.getCurrentController()
	obj = cont.owner
	scene = logic.getCurrentScene()
	dict = logic.globalDict
	level = dict['level']
	scene = logic.getCurrentScene()
	enemyID = str(obj)[len(str(obj))-4:len(str(obj))]
	'''	dict['Navmesh'] = 
	
	if 'Navmesh%s.000' % level in scene.objects and dict['breakable'] == False:
			steering.navmesh = scene.objects['Navmesh%s.000' % level]
	elif 'Navmesh%s.001' % level in scene.objects and dict['breakable'] == True:
			steering.navmesh = scene.objects['Navmesh%s.001' % level]'''
	
	if 'level' in dict:
		regular = EnemyTemp(10, 120, 'regular')
		miner = EnemyTemp(10, 120, 'miner')
		artillery = EnemyTemp(10,120, 'artillery')
		if obj['type'] == 'regular':
			if 'enemy' in obj:
				if not 'init' in obj:
					obj['init'] = 1
					scene.objects['CamMain']['enemies'] += 1.0
				if 'Tank' in scene.objects:
					regular.Pathing()
				regular.Health()	
			elif 'gun' in obj:
				regular.Gun()
				if not 'Tank' in scene.objects:
					pass
				else:
					regular.Aim()
			else:
				regular.RocketInit()
		elif obj['type'] == 'miner':
			if 'enemy' in obj:
				if not 'init' in obj:
					obj['init'] = 1
					scene.objects['CamMain']['enemies'] += 1.0
				if not 'Tank' in scene.objects:
					pass
				else:
					miner.Pathing()
				miner.Health()	
			elif 'gun' in obj:
				miner.Gun()
				if not 'Tank' in scene.objects:
					pass
				else:
					miner.Aim()
			else:
				miner.RocketInit()
		elif obj['type'] == 'artillery':
			if 'enemy' in obj:
				if not 'init' in obj:
					obj['init'] = 1
					scene.objects['CamMain']['enemies'] += 1.0
				if 'Tank' in scene.objects:
					artillery.Pathing()
				artillery.Health()	
			elif 'gun' in obj:
				artillery.Gun()
				if not 'Tank' in scene.objects:
					pass
				else:
					artillery.Aim()
			else:
				artillery.RocketInit()
Beispiel #33
0
def ArtilleryRocket():
	
	cont = logic.getCurrentController()
	obj = cont.owner
	scene = logic.getCurrentScene()
	dict = logic.globalDict
	level= dict['level']
	if 'Enemy%s%s' % (level,obj['id']) in scene.objects:
		enemy = scene.objects['EnemyRocketInit%s%s' % (level,obj['id'])]
	if 'Tank' in scene.objects:
		tarLoc = copy.copy(scene.objects['Tank'].worldPosition)
	motion = cont.actuators['Motion']
	collision = cont.sensors['Collision']
	
	def Init():
		if not 'init' in obj:
			obj['init'] = 1
			obj['shadowInit'] = False
			if not 'speed' in obj:
				obj['speed'] = 0.0
			if not 'dir' in obj:
				obj['dir'] = 0.0
			obj['time'] = 0.0
			obj['vectTime'] = 11
			obj['rocket'] = True
			obj['hp'] = 1
			obj['vect'] = 0
			obj['vectNum'] = 10
			obj['rocketInitLoc'] = copy.copy(scene.objects['EnemyRocketInit%s%s' % (level,obj['id'])].worldPosition)
			vertList = []
			for i in range(0,obj['vectNum'] + 1):
				endVert = (tarLoc[0] - enemy.worldPosition[0], tarLoc[1] - enemy.worldPosition[1], tarLoc[2] - enemy.worldPosition[2])
				vertX = Scalar(endVert, mathutils.Vector((i/obj['vectNum'],i/obj['vectNum'],i/obj['vectNum'])))
				vertZ = -1*(i**2) + i*obj['vectNum']
				vertX[2] = vertZ
				vert = (enemy.worldPosition[0] + vertX[0], enemy.worldPosition[1] + vertX[1],enemy.worldPosition[2] +vertZ)
				vertList.append(vert)
			obj['vertList'] = copy.copy(vertList)
			obj['shadow'] = scene.addObject('Shadow', scene.objects['Tank'])
			obj['shadow'].setVisible(False)
	def Update():
		
		rocketDist = .05 + Dist((obj.worldPosition[0], obj.worldPosition[1], 0.0), (obj['rocketInitLoc'][0], obj['rocketInitLoc'][1], 0.0))
		enemyDist = Dist((obj['rocketInitLoc'][0], obj['rocketInitLoc'][1], 0.0), (obj['vertList'][obj['vect']][0], obj['vertList'][obj['vect']][1], 0.0))
		if obj['vect'] <= (obj['vectNum'] - 1) and rocketDist >= enemyDist:
			obj.alignAxisToVect(mathutils.Vector((obj['vertList'][obj['vect'] + 1][0] - obj['vertList'][obj['vect']][0], obj['vertList'][obj['vect'] + 1][1] - obj['vertList'][obj['vect']][1], obj['vertList'][obj['vect'] + 1][2] - obj['vertList'][obj['vect']][2])), 1, 1.0)
			verticalDist = (Dist((0.0, 0.0, obj['vertList'][obj['vect']][2]), (0.0, 0.0, obj['vertList'][obj['vect']+1][2])))
			obj['speed'] = (obj['vertList'][int(obj['vectNum']/2)][2] - obj.worldPosition[2])/25 + verticalDist/20 + .1
			obj['vect'] += 1
		if rocketDist > 0.7*(Dist(obj['rocketInitLoc'], obj['vertList'][len(obj['vertList'])-1])) and obj['shadowInit'] == False:
			obj['shadow'].setVisible(True)
			obj['shadow'].worldScale = [(1-(obj.worldPosition[2]/27.5)), (1-(obj.worldPosition[2]/27.5)), 1]
		#for i in range(0,obj['vectNum']):
		#	render.drawLine(obj['vertList'][i],obj['vertList'][i+1],[0.0,0.0,0.0])
		
		scene.addObject('EffectRocket1',obj)
		scene.addObject('EffectRocket2',obj)
		
		motion.useLocalDLoc = True
		motion.useLocalDRot = True
		motion.dLoc = [0.0, obj['speed'] ,0.0]
		obj.applyForce([0.0, 0.0, 9.82], 0)
		cont.activate(motion)
		
		#render.drawLine(obj.worldPosition, obj.worldPosition + obj.orientation[0]*2, [0.0,0.0,0.0])
		obj['time'] += 1
		if obj['time'] > 2:
			if obj.worldPosition[2] < 1:
				obj['hp'] -= 10
			if collision.positive:
				enemy = collision.hitObject
				if 'enemy' in enemy:
					logic.sendMessage('hit', 'None', str(enemy))
				if 'hp' in enemy:
					enemy['hp'] -= 10
				obj.endObject()
				scene.objects['Shadow'].endObject()
				explosion = scene.addObject('Explosion',obj)
				logic.sendMessage('rocket_explosion', 'None')
		
		if obj['hp'] < 1:
			obj.endObject()
			scene.objects['Shadow'].endObject()
			explosion = scene.addObject('Explosion',obj)
			logic.sendMessage('rocket_explosion', 'None')
		
	Init()
	Update()
Beispiel #34
0
def Generic(particlelist):
    """
	Author: SolarLune (Josiah Lane)
	Date Updated: 4/26/11
	License: Custom - users of this script can use this script for any purpose, commercial or otherwise, with attribution.
	
	A generic particle handling script. Works for most kinds of particle effects.	
	"""

    sce = logic.getCurrentScene()
    cont = logic.getCurrentController()

    always = cont.sensors[0]
    freq = always.frequency + 1
    f = freq

    cam = sce.active_camera

    particles = particlelist[:]  # Make a copy of the array

    def Init(obj, override=0):

        if not 'init' in obj or override == 1:

            obj['init'] = 1
            obj['sf'] = 0.0

            if obj.parent == None:
                obj['scale'] = obj.scaling.copy()
            else:
                obj['scale'] = obj.localScale.copy(
                )  # Original scale of the particle

            if not 'emitter' in obj:  # Owner emitter object
                obj['emitter'] = None

            obj['time'] = 0.0  # Time before death

            obj['alpha'] = 0.0

            if not 'speed' in obj:
                obj['speed'] = [0.0, 0.0, 0.0]
            if not 'forcespd' in obj:  # Force speed
                obj['forcespeed'] = [0.0, 0.0, 0.0]

            if not 'friction' in obj:  # Default friction for the particle; if 1, then the smoke won't slow down
                obj['friction'] = [0.0, 0.0, 0.0]
            if not 'growrate' in obj:
                obj['growrate'] = 0.02  # Default growth rate
            if not 'force' in obj:
                obj['force'] = [
                    0.0, 0.0, 0.0
                ]  # Force on a given axis (constant or stacking)
            if not 'forcecompound' in obj:  # Whether the force grows over time (i.e. with z-axis grav. = 0.1, first frame = 0.1, second 0.2, third 0.3, etc.)
                obj['forcecompound'] = 0
            if not 'forcelocal' in obj:
                obj['forcelocal'] = 0

            if not 'cache' in obj:
                obj['cache'] = 0

            if not 'lod' in obj:
                obj['lod'] = 1
            if not 'loddist' in obj:
                obj['loddist'] = 20

            if not 'collide' in obj:
                obj['collide'] = 0
            if not 'collidevar' in obj:
                obj['collidevar'] = None

            if not 'startalpha' in obj:
                obj['startalpha'] = obj.color[
                    3]  # Original (starting) alpha (alpha to get up to when fading in)

            if not 'fadeout' in obj:
                obj['fadeout'] = 40.0

            if not 'fadein' in obj:
                obj['fadein'] = 0.0

            obj['fadingin'] = 0

            if obj['fadein'] > 0.0:
                obj.color = [obj.color[0], obj.color[1], obj.color[2],
                             0.0]  # Set the alpha to 0 to fade in from
                obj['fadingin'] = 1

            if not 'movelocal' in obj:
                obj['movelocal'] = 0

            if not 'prototype' in obj:
                obj['prototype'] = 0

            obj['protoindex'] = 0

            obj['skip'] = 0  # Particle calculation LOD based on life

            if not 'life' in obj:
                obj['life'] = 40  # Default number of frames that the particle lives

            obj['frictionon'] = 0  # A simple check I do to make sure that friction is on; this reduces logic load on the CPU
            obj['forceon'] = 0  # Another simple check to make sure that force is on, reducing logic load
            obj['speedon'] = 0  # Another check for speed

            if obj['friction'][0] != 0 or obj['friction'][1] != 0 or obj[
                    'friction'][
                        2] != 0:  # Don't compute all this stuff if friction isn't on
                obj['frictionon'] = 1

            if obj['force'][0] != 0 or obj['force'][1] != 0 or obj['force'][
                    2] != 0:  # Don't compute all this stuff if force isn't on
                obj['forceon'] = 1

            if obj['speed'][0] != 0 or obj['speed'][1] != 0 or obj['speed'][
                    2] != 0:
                obj['speedon'] = 1

            obj['origscale'] = obj['scale'].copy()
            obj['origspd'] = obj['speed'][:]
            obj['origpos'] = obj.worldPosition.copy()

            if obj['emitter'] != None and not obj['emitter'].invalid:
                obj['origoff'] = obj['emitter'].worldPosition.copy(
                ) - obj.worldPosition.copy()
            else:
                obj['origoff'] = obj.worldPosition.copy()

            obj['origcolor'] = obj.color[:]

    for x in range(len(particles)):

        obj = particles[x]

        Init(obj)

        #emitter = obj['emitter']

        die = 0  # By default, the particle doesn't die, but later on, in the right circumstances, this variable will show that it should end

        ##### PARTICLE UPDATE #####

        amproto = 0
        if obj['emitter'].invalid or obj['emitter'] == None:
            obj['prototype'] = 0
        else:
            amproto = obj == obj['emitter']['firstparticle']

        if obj['prototype'] == 1 and not amproto and not obj['emitter'][
                'protodone'] == None:

            proto = obj['emitter']['emitterproto'][obj['protoindex']]

            #print (proto)

            color = proto[0]
            scaling = proto[1]
            spd = proto[2]
            frc = proto[3]

            #print (spd, frc)

            if spd != None:
                obj.applyMovement([spd[0], spd[1], spd[2]], obj['movelocal'])
            if frc != None:
                obj.applyMovement([frc[0], frc[1], frc[2]], obj['forcelocal'])

            obj.color = color
            obj.scaling = scaling

            obj['protoindex'] += 1

            if obj['protoindex'] >= len(obj['emitter']['emitterproto']):
                die = 1

        else:

            obj['time'] += 1.0 * f

            if obj['frictionon']:

                obj['speed'][0] -= obj['speed'][0] * (obj['friction'][0] * f)
                obj['speed'][1] -= obj['speed'][1] * (obj['friction'][1] * f)
                obj['speed'][2] -= obj['speed'][2] * (obj['friction'][2] * f)

            spd = obj['speed']

            if obj['speedon']:  # Handle collisions

                if obj['collide'] != 0:

                    pos = obj.worldPosition.copy()
                    topos = pos.copy()

                    topos.x += spd[0] * 2.0 * f
                    topos.y += spd[1] * 2.0 * f
                    topos.z += spd[2] * 2.0 * f

                    col = obj.rayCast(topos, pos, 0, obj['collidevar'])

                    if col[0] != None:
                        if obj['collide'] == 1:  # Stop
                            obj['speed'] = [0, 0, 0]
                        elif obj['collide'] == 2:  # Die
                            die = 1
                        elif obj['collide'] == 3:  # Full reflection
                            movement = Vector(obj['speed'])
                            refl = movement.reflect(col[2])
                            obj['speed'] = [refl.x, refl.y, refl.z]
                        elif obj['collide'] == 4:  # Angled reflection
                            movement = Vector(obj['speed'])
                            refl = movement.reflect(col[2])
                            spd = [refl.x, refl.y, refl.z]

                obj.applyMovement([spd[0] * f, spd[1] * f, spd[2] * f],
                                  obj['movelocal'])

            if (obj.getDistanceTo(cam) <= obj['loddist']
                    and obj['lod'] == 1) or obj['lod'] == 0:

                if obj['forceon']:

                    frcspd = obj['forcespeed']

                    if obj['forcecompound']:

                        obj['forcespeed'] = [
                            obj['forcespeed'][0] + (obj['force'][0] * f),
                            obj['forcespeed'][1] + (obj['force'][1] * f),
                            obj['forcespeed'][2] + (obj['force'][2] * f)
                        ]
                        frcspd = obj['forcespeed']

                    else:
                        frcspd = [
                            obj['forcespeed'][0] + (obj['force'][0] * f),
                            obj['forcespeed'][1] + (obj['force'][1] * f),
                            obj['forcespeed'][2] + (obj['force'][2] * f)
                        ]

                    #frcspd = [frcspd[0] * f, frcspd[1] * f, frcspd[2] * f]

                    #if obj['collide'] != 0:		# Handle collisions for force; disabled due to irregular movement

                    #	pos = obj.worldPosition.copy()
                    #	topos = pos.copy()

                    #	topos.x += frcspd[0]
                    #	topos.y += frcspd[1]
                    #	topos.z += frcspd[2]

                    #	col = obj.rayCast(topos, pos, 0, obj['collidevar'])

                    #	if col[0] != None:
                    #		if obj['collide'] == 1:		# Stop
                    #			frcspd = [0, 0, 0]
                    #		elif obj['collide'] == 2:	# Die
                    #			die = 1
                    #		elif obj['collide'] == 3:	# Full reflection
                    #			movement = mathutils.Vector(frcspd)
                    #			refl = movement.reflect(col[2])
                    #			obj['forcespeed'] = [refl.x, refl.y, refl.z]
                    #		elif obj['collide'] == 4:	# Angled reflection
                    #			movement = mathutils.Vector(frcspd)
                    #			refl = movement.reflect(col[2])
                    #			frcspd = [refl.x, refl.y, refl.z]

                    #frcspd = obj['forcespeed']

                    obj.applyMovement(frcspd, obj['forcelocal'])

                if obj['growrate'] != 0:
                    obj['sf'] += obj[
                        'growrate'] * f  # Scale the smoke by the particle's growth rate
                    obj.scaling = [
                        obj['scale'].x + obj['sf'], obj['scale'].y + obj['sf'],
                        obj['scale'].z + obj['sf']
                    ]

                alpha = obj['startalpha']

                if obj['fadingin']:

                    if obj['fadein'] > 0.0 and obj['startalpha'] > 0.0:

                        if obj.color[3] >= obj['startalpha']:
                            obj['fadingin'] = 0
                            obj.color = [
                                obj.color[0], obj.color[1], obj.color[2],
                                obj['startalpha']
                            ]
                        else:
                            rate = (float(obj['startalpha']) /
                                    float(obj['fadein'])) * f
                            alpha = obj.color[3] + rate

                if obj['time'] >= obj['life'] - obj['fadeout']:

                    if obj['fadeout'] > 0.0 and obj['startalpha'] > 0.0:

                        rate = (-float(obj['startalpha']) /
                                float(obj['fadeout'])) * f
                        alpha = obj.color[3] + rate

                obj.color = [obj.color[0], obj.color[1], obj.color[2], alpha]

            if amproto and obj['prototype']:  # Prototype

                proto = obj['emitter']['emitterproto']

                if obj['forceon']:
                    protofrc = frcspd
                else:
                    protofrc = None

                if obj['speedon']:
                    protospd = spd
                else:
                    protospd = None

                stats = [
                    obj.color.copy(),
                    obj.scaling.copy(), protospd, protofrc
                ]

                proto.append(stats)

        ##### PARTICLE DEATH #####

        if (amproto and obj['prototype']) or not obj['prototype']:

            if obj['fadeout'] == 1 and obj.color[3] <= 0.0:
                die = 1

            elif obj['time'] >= obj[
                    'life']:  # If the particle is invisible or it has been alive for longer than it's life variable,
                die = 1

            elif not cam.pointInsideFrustum(obj.position) and obj['partcull']:
                die = 1

        if die:

            if amproto:

                obj['emitter'][
                    'protodone'] = 1  #obj['emitter']['emitterproto']
                #obj['emitterproto'] = []
                #obj['emitter']['firstparticle'] = None

                #print ("I was the prototype")

            if obj['cache'] and not obj[
                    'emitter'].invalid:  # If the emitter still exists and caching is on

                del obj['init']  # Reinitialize the object
                obj['speed'] = obj[
                    'origspd'][:]  # And reset it, because the BGE will use the same particle again

                obj.worldPosition = obj['emitter'].worldPosition.copy() + obj[
                    'origoff']  # Offset the object

                obj.scaling = obj['origscale'].copy()
                obj.color = obj['origcolor'][:]
                Init(obj)

                if obj['emitter']['partcache']:
                    obj['emitter']['cachedone'] = 1

            else:
                particlelist.remove(obj)
                obj.endObject()  # End the object

                if obj['emitter'] != None and not obj[
                        'emitter'].invalid:  # Tell the emitter that spawned you that you're gone
                    obj['emitter']['emitterpartamt'] -= 1
                    obj['emitter']['particles'].remove(obj)
Beispiel #35
0
def zeroPos():
    # controller = GameLogic.getCurrentController()
    # own = controller.owner
    scene = GameLogic.getCurrentScene()

    # Romain
    # avoid multiple resettings
    # this is important here because the gratings are changed
    # when calling zeroPos and we don't want to have two events
    # associated with one resetting

    # finally I generalize it to all cases
    try:  # if initialisation, "last_zero" still doesn't exist
        GameLogic.Object["last_zero"]
        init = 0
    except:
        init = 1
    if not init and (settings.gratings or settings.cues):
        if GameLogic.Object["last_zero"] <= 3:
            return

    if init and settings.gratings:
        # Romain
        # make some objects disappear
        objectsToRemove = [
        ]  # put the object name into quotes exple : ["name1","name2"]
        for i in objectsToRemove:
            scene.objects[i].visible = False
        # set normal walls to invisible
        for i in scene.objects:
            if i.name[:8] == "LeftWall" or i.name[:9] == "RightWall":
                i.visible = False
    if init and not settings.gratings:
        try:
            for i in ["LW1", "RW1", "CeilingGrating"]:
                scene.objects[i].visible = False
        except KeyError:
            sys.stderr.write("BLENDER: Warning: Grating walls are missing")
    if init and not settings.cues:
        try:
            for i in settings.objects_cues:
                scene.objects[i].visible = False
        except AttributeError:
            sys.stderr.write("BLENDER: Warning: Cues are missing")
    GameLogic.Object["last_zero"] = 0

    if scene.name == "Scene":
        playerName = 'MovingCube'
        rew1Name = 'Cylinder.001'
        rew2Name = 'Cylinder.002'
        rew3Name = 'Cylinder.003'
    elif scene.name == "Looming":
        playerName = 'MovingCube.002'
    else:
        playerName = 'MovingCube.001'
        rew1Name = 'Cone.001'
        rew2Name = 'Cone.002'
        rew3Name = 'Cylinder.000'
    own = scene.objects[playerName]
    if sys.version_info >= (3, ):
        euler = mu.Euler((0, 0, 0))
        euler = euler.to_matrix()
    else:
        euler = mu.Euler(0, 0, 0)
    own.localOrientation = euler  # [[0,0,0],[0,0,0],[0,0,0]]
    if settings.linear and not settings.looming:
        startOdorCounter()
        own.localPosition = [0, settings.startPos, 1.5]  # y was +80
        if settings.reward_double:

            # Randomly select one of the 2 rewards:
            GameLogic.Object['select_rew'] = "%s" % (np.random.randint(2) + 1)

            # Distribute rewards with at least 20 units distance between the 2:
            rew1 = scene.objects[rew1Name]
            rew2 = scene.objects[rew2Name]
            new_rew_y = np.random.uniform(20.0, 120.0, 2)
            while np.diff(new_rew_y)[0] < 20.0:
                new_rew_y = np.random.uniform(20.0, 120.0, 2)
            rew1.localPosition = [0, new_rew_y[0], rew1.position[2]]
            rew2.localPosition = [0, new_rew_y[1], rew2.position[2]]

        elif settings.reward_cpp:
            rew1 = scene.objects[rew1Name]
            rew2 = scene.objects[rew2Name]

            rew1.localPosition = [0, 60, rew1.position[2]]
            rew2.localPosition = [200, 0, rew2.position[2]]
        else:
            rew2 = scene.objects[rew2Name]
            rew3 = scene.objects[rew3Name]

            rew2.localPosition = [0, 1000, rew2.position[2]]
            rew3.localPosition = [0, 1000, rew3.position[2]]

    elif not settings.looming:
        own.localPosition = [0, -150, 1.5]
    else:
        own.localPosition = [0, 0, 0]

    # Romain : randomly change wall gratings
    if settings.gratings:
        chooseWalls.randomWalls(settings.proba_env1)

    # Romain : select the pair of cues either 'randomly without replacement' settings.groups_trials = True
    # or completely randomly if settings.groups_trials = False
    if settings.cues:
        if settings.groups_trials:
            if GameLogic.Object['run_number'] in [None, settings.n_runs - 1]:
                if GameLogic.Object['run_number'] == settings.n_runs - 1:
                    GameLogic.Object["stopped_counter_sessions"] = 0
                GameLogic.Object['run_number'] = 0
                GameLogic.Object['current_order'] = chooseCues.generate_order(
                    settings.content_trials)
                cues.write_new_session()
                print(GameLogic.Object['current_order'])
            else:
                GameLogic.Object['run_number'] += 1
                GameLogic.Object["stopped_counter_trials"] = 0
            chooseCues.chooseCues(GameLogic.Object['current_order'][
                GameLogic.Object['run_number']])
        else:
            chooseCues.randomCues(settings.proba_mismatch)

    if settings.cues or settings.gratings:
        gc.zeroPump()
        GameLogic.Object['WallTouchTicksCounter'] = None
        GameLogic.Object['RewardTicksCounter'] = None
Beispiel #36
0
# File tested with Blender 2.66
#
# Copyright - February 2013
# This work is licensed under the Creative Commons
# Attribution-Share Alike 3.0 Unported License
# #############################

import bge
from bge import logic as G
from bge import render as R

# showing the mouse cursor
R.showMouse(True)

# storing the current scene in a variable
scene = G.getCurrentScene()


# define a class to store all group elements and the click object
class Group():
    def __init__(self, name):
        self.name = name
        self.click = None
        self.objects = []


# create new element groups
cube_group = Group("cubes")
sphere_group = Group("sphere")

# add all objects with an "ui" property to the created element
Beispiel #37
0
    def recieve(self):
        """"
        Recieve all the packets from the server.
        Check what kind of packet it is: movement? new connection?
        and handle the packet
        """
        try:
            # Listen for incoming packets
            data = self.server.recv(10024)
            try:
                # Sometimes the packets come in so fast that it is "merged together" (First json, second json)
                # We then have to recognize this so we can decode every json and place it in a queue
                state = re.split('(\{.*?\})(?= *\{)', data.decode())
                accumulator = ''
                res = []
                for subs in state:
                    accumulator += subs
                    try:
                        res.append(json.loads(accumulator))
                        accumulator = ''
                    except:
                        pass
            except:
                pass
                print("Something went wrong while decoding the json")
            else:
                # For every json check what kind of dict it is
                # If it found the type handle the packet
                for packet in res:
                    if 'new-connection' in packet.keys():
                        """"
                        A new client has connected to the server
                        We spawn it on the client's game so he can see it too
                        We the player under the IP of the new client so we can apply movement on it later
                        """

                        # Ip of the new client
                        ip = packet['new-connection']['ip']

                        # What is the name of the object the client has?
                        # Might be usefull for upgrades ect..
                        object = packet['new-connection']['object']

                        # Get the current scene and spawn the client in the spawner
                        scene = logic.getCurrentScene()
                        spawner = scene.objects["Spawner"]
                        player = scene.addObject(object, spawner)

                        # Add the ip to the player object
                        player["ip"] = ip
                        self.players[ip] = player

                        # If it is the first time a user is "intitialized" then we know that this is
                        # the user that belongs to this client. So we store the object
                        if self.user_initialized == False:
                            self.local_user = player
                            self.user_initialized = True


                    if 'init_connection' in packet:
                        """" 
                        if a user connects to the server and there are allready other players inside the game
                        then we need to get the information about the other objects so we can spawn them in ect..
                        """
                        for event in packet['init_connection']['objects']:
                            scene = logic.getCurrentScene()
                            spawner = scene.objects["Spawner"]
                            player = scene.addObject('Tank', spawner)
                            player['ip'] = event
                            self.players[event] = player

                            # Handle the rotation
                            # We use Eueler for this (the last number handles the Z rotation)
                            player.localOrientation = [0, 0, packet['init_connection']['objects'][event][1]]

                            # Change the players position to the given position
                            # We us a vecor for this
                            player.worldPosition = Vector(packet['init_connection']['objects'][event][0])

                    if 'position' in packet.keys():
                        """" 
                        These packets contain the position (worldlocation & rotation) of a specific player
                        if the ip in the packet is not equal to the clients IP then apply the movement
                        (otherwise this will override the movement and the player would be stuck on one position)
                        """
                        if self.user_initialized and packet['position']['ip'] \
                                != "{}:{}".format(self.ip, self.port):
                            try:
                                # Get the object that belongs to that ip
                                instance = self.players[packet['position']['ip']]

                                # Handle the rotation
                                instance.localOrientation = [0, 0, packet['position']['coordinates'][1]]

                                # Handle the movement
                                instance.worldPosition = Vector(packet['position']['coordinates'][0])
                            except:
                                # NOTE: it's possible that this packet came in before we initialized the objects
                                # so it can probably not find the right object. So no worries about this error
                                print("Something went wrong handling the position. Line: 150")

                    if 'send all positions' in packet.keys():
                        """" 
                        If the server gets a new connection and there are allready players in game
                        then it will request the info about the other objects.
                        so when the client gets this packet it sends all the clients back
                        """
                        scene = logic.getCurrentScene()
                        players = {
                            gobj["ip"]: [list(gobj.worldPosition), gobj.localOrientation.to_euler()[2]] \
                            for gobj in scene.objects \
                            if gobj.name == "Tank"
                        }

                        position = {
                            'init_connection': {
                                'objects': players
                            }
                        }
                        self.server.sendall(json.dumps(position).encode())
        except socket.error:
            pass
Beispiel #38
0
def _powertrain(controller, car):

    #declare variables
    gas = None
    #moje
    gearUp = None
    gearDown = None
    scene = logic.getCurrentScene()
    StreetLamp = scene.objects["StreetLamp"]
    SpeedMeter = scene.objects["SpeedMeter"]
    #/moje
    reverse = None
    brake = None
    ebrake = None

    #get the vehicl id
    vehicleID = _constraintID(car)

    #engine power
    power = 0

    #engine
    engine = False

    #check for engine override
    if "Engine" in car:
        engine = car["Engine"]

    #set default values
    forwardSpeed = 100
    #moje
    currentGear = 0
    #/moje
    reverseSpeed = 300
    brakeAmount = 65
    eBrakeAmount = 100
    backdrive = False
    frontdrive = True

    #check for forward speed override
    if "ForwardSpeed" in car:

        #set forward speed
        forwardSpeed = car["ForwardSpeed"]

    #moje
    if "CurrentGear" in car:
        currentGear = car["CurrentGear"]
    #/moje

    #check for reverse speed override
    if "ReverseSpeed" in car:

        #set reverse speed
        reverseSpeed = car["ReverseSpeed"]

    #check for brake amount override
    if "BrakeAmount" in car:

        #set brake amount
        brakeAmount = car["BrakeAmount"]

    #check for E-brake amount override
    if "EBrakeAmount" in car:

        #set brake amount
        eBrakeAmount = car["EBrakeAmount"]

    #check for BackWheelDrive override
    if "BackWheelDrive" in car:

        #set back wheel drive
        backdrive = car["BackWheelDrive"]

    #check for FrontWheelDrive override
    if "FrontWheelDrive" in car:

        #set front wheel drive
        frontdrive = car["FrontWheelDrive"]

    #check for gas sensor
    if "Gas" in controller.sensors:
        gas = controller.sensors["Gas"]

    #check for reverse sensor
    if "Reverse" in controller.sensors:
        reverse = controller.sensors["Reverse"]

    #check for brake sensor
    if "Brake" in controller.sensors:
        brake = controller.sensors["Brake"]

    #check for E-brake sensor
    if "EBrake" in controller.sensors:
        ebrake = controller.sensors["EBrake"]

    #moje
    if "GearUp" in controller.sensors:
        gearUp = controller.sensors["GearUp"]

    if "GearDown" in controller.sensors:
        gearDown = controller.sensors["GearDown"]

    if "StartStop" in controller.sensors:
        startStop = controller.sensors["StartStop"]
    #/moje

    #check if gas exists
    if gas:
        #check if engine is on
        if engine:
            #check if gas is positive
            if gas.positive:
                #print("funkcja gas")
                #set power
                if currentGear == -1:
                    forwardSpeed = -1000
                    if carsetup.RPM < carsetup.maxRPM:
                        carsetup.RPM += 0.00001 + (carsetup.RPM / 100)
                        StreetLamp.applyRotation(
                            [0, 0.00001 + (carsetup.RPM / 100), 0], 1)
                        #if carsetup.Speed <= carsetup.MaxSpeed_1G:
                        SpeedMeter.applyRotation([0, 0.005, 0], 1)
                        carsetup.Speed += 0.005
                        forwardSpeed = (carsetup.Speed * 50) * (carsetup.RPM +
                                                                50)
                        power = forwardSpeed

                elif currentGear == 0:
                    forwardSpeed = 0
                    if carsetup.RPM <= carsetup.maxRPM:
                        StreetLamp.applyRotation([0, 0.1, 0], 1)
                        carsetup.RPM += 0.1
                    if carsetup.Speed > carsetup.MinSpeed:
                        SpeedMeter.applyRotation([0, -0.005, 0], 1)
                        carsetup.Speed -= 0.005

                elif currentGear == 1:
                    if carsetup.RPM < carsetup.autoRPM:
                        carsetup.RPM += 0.00001 + (carsetup.RPM / 100)
                        StreetLamp.applyRotation(
                            [0, 0.00001 + (carsetup.RPM / 100), 0], 1)
                        SpeedMeter.applyRotation([
                            0, (carsetup.Speed + 0.1) /
                            (carsetup.maxRPM - carsetup.RPM) * 0.035, 0
                        ], 1)
                        carsetup.Speed += (carsetup.Speed + 0.1) / (
                            carsetup.maxRPM - carsetup.RPM) * 0.035
                        forwardSpeed = (carsetup.Speed * 100) * (carsetup.RPM +
                                                                 150)
                        power = -forwardSpeed
                    else:
                        car["CurrentGear"] = currentGear + 1
                        StreetLamp.applyRotation([0, -1, 0], 1)
                        carsetup.RPM -= 1

                elif currentGear == 2:
                    if carsetup.RPM < carsetup.autoRPM:
                        carsetup.RPM += 0.00001 + (carsetup.RPM / 200)
                        StreetLamp.applyRotation(
                            [0, 0.00001 + (carsetup.RPM / 200), 0], 1)
                        forwardSpeed = 200
                        power = -forwardSpeed
                        SpeedMeter.applyRotation([
                            0, (carsetup.Speed + 0.1) /
                            (carsetup.maxRPM - carsetup.RPM) * 0.01, 0
                        ], 1)
                        carsetup.Speed += (carsetup.Speed + 0.1) / (
                            carsetup.maxRPM - carsetup.RPM) * 0.01
                        forwardSpeed = (carsetup.Speed * 10) * (carsetup.RPM +
                                                                150)
                        power = -forwardSpeed
                    else:
                        car["CurrentGear"] = currentGear + 1
                        StreetLamp.applyRotation([0, -1, 0], 1)
                        carsetup.RPM -= 1

                elif currentGear == 3:
                    if carsetup.RPM < carsetup.autoRPM:
                        carsetup.RPM += 0.00001 + (carsetup.RPM / 300)
                        StreetLamp.applyRotation(
                            [0, 0.00001 + (carsetup.RPM / 300), 0], 1)
                        forwardSpeed = 200
                        power = -forwardSpeed
                        SpeedMeter.applyRotation([
                            0, (carsetup.Speed + 0.1) /
                            (carsetup.maxRPM - carsetup.RPM) * 0.005, 0
                        ], 1)
                        carsetup.Speed += (carsetup.Speed + 0.1) / (
                            carsetup.maxRPM - carsetup.RPM) * 0.005
                        forwardSpeed = (carsetup.Speed * 10) * (carsetup.RPM +
                                                                150)
                        power = -forwardSpeed
                    else:
                        car["CurrentGear"] = currentGear + 1
                        StreetLamp.applyRotation([0, -1, 0], 1)
                        carsetup.RPM -= 1

                elif currentGear == 4:
                    if carsetup.RPM < carsetup.autoRPM:
                        carsetup.RPM += 0.00001 + (carsetup.RPM / 600)
                        StreetLamp.applyRotation(
                            [0, 0.00001 + (carsetup.RPM / 600), 0], 1)
                        forwardSpeed = 200
                        power = -forwardSpeed
                        SpeedMeter.applyRotation([
                            0, (carsetup.Speed + 0.1) /
                            (carsetup.maxRPM - carsetup.RPM) * 0.002, 0
                        ], 1)
                        carsetup.Speed += (carsetup.Speed + 0.1) / (
                            carsetup.maxRPM - carsetup.RPM) * 0.002
                        forwardSpeed = (carsetup.Speed * 10) * (carsetup.RPM +
                                                                150)
                        power = -forwardSpeed
                    else:
                        car["CurrentGear"] = currentGear + 1
                        StreetLamp.applyRotation([0, -1, 0], 1)
                        carsetup.RPM -= 1

                elif currentGear == 5:
                    if carsetup.RPM <= carsetup.maxRPM:
                        carsetup.RPM += 0.00001 + (carsetup.RPM / 800)
                        StreetLamp.applyRotation(
                            [0, 0.00001 + (carsetup.RPM / 800), 0], 1)
                    if carsetup.Speed < carsetup.MaxSpeed_5G:
                        SpeedMeter.applyRotation([
                            0, (carsetup.Speed + 0.1) /
                            (carsetup.maxRPM - carsetup.RPM) * 0.001, 0
                        ], 1)
                        carsetup.Speed += (carsetup.Speed + 0.1) / (
                            carsetup.maxRPM - carsetup.RPM) * 0.001
                        forwardSpeed = (carsetup.Speed * 10) * (carsetup.RPM +
                                                                150)
                        power = -forwardSpeed

            else:
                if currentGear == -1:
                    if carsetup.Speed > carsetup.MinSpeed:
                        SpeedMeter.applyRotation(
                            [0, -0.008 * (carsetup.Speed / (carsetup.RPM)), 0],
                            1)
                        carsetup.Speed -= (0.008 * (carsetup.Speed /
                                                    (carsetup.RPM)))
                    if carsetup.RPM > carsetup.nRPM:
                        StreetLamp.applyRotation([0, -0.008, 0], 1)
                        carsetup.RPM -= 0.008
                if currentGear == 0:
                    power = 0
                    if carsetup.Speed > carsetup.MinSpeed:
                        SpeedMeter.applyRotation([0, -0.003, 0], 1)
                        carsetup.Speed -= 0.003
                    if carsetup.RPM <= carsetup.nRPM:
                        StreetLamp.applyRotation([0, 0.03, 0], 1)
                        carsetup.RPM += 0.03
                    elif carsetup.RPM > carsetup.nRPM:
                        StreetLamp.applyRotation([0, -0.02, 0], 1)
                        carsetup.RPM -= 0.02
                if currentGear == 1:
                    if carsetup.Speed > carsetup.MinSpeed:
                        SpeedMeter.applyRotation(
                            [0, -0.008 * (carsetup.Speed / (carsetup.RPM)), 0],
                            1)
                        carsetup.Speed -= (0.008 * (carsetup.Speed /
                                                    (carsetup.RPM)))
                        forwardSpeed = (carsetup.Speed * 10) * (carsetup.RPM +
                                                                50)
                        power = -forwardSpeed
                    if carsetup.RPM > carsetup.nRPM:
                        StreetLamp.applyRotation([0, -0.008, 0], 1)
                        carsetup.RPM -= 0.008
                    if carsetup.Speed >= carsetup.MinSpeed:
                        forwardSpeed = (carsetup.Speed * 10) * (carsetup.RPM +
                                                                50)
                        power = -forwardSpeed
                if currentGear == 2:
                    if carsetup.Speed > carsetup.MinSpeed:
                        SpeedMeter.applyRotation(
                            [0, -0.001 * (carsetup.Speed / (carsetup.RPM)), 0],
                            1)
                        carsetup.Speed -= (0.001 * (carsetup.Speed /
                                                    (carsetup.RPM)))
                    if carsetup.RPM > carsetup.nRPM:
                        StreetLamp.applyRotation([0, -0.003, 0], 1)
                        carsetup.RPM -= 0.003
                    else:
                        car["CurrentGear"] = currentGear - 1
                        StreetLamp.applyRotation([0, 1, 0], 1)
                        carsetup.RPM += 1
                if currentGear == 3:
                    if carsetup.Speed > carsetup.MinSpeed_3G:
                        SpeedMeter.applyRotation(
                            [0, -0.001 * (carsetup.Speed / (carsetup.RPM)), 0],
                            1)
                        carsetup.Speed -= (0.001 * (carsetup.Speed /
                                                    (carsetup.RPM)))
                    if carsetup.RPM > carsetup.nRPM:
                        StreetLamp.applyRotation([0, -0.003, 0], 1)
                        carsetup.RPM -= 0.003
                    else:
                        car["CurrentGear"] = currentGear - 1
                        StreetLamp.applyRotation([0, 1, 0], 1)
                        carsetup.RPM += 1
                if currentGear == 4:
                    if carsetup.Speed > carsetup.MinSpeed_4G:
                        SpeedMeter.applyRotation(
                            [0, -0.001 * (carsetup.Speed / (carsetup.RPM)), 0],
                            1)
                        carsetup.Speed -= (0.001 * (carsetup.Speed /
                                                    (carsetup.RPM)))
                    if carsetup.RPM > carsetup.nRPM:
                        StreetLamp.applyRotation([0, -0.003, 0], 1)
                        carsetup.RPM -= 0.003
                    else:
                        car["CurrentGear"] = currentGear - 1
                        StreetLamp.applyRotation([0, 1, 0], 1)
                        carsetup.RPM += 1
                if currentGear == 5:
                    if carsetup.Speed > carsetup.MinSpeed_5G:
                        SpeedMeter.applyRotation(
                            [0, -0.001 * (carsetup.Speed / (carsetup.RPM)), 0],
                            1)
                        carsetup.Speed -= (0.001 * (carsetup.Speed /
                                                    (carsetup.RPM)))
                    if carsetup.RPM > carsetup.nRPM:
                        StreetLamp.applyRotation([0, -0.003, 0], 1)
                        carsetup.RPM -= 0.003
                    else:
                        car["CurrentGear"] = currentGear - 1
                        StreetLamp.applyRotation([0, 1, 0], 1)
                        carsetup.RPM += 1
        elif not engine:
            if carsetup.RPM > carsetup.minRPM:
                StreetLamp.applyRotation([0, -0.05, 0], 1)
                carsetup.RPM -= 0.05
            if carsetup.Speed > carsetup.MinSpeed:
                SpeedMeter.applyRotation([0, -0.005, 0], 1)
                carsetup.Speed -= 0.005

    #moje
    if gearUp:
        if gearUp.positive:
            if currentGear == 0:
                if carsetup.RPM < 0.5 and carsetup.Speed < 0.1:
                    power = 0
                    car["CurrentGear"] = currentGear + 1
                else:
                    print("Autmonatyczna skrzynia biegów zniszczona")
            if currentGear == -1:
                power = 0
                car["CurrentGear"] = currentGear + 1
    if gearDown:
        if gearDown.positive:
            if engine:
                if currentGear == 0:
                    if carsetup.RPM < 0.5 and carsetup.Speed < 0.1:
                        power = 0
                        car["CurrentGear"] = currentGear - 1
                    else:
                        print("Autmonatyczna skrzynia biegów zniszczona")
                if currentGear == 1:
                    power = 0
                    car["CurrentGear"] = currentGear - 1
            else:
                if currentGear == 5:
                    car["CurrentGear"] = currentGear - 1
                elif currentGear == 4:
                    car["CurrentGear"] = currentGear - 1
                elif currentGear == 3:
                    car["CurrentGear"] = currentGear - 1
                elif currentGear == 2:
                    car["CurrentGear"] = currentGear - 1
                elif currentGear == 1:
                    car["CurrentGear"] = currentGear - 1
                elif currentGear == 0:
                    car["CurrentGear"] = currentGear - 1
    if startStop:
        if startStop.positive:
            if not engine and currentGear == 0:
                car["Engine"] = True
            elif engine and carsetup.RPM < 0.5:
                car["Engine"] = False
    #/moje

    #check if reverse exists
    if reverse:

        #check if reverse is positive
        if reverse.positive:

            #check if engine is on
            if engine:

                #set power
                power = reverseSpeed

                #check if gas exists
                if gas:

                    #check if gas is positive
                    if gas.positive:

                        #set power
                        power = 0

    #check if brake exists
    if brake:

        #check if brake is positive
        if brake.positive:
            #moje
            #gas.negative
            #/moje
            #apply braking

            #moje
            if carsetup.Speed > carsetup.MinSpeed:
                SpeedMeter.applyRotation(
                    [0, -0.01 * (carsetup.Speed / (carsetup.RPM)), 0], 1)
                carsetup.Speed -= (0.01 * (carsetup.Speed / (carsetup.RPM)))
                vehicleID.applyBraking(
                    carsetup.MaxSpeed_5G / (carsetup.Speed + 0.00001), 2)
                vehicleID.applyBraking(
                    carsetup.MaxSpeed_5G / (carsetup.Speed + 0.00001), 3)
                power = 0
            if carsetup.RPM > carsetup.nRPM:
                StreetLamp.applyRotation([0, -0.012, 0], 1)
                carsetup.RPM -= 0.012

            #elif carsetup.RPM = carsetup.nRPM:
            #car["Engine"] = False
            #/moje

            #vehicleID.applyBraking(brakeAmount, 0)
            #vehicleID.applyBraking(brakeAmount, 1)
            #vehicleID.applyBraking(brakeAmount, 2)
            #vehicleID.applyBraking(brakeAmount, 3)

            #set power
            #power = 0

            #moje
            '''if carsetup.RPM > carsetup.minRPM and currentGear != 0:
				StreetLamp.applyRotation([0, -0.065, 0], 1)
				carsetup.RPM -= 0.065'''
            #elif carsetup.RPM = carsetup.nRPM:
            #car["Engine"] = False
            #/moje

        else:
            #remove braking
            vehicleID.applyBraking(0, 2)
            vehicleID.applyBraking(0, 3)

    #check if e brake exists
    if ebrake:

        #check if e brake is positive
        if ebrake.positive:

            #apply braking
            vehicleID.applyBraking(eBrakeAmount, 2)
            vehicleID.applyBraking(eBrakeAmount, 3)

            #set power
            power = 0

    #check if back wheel drive
    if backdrive:

        #apply power
        vehicleID.applyEngineForce(power, 2)
        vehicleID.applyEngineForce(power, 3)

    #check if front wheel drive
    if frontdrive:

        #apply power
        vehicleID.applyEngineForce(power, 0)
        vehicleID.applyEngineForce(power, 1)
Beispiel #39
0
def raycast_line(anglevect,
                 anglewidth,
                 topos,
                 frompos=None,
                 raynum=3,
                 center=1,
                 from_scalar=1.0,
                 to_scalar=1.0,
                 dist=0,
                 prop='',
                 face=1,
                 xray=1,
                 poly=0,
                 obj=None,
                 debug=False,
                 objdebug=None):
    """
    Casts several rays in a line, starting from frompos and going to topos, and then iterating along the line indicated by anglevect.

    The function returns a dictionary, consisting of four items:

    'rays': The return of the raycasts (either a hit, or an empty list, depending on what the rays hit; the output from a raycast() function, basically)
    'ray_end': The ending position of the last successful raycast, or None if there wasn't a successful raycast
    'ray_start' The starting position of the last successful raycast, or None if there wasn't a successful raycast
    'offset' The offset between the starting point of the successful ray cast and the provided starting ray cast position. Useful in case
    you want to reorient the position of an object from the ray cast (i.e. move to contact point), but still want to use the object's
    center position (don't move to where the ray hit, but move to where it hit relative to the object's center position).

    anglevect = The angle that the rays should be cast on.

    anglewidth = How wide the rays should be cast in Blender Units (i.e. a value of 1 means that from the left-most ray to the right-most ray is 1 BU).

    raynum = number of rays to cast

    center = if the rays should be centered on the anglevect Vector or not
    (i.e. treat frompos and topos as the center ray, or as the ray starting from anglevect)

    from / to_scalar = A percentage of the width to stretch (i.e. to have a wider end "edge" than starting "edge")

    dist = distance of each raycast; defaults to 0, which equals the distance between the from position and end position of the vectors

    prop = property to check for with each raycast; defaults = '', which detects any object

    face = whether to return a face if the ray hits something

    xray = whether to go through objects that don't match the property criteria (objects that don't have the property
    named by 'prop')

    poly = whether to return the polygon / UV hit; check the api documentation for more information

    obj = object to use for the ray casts; if left set to default (None), then it will use whatever object is calling
    the function.

    objdebug = default None; an object to use for debugging

    -----

    Okay, so now what is this actually used for? Mainly, to do kind of a 'ray cast wall'. An example would be if you
    want to cast multiple rays for a character in a platforming game. You would do this instead of using the built-in Bullet
    physics engine to handle gravity and collisions so that you could have partially impassable objects, for example.

    An example of using this function would look something like this:

    width = 0.6

    frompos = obj.worldPosition.copy()
    topos = frompos.copy()
    topos.z -= 1

    dist = 0.5 + abs(obj.worldLinearVelocity.z)

    ground = bghelper.RaycastLine(obj.worldOrientation.col[0], width, topos, frompos, 3, 1, dist, 'ground', debug = 1)[0]

    This will cast three rays in a straight line, with the center one being below the object's world position. Debug is on,
    so it will draw the lines visibly onscreen (barring a bug with the render engine about drawing lines with overlay or
    underlay scenes activated). It will return an object with the 'ground' property, if it finds one. If so, then it will
    return a list consisting of the successful raycast and its starting and ending position (i.e. [ray, topos, frompos]).
    Otherwise, it will return a list consisting of a list with a None in it, and two other Nones (i.e. [[None], None, None]).
    This way you can check: if bghelper.LineRayCast()[0] == None to see if the ray was successful (or any other index of the
    returned list).

    """

    anglevect = anglevect.copy()
    anglevect.magnitude = anglewidth

    if obj is None:
        obj = logic.getCurrentController().owner
    if frompos is None:
        frompos = obj.worldPosition.copy()

    if not isinstance(topos, mathutils.Vector):
        topos = mathutils.Vector(topos)
    if not isinstance(frompos, mathutils.Vector):
        frompos = mathutils.Vector(frompos)

    rtp = topos.copy()
    rfp = frompos.copy()

    rn = raynum - 1

    if rn <= 0:
        rn = 1

    ray = [None]

    if center:
        rtp -= (anglevect / 2) * to_scalar
        rfp -= (anglevect / 2) * from_scalar

    output = {}

    for x in range(raynum):

        ray = obj.rayCast(rtp, rfp, dist, prop, face, xray, poly)

        if debug:

            to = rtp - rfp
            to.magnitude = dist

            if ray[0]:
                render.drawLine(rfp, rfp + to, [0, 1, 0])
            else:
                render.drawLine(rfp, rfp + to, [1, 0, 0])

        if objdebug:

            to = rtp - rfp

            sce = logic.getCurrentScene()

            db = sce.addObject(objdebug, obj, 1)
            db.worldPosition = rfp
            db.alignAxisToVect(to, 0)
            db.worldScale = [to.magnitude, 1, 1]

            if ray[0]:
                db.color = [0, 1, 0, 1]
            else:
                db.color = [1, 0, 0, 1]

        if ray[0] is not None:

            if output == {}:
                output["rays"] = ray
                output["ray_start"] = rfp
                output["ray_end"] = rtp
                output["offset"] = rfp - frompos
            else:

                if (rfp - ray[1]).magnitude < (output['ray_end'] -
                                               output['rays'][1]).magnitude:
                    # Only overwrite previous raycast results if this one is closer
                    output["rays"] = ray
                    output["ray_start"] = rfp
                    output["ray_end"] = rtp
                    output["offset"] = rfp - frompos

        av = anglevect / rn

        rtp += av * to_scalar
        rfp += av * from_scalar

        # if not converge:
        #	rfp += av

    if output:
        return output

    return {'rays': ray, 'ray_start': None, 'ray_end': None, 'offset': None}
Beispiel #40
0
def _steer(controller, car):

    #moje
    scene = logic.getCurrentScene()
    StrWheel = scene.objects["SteeringWheel"]
    #av = kiera.axisValues
    #print("kiera")
    #print(kiera)
    #/moje

    #declare variables
    left = None
    right = None
    #turn amount
    #turnAmount = math.radians(car["TurnAmount"])

    #get turn speed
    turnSpeed = car["TurnSpeed"] * 0.005

    #get vehicle id
    vehicleID = _constraintID(car)

    #check for left sensor
    if "Left" in controller.sensors:
        left = controller.sensors["Left"]

    #check for right sensor
    if "Right" in controller.sensors:
        right = controller.sensors["Right"]
    #turnAmount = math.radians(right.axisValues[0])/800
    turnAmount = ((abs(right.axisValues[0])) / 50000)
    #print(turnAmount)
    print(carsetup.turnAmount[car])

    #check if the sensors exist
    if left and right:

        #check if both are positive
        if left.positive and right.positive:
            pass

        #check if left is positive
        elif left.positive and not right.positive:
            #check turn amount
            if carsetup.turnAmount[car] < turnAmount:

                #add to turn value
                carsetup.turnAmount[car] += turnSpeed

                #apply steering
                vehicleID.setSteeringValue(carsetup.turnAmount[car], 0)
                vehicleID.setSteeringValue(carsetup.turnAmount[car], 1)

                #moje
                StrWheel.applyRotation([0, -0.1, 0], 1)
                #/moje
            #print("left")

        #check if right is positive
        elif not left.positive and right.positive:
            #check turn amount
            if carsetup.turnAmount[car] > -turnAmount:

                #subtract from turn value
                carsetup.turnAmount[car] -= turnSpeed

                #apply steering
                vehicleID.setSteeringValue(carsetup.turnAmount[car], 0)
                vehicleID.setSteeringValue(carsetup.turnAmount[car], 1)

                #moje
                StrWheel.applyRotation([0, 0.1, 0], 1)
                #/moje
            #print("right")

        #check if none are positive
        elif not left.positive and not right.positive:

            #check if steering right
            if carsetup.turnAmount[car] <= -turnSpeed:

                #add to turn value
                carsetup.turnAmount[car] += turnSpeed
                #moje
                StrWheel.applyRotation([0, -0.1, 0], 1)
                #/moje

            #check if steering left
            elif carsetup.turnAmount[car] > turnSpeed:

                #subtract from turn value
                carsetup.turnAmount[car] -= turnSpeed
                #moje
                StrWheel.applyRotation([0, 0.1, 0], 1)
                #/moje
            #print("not left not right")

            #apply steering
            vehicleID.setSteeringValue(carsetup.turnAmount[car], 0)
            vehicleID.setSteeringValue(carsetup.turnAmount[car], 1)
Beispiel #41
0
import bge.render as Rasterizer
import mathutils
from bge import logic as gl

# get game window height and width
height = Rasterizer.getWindowHeight()
width = Rasterizer.getWindowWidth()

# get the controller
controller = gl.getCurrentController()

# Get the owner
owner = controller.owner

# get current scene
scene = gl.getCurrentScene()

# get a list of the objects in the current scene
objList = scene.objects

# Get object Cursor (warning: cursor is sqlite in gl !)
cursorCube = objList["Cursor"]
gamemotor = objList["Game_Motor"]

dec_x = gl.dec_x
dec_y = gl.dec_y

mouse = controller.sensors['Mouse']

# set only one time with prop showMouse in owner
if not owner['showMouse']:
Beispiel #42
0
def init():
    if settings.looming:
        scene = GameLogic.getCurrentScene()
        scene.replace("Looming")

    GameLogic.Object = {}
    print("BLENDER: GameLogic object created")
    GameLogic.Object['closed'] = False
    GameLogic.setLogicTicRate(100)

    sys.stdout.write(
        "BLENDER: Maximum number of logic frames per render frame: %d\n" %
        GameLogic.getMaxLogicFrame())
    sys.stdout.write(
        "BLENDER: Maximum number of physics frames per render frame: %d\n" %
        GameLogic.getMaxPhysicsFrame())
    sys.stdout.write("BLENDER: Physics update frequency: %d Hz\n" %
                     GameLogic.getPhysicsTicRate())

    # open arduino and pump

    try:
        arduino = arduino_serial.SerialPort(settings.arduino_port, 19200)
        sys.stdout.write("BLENDER: Successfully opened arduino\n")
    except OSError:
        sys.stdout.write("BLENDER: Failed to open arduino\n")
        arduino = None
    GameLogic.Object['arduino'] = arduino
    if arduino is not None:
        arduino.write(b'd')
        # Set all valves to low
        arduino.write(b'6')
        arduino.write(b'8')
        arduino.write(b'0')
        arduino.write(b'f')

    try:
        pumppy = serial.Serial(settings.pump_port, 19200, timeout=1)
        sys.stdout.write("BLENDER: Successfully opened pump\n")
        gc.setPumpVolume(pumppy, settings.reward_volume)
    except:
        sys.stdout.write("BLENDER: Failed to open pump\n")
        pumppy = None

    if ncl.has_comedi:
        print("BLENDER: Found comedi library")
        gOuttrigsubdev = 2
        gOuttrigchan = 0
        gOutfrchan = 1
        gOutleftchan = 2
        gOutrightchan = 3
        gOutexpchan = 4

        gIntrigsubdev = 7
        gIntrigchan = 0

        gDevrange = 0

        # open ni trigger channels
        devintrigch, fdintrigch, nameintrigch = ncl.open_dev(
            "/dev/comedi0_subd2")
        devouttrigch, fdouttrigch, nameouttrigch = ncl.open_dev(
            "/dev/comedi0_subd11")

        intrigch = ncl.nichannel(devintrigch, gIntrigchan, gIntrigsubdev,
                                 fdintrigch, gDevrange)
        outtrigch = ncl.nichannel(devouttrigch, gOuttrigchan, gOuttrigsubdev,
                                  fdouttrigch, gDevrange)
        outfrch = ncl.nichannel(devouttrigch, gOutfrchan, gOuttrigsubdev,
                                fdouttrigch, gDevrange)
        outleftch = ncl.nichannel(devouttrigch, gOutleftchan, gOuttrigsubdev,
                                  fdouttrigch, gDevrange)
        outrightch = ncl.nichannel(devouttrigch, gOutrightchan, gOuttrigsubdev,
                                   fdouttrigch, gDevrange)
        outexpch = ncl.nichannel(devouttrigch, gOutexpchan, gOuttrigsubdev,
                                 fdouttrigch, gDevrange)  #MC2015

        ncl.init_comedi_dig(
            intrigch,
            outtrigch,
            outfrch,
            outleftch,
            outrightch,
            outexpch  #MC2015
        )
    else:
        intrigch = None
        outtrigch = None
        outfrch = None
        outleftch = None
        outrightch = None
        outexpch = None  #MC2015

    GameLogic.Object['intrigch'] = intrigch
    GameLogic.Object['outtrigch'] = outtrigch
    GameLogic.Object['outfrch'] = outfrch
    GameLogic.Object['outleftch'] = outleftch
    GameLogic.Object['outrightch'] = outrightch
    GameLogic.Object['outexpch'] = outexpch  #MC2015

    GameLogic.Object['pumppy'] = pumppy
    GameLogic.Object['left_on'] = False
    GameLogic.Object['right_on'] = False

    GameLogic.Object['file_open'] = False
    GameLogic.Object['train_open'] = False
    GameLogic.Object['bcstatus'] = False

    gio.create_data_dir()
    GameLogic.Object['time0'] = time.time()
    GameLogic.Object['prevtime'] = time.time()
    GameLogic.Object['nframes'] = 0

    GameLogic.Object['rewcount'] = 0
    GameLogic.Object['rewfail'] = 0
    GameLogic.Object['puffcount'] = 0
    GameLogic.Object['puffthistrial'] = 0
    GameLogic.Object['isloom'] = 0
    GameLogic.Object['loomcounter'] = 0
    GameLogic.Object['loom_first_trial'] = 0
    if settings.linear:
        GameLogic.Object['rewpos'] = [0.98]  # 1.0 # np.zeros((16))
    else:
        GameLogic.Object['rewpos'] = [
            -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1.0, 0.75, 0.5, 0.25, 0.0,
            -0.25, -0.5, -0.75, -1.0
        ]  # 1.0 # np.zeros((16))
    GameLogic.Object['boundx'] = 8.0
    GameLogic.Object['boundy'] = 158.0
    GameLogic.Object['hysteresis'] = 0.5
    GameLogic.Object['speed_tracker'] = np.zeros((100))

    blenderpath = GameLogic.expandPath('//')

    if not settings.cpp:
        s1, conn1, addr1, p1 = gc.spawn_process(
            "\0mouse0socket",
            ['python3', '%s/py/usbclient.py' % blenderpath, '0'])
        s2, conn2, addr2, p2 = gc.spawn_process(
            "\0mouse1socket",
            ['python3', '%s/py/usbclient.py' % blenderpath, '1'])
    else:
        if settings.readlib == "xinput":
            mice = xinput.find_mice(model=settings.mouse)
            for mouse in mice:
                # xinput.set_owner(mouse) # Don't need this if using correct udev rule
                xinput.switch_mode(mouse)
            if settings.usezmq:
                procname = 'readout_zmq'
            else:
                procname = 'readout'
            if len(mice) >= 1:
                s1, conn1, addr1, p1 = \
                    gc.spawn_process(
                        "\0mouse0socket",
                        [('%s/cpp/generic-ev/' % blenderpath) + procname, '%d' % mice[0].evno, '0'],
                        usezmq=settings.usezmq)
            else:
                s1, conn1, addr1, p1 = None, None, None, None
            if len(mice) >= 3:
                s2, conn2, addr2, p2 = \
                    gc.spawn_process(
                        "\0mouse1socket",
                        [('%s/cpp/generic-ev/readout' % blenderpath) + procname, '%d' % mice[2].evno, '1'],
                        usezmq=settings.usezmq)
            else:
                s2, conn2, addr2, p2 = None, None, None, None
        elif settings.readlib == "libusb":
            s1, conn1, addr1, p1 = \
                gc.spawn_process("\0mouse1socket",
                              ['%s/cpp/g500-usb/readout' % blenderpath, '1'])
            s2, conn2, addr2, p2 = \
                gc.spawn_process("\0mouse0socket",
                              ['%s/cpp/g500-usb/readout' % blenderpath, '0'])
        else:
            s1, conn1, addr1, p1, s2, conn2, add2, p2 = \
                None, None, None, None, None, None, None, None

    if settings.has_webcam:
        sys.stdout.write("BLENDER: Starting webcam... ")
        sys.stdout.flush()
        if not settings.cpp:
            svid, connvid, addrvid, pvid = gc.spawn_process("\0vidsocket", [
                'python3 %s/py/webcam.py' % blenderpath,
            ],
                                                            shell=True)
        else:
            svid, connvid, addrvid, pvid = gc.spawn_process("\0vidsocket", [
                '%s/cpp/webcam/webcam' % blenderpath,
            ],
                                                            system=False)
        print("done")
        connvid.send(GameLogic.Object['day_dir'].encode('latin-1'))
        gc.recv_ready(connvid)
        connvid.setblocking(0)
        GameLogic.Object['vidconn'] = connvid

    if settings.has_fw:
        if not settings.fw_local:
            GameLogic.Object['fwip'] = ''  #"128.40.202.203"
            sfw, connfw, addrfw = gc.spawn_process_net(
                GameLogic.Object['fwip'])
            if connfw is None:
                settings.has_fw = False
        else:
            sys.stdout.write("BLENDER: Starting fw... ")
            sys.stdout.flush()
            sfw, connfw, addrfw, pfw = \
                gc.spawn_process("\0fwsocket", ['%s/cpp/dc1394/dc1394' % blenderpath,], #MC2015
                              system=False, addenv={"SDL_VIDEO_WINDOW_POS":"\"1280,480\""})
            print("done")

        connfw.send(GameLogic.Object['fw_trunk'].encode('latin-1'))
        gc.recv_ready(connfw)
        connfw.setblocking(0)
        GameLogic.Object['fwconn'] = connfw

    GameLogic.Object['has_fw'] = settings.has_fw

    if settings.has_comedi and ncl.has_comedi:
        scomedi, conncomedi, addrcomedi, pcomedi = \
            gc.spawn_process("\0comedisocket", ['python3', '%s/py/nicomedi.py' % blenderpath,])

        conncomedi.send(blenderpath.encode('latin-1'))
        gc.recv_ready(conncomedi)
        conncomedi.setblocking(0)
        GameLogic.Object['comediconn'] = conncomedi

    if settings.has_licksensor:
        slick, connlick, addrlick, plick = \
            gc.spawn_process("\0licksocket", ['python3', '%s/py/licksensor.py' % blenderpath,])

        connlick.send(blenderpath.encode('latin-1'))
        gc.recv_ready(connlick)
        connlick.setblocking(0)
        GameLogic.Object['lickconn'] = connlick

    if settings.has_licksensor_piezo:
        slickpiezo, connlickpiezo, addrlickpiezo, plickpiezo = \
            gc.spawn_process("\0lickpiezosocket", ['python3', '%s/py/licksensorpiezo.py' % blenderpath,])

        connlickpiezo.send(blenderpath.encode('latin-1'))
        gc.recv_ready(connlickpiezo)
        connlickpiezo.setblocking(0)
        GameLogic.Object['lickpiezoconn'] = connlickpiezo

    if settings.cpp:
        for mconn in [conn1, conn2]:
            if mconn is not None:
                mconn.send(b'start')
                gc.recv_ready(mconn, usezmq=settings.usezmq)
                if not settings.usezmq:
                    mconn.setblocking(0)

    if len(mice):
        GameLogic.Object['m1conn'] = conn1
        GameLogic.Object['m2conn'] = conn2
    else:
        GameLogic.Object['m1conn'] = None
        GameLogic.Object['m2conn'] = None

    GameLogic.Object['tmprec'] = False
    GameLogic.Object['trainrec'] = False
    GameLogic.Object['RewardTicksCounter'] = None
    GameLogic.Object['RewardChange'] = False
    GameLogic.Object['WallTouchTicksCounter'] = None
    GameLogic.Object['OdorTicksCounter'] = None

    GameLogic.Object['piezolicks'] = 0
    GameLogic.Object['piezoframes'] = 0
    GameLogic.Object['piezoframepause'] = 0

    scene = GameLogic.getCurrentScene()
    if scene.name == "Scene":
        playerName = 'MovingCube'
        legName = 'LeftLeg'
    elif scene.name == "Looming":
        playerName = 'MovingCube.002'
        legName = 'LeftLeg.002'
    else:
        playerName = 'MovingCube.001'
        legName = 'LeftLeg.001'

    rew_sensor = scene.objects[playerName]
    touch_sensor = scene.objects[legName]

    if settings.linear:
        rew_sensor.sensors['SReward'].usePosPulseMode = True
        touch_sensor.sensors['SLeftTouch'].usePosPulseMode = True
    else:
        rew_sensor.sensors['SReward'].usePosPulseMode = False
        touch_sensor.sensors['SLeftTouch'].usePosPulseMode = False
    GameLogic.Object['scene_changed'] = 0
    GameLogic.Object['scene_name'] = scene.name

    GameLogic.Object['reset_pulse'] = False

    #current injection variables
    #variables for current injection - MC2015
    GameLogic.Object['start_pulse_y'] = 50
    GameLogic.Object['inj_amp'] = 50
    GameLogic.Object['do_tbs1'] = False
    GameLogic.Object['do_tbs2'] = False

    zeroPos()
    gc.zeroPump()
Beispiel #43
0
	def Pathing(self):
		cont = logic.getCurrentController()
		obj = cont.owner
		scene = logic.getCurrentScene()
		messageL = cont.sensors['MessageL']
		messageR = cont.sensors['MessageR']
		steering = cont.actuators['Steering']
		dict = logic.globalDict
		level = dict['level']
		enemyID = str(obj)[len(str(obj))-4:len(str(obj))]
		#print(scene.objects)
		
		def Init():
			if not 'init1' in obj:
				obj['init1'] = 1
				obj['evadeTimer'] = 50
				scene.addObject('EvadeR', obj)
				scene.addObject('EvadeL', obj)
				obj['trailTime'] = 0
				obj['trail'] = False
				if self.type == 'kamikaze':
					obj['following'] = False
		Init()
		
		
		#if 'Navmesh%s.000' % level in scene.objects:
		#	steering.navmesh = scene.objects['Navmesh%s.000' % level]
			
		evadeR = scene.objects['EvadeR']
		evadeL = scene.objects['EvadeL']
		obj['evadeTimer'] += 1
		
		if self.type == 'kamikaze' and obj.rayCast('Tank', obj, 0, 'player', 0, 0)[0] != None:
			obj['following'] = True
		
		if obj['trail'] == True and obj['trailTime'] > 2:
			scene.addObject('Trail', obj, 1000)
			obj['trailTime'] = 0
		
		if self.type != 'artillery':
			obj['trail'] = False
			obj['trailTime'] += 1
			for i in range (0,361,30):
				i *= (math.pi/180)	
				#Evading to the left
				if self.type == 'regular' and messageL.positive and obj['evadeTimer']:
					if 'Rocket' in scene.objects:
						evadeR.worldPosition = obj.worldPosition + Scalar(scene.objects['Rocket'].orientation[0], mathutils.Vector((-1,1,1)))*3
						evadeL.worldPosition = obj.worldPosition - Scalar(scene.objects['Rocket'].orientation[0], mathutils.Vector((-1,1,1)))*3
						steering.behavior = 2
						steering.distance = 1000
						cont.activate(steering)
						steering.target = scene.objects['EvadeR']
						obj['evadeTimer'] = 0
						#print(scene.objects['Rocket'].orientation[0])
						#render.drawLine(obj.worldPosition, scene.objects['EvadeR'].worldPosition,(1.0,1.0,1.0))
						#print("L")
				#Evading to the right
				elif self.type == 'regular' and messageR.positive and obj['evadeTimer']:
					if 'Rocket' in scene.objects:
						evadeR.worldPosition = obj.worldPosition + Scalar(scene.objects['Rocket'].orientation[0], mathutils.Vector((-1,1,1)))*3
						evadeL.worldPosition = obj.worldPosition - Scalar(scene.objects['Rocket'].orientation[0], mathutils.Vector((-1,1,1)))*3
						steering.behavior = 2
						steering.distance = 1000
						cont.activate(steering)
						steering.target = scene.objects['EvadeL']
						obj['evadeTimer'] = 0
						#render.drawLine(obj.worldPosition, scene.objects['EvadeL'].worldPosition,(1.0,1.0,1.0))
						#print("R")
				#Following Player
				elif self.type == 'regular' and obj.rayCast('Tank', obj, 0, 'player', 0, 0)[0] == None and obj['evadeTimer'] >= 50:
					steering.behavior = 3
					steering.distance = 1
					steering.target = scene.objects['Tank']
					cont.activate(steering)
					#render.drawLine(obj.worldPosition, steering.target.worldPosition, [1.0, 1.0, 1.0])
					#print("Tank")
				#Keeping distance from obstacles
				elif obj.rayCast(obj.worldPosition + mathutils.Vector((2.5*math.sin(i),2.5*math.cos(i),0)), obj, 2.5, "", 0, 0, 0)[0] != None and obj['evadeTimer'] >= 50:
					evadeObject = scene.addObject('Evade', obj, 50)
					evadeObject.worldPosition = obj.rayCast(obj.worldPosition + mathutils.Vector((2.5*math.sin(i),2.5*math.cos(i),0)), obj, 2.5, "", 0, 0, 0)[1]
					steering.behavior = 2
					steering.distance = 1000
					cont.activate(steering)
					steering.target = scene.objects['Evade']
					#render.drawLine(obj.worldPosition, obj.worldPosition + mathutils.Vector((5*math.sin(i),5*math.cos(i),0)), [1.0, 1.0, 1.0])
					#print("Wall")
				#kamikaze following player
				elif self.type == 'kamikaze' and obj['following'] == True:
					steering.behavior = 3
					steering.distance = 0
					steering.target = scene.objects['Tank']
					cont.activate(steering)
					#print("kamikaze")
				else:
					obj['trail'] = False
					cont.deactivate(steering)
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             #
#  GNU General Public License for more details.                              #
#                                                                            #
#  You should have received a copy of the GNU General Public License         #
#  along with AQUAgpusph.  If not, see <http://www.gnu.org/licenses/>.       #
#                                                                            #
##############################################################################

import bge
from bge import logic as g
from math import *
from mathutils import *
from sss_dynamic import sssDynamic
from sss_destroyable import sssDestroyable

GRAV = abs(g.getCurrentScene().gravity.z)
RHO = 1025.0


class sssFloating(sssDynamic, sssDestroyable):
    def __init__(self, obj):
        sssDynamic.__init__(self, obj)
        sssDestroyable.__init__(self, obj)
        # Convert the volume attributes in a faster set of arrays
        self.vols_z, self.vols_v = self.getVolumes()
        # Correct the mass factor (sometime it could gone out of bounds)
        z = self.worldPosition[2]
        self.worldPosition[2] = 0.0
        real_mass = self.displacement()
        self.worldPosition[2] = z
        blen_mass = self.mass
Beispiel #45
0
from bge import logic as g
from bge import texture
from mathutils import *
from math import *
import bgl
#import bpy

cont = g.getCurrentController()
own = cont.owner
scene = g.getCurrentScene()
objlist = scene.objects

reflsize = 512  #reflection tex dimensions
refrsize = 512  #refraction tex dimensions
offset = 0.2  #geometry clipping offset

#texture background color
bgR = 0.63
bgG = 0.84
bgB = 1.0
bgA = 0.0

activecam = scene.active_camera
viewer = activecam

#if 'initcam' not in own:
#	cam = bpy.data.cameras.new('rendercamera')
#	cam_ob = bpy.data.objects.new('watercamera', cam)
#	bpy.context.scene.objects.link(cam_ob)
#	own['initcam'] = 1
Beispiel #46
0
checks for key events

todo: add support for custom keys
--------------------------------------------------------------------------------------------------------
'''
from bge import logic, events

keyboard = logic.keyboard
mouse = logic.mouse

JUST_ACTIVATED = logic.KX_INPUT_JUST_ACTIVATED
JUST_RELEASED = logic.KX_INPUT_JUST_RELEASED
ACTIVE = logic.KX_INPUT_ACTIVE
NONE = logic.KX_INPUT_NONE

player = logic.getCurrentScene().objects['sintel_col']


def main(cont):
    if keyboard.events[events.WKEY] == JUST_ACTIVATED or keyboard.events[
            events.WKEY] == ACTIVE:
        player['FORWARD'] = True
    if keyboard.events[events.WKEY] == JUST_RELEASED:
        player['FORWARD'] = False
    if keyboard.events[events.AKEY] == JUST_ACTIVATED or keyboard.events[
            events.AKEY] == ACTIVE:
        player['LEFT'] = True
    if keyboard.events[events.AKEY] == JUST_RELEASED:
        player['LEFT'] = False
    if keyboard.events[events.SKEY] == JUST_ACTIVATED or keyboard.events[
            events.SKEY] == ACTIVE:
Beispiel #47
0
def Potion_Heal():
    target = logic.getCurrentScene().objects['System']['sys'].player['ent']
    target.fighter.hurt(-25)
    print("HEALED 25")
Beispiel #48
0
def carInit():
    ## setup aliases for Blender API access ##
    cont = logic.getCurrentController()
    logic.scene = logic.getCurrentScene()
    logic.car = cont.owner

    ## setup general vehicle characteristics ##
    wheelAttachDirLocal = [0, 0, -1]
    wheelAxleLocal = [-1, 0, 0]

    ## setup vehicle physics ##
    vehicle = constraints.createConstraint(logic.car.getPhysicsId(), 0,
                                           constraints.VEHICLE_CONSTRAINT)
    logic.car["cid"] = vehicle.getConstraintId()
    vehicle = constraints.getVehicleConstraint(logic.car["cid"])

    ## initialize temporary variables ##
    logic.car["dS"] = 0.0

    ## attached wheel based on actuator name ##
    wheel0 = logic.scene.objects["Wheel0"]
    wheelAttachPosLocal = [wheelBaseWide, wheelFrontOffset, AttachHeightLocal]
    vehicle.addWheel(wheel0, wheelAttachPosLocal, wheelAttachDirLocal,
                     wheelAxleLocal, suspensionLength, wheelRadius, 1)

    wheel1 = logic.scene.objects["Wheel1"]
    wheelAttachPosLocal = [-wheelBaseWide, wheelFrontOffset, AttachHeightLocal]
    vehicle.addWheel(wheel1, wheelAttachPosLocal, wheelAttachDirLocal,
                     wheelAxleLocal, suspensionLength, wheelRadius, 1)

    wheel2 = logic.scene.objects["Wheel2"]
    wheelAttachPosLocal = [wheelBaseWide, wheelBackOffset, AttachHeightLocal]
    vehicle.addWheel(wheel2, wheelAttachPosLocal, wheelAttachDirLocal,
                     wheelAxleLocal, suspensionLength, wheelRadius, 0)

    wheel3 = logic.scene.objects["Wheel3"]
    wheelAttachPosLocal = [-wheelBaseWide, wheelBackOffset, AttachHeightLocal]
    vehicle.addWheel(wheel3, wheelAttachPosLocal, wheelAttachDirLocal,
                     wheelAxleLocal, suspensionLength, wheelRadius, 0)

    ## set vehicle roll tendency ##
    vehicle.setRollInfluence(influence, 0)
    vehicle.setRollInfluence(influence, 1)
    vehicle.setRollInfluence(influence, 2)
    vehicle.setRollInfluence(influence, 3)

    ## set vehicle suspension hardness ##
    vehicle.setSuspensionStiffness(stiffness, 0)
    vehicle.setSuspensionStiffness(stiffness, 1)
    vehicle.setSuspensionStiffness(stiffness, 2)
    vehicle.setSuspensionStiffness(stiffness, 3)

    ## set vehicle suspension dampness ##
    vehicle.setSuspensionDamping(damping, 0)
    vehicle.setSuspensionDamping(damping, 1)
    vehicle.setSuspensionDamping(damping, 2)
    vehicle.setSuspensionDamping(damping, 3)

    ## set vehicle suspension compression ratio ##
    vehicle.setSuspensionCompression(compression, 0)
    vehicle.setSuspensionCompression(compression, 1)
    vehicle.setSuspensionCompression(compression, 2)
    vehicle.setSuspensionCompression(compression, 3)

    ## set vehicle tire friction ##
    vehicle.setTyreFriction(friction, 0)
    vehicle.setTyreFriction(friction, 1)
    vehicle.setTyreFriction(friction, 2)
    vehicle.setTyreFriction(friction, 3)
Beispiel #49
0
 def __init__(self):
     scene = logic.getCurrentScene()
     super(SpaceBlock, self).__init__(scene, scene.objects['space_block'])
from bge import logic as GameLogic
import numpy

THRESHOLD = 6.0


def checkDistance():
    if own.name + str("_marker") in scene.objects and not scene.objects[
            "Base"]["Selected"]:
        objPos = own.worldPosition
        markerPos = scene.objects[own.name + str("_marker")].worldPosition
        dist = numpy.linalg.norm(objPos - markerPos)
        if dist < THRESHOLD:
            sendMsg = cont.actuators["Message"]
            sendMsg.subject = "RemoveMarker"
            sendMsg.propName = own.name + str("_marker")
            cont.activate(sendMsg)


scene = GameLogic.getCurrentScene()

cont = GameLogic.getCurrentController()
own = cont.owner

if __name__ == "__main__":
    checkDistance()
Beispiel #51
0
	def kx_scene(self):
		return logic.getCurrentScene()
"""
Script dla programacion de los botones de inicio y noes envia
a la scena principal de BreathSoft
"""
from bge import logic as g, events
import Rasterizer
Rasterizer.showMouse(1)
controlador = g.getCurrentController()
propiedad = controlador.owner
escena = g.getCurrentScene()
raton = g.mouse.events
izq = raton[events.LEFTMOUSE]
sensor = controlador.sensors["raton"]
clic = sensor.hitObject
propiedad["clic"] = str(clic)

if not clic == None:
    if str(clic) == "Boton" and izq:
        controlador.activate("Entrada")
Beispiel #53
0
import bge.logic as logic
owner = logic.getCurrentController().owner
owner.position = [owner['startx'],owner['starty'],owner['startz']]
owner.orientation = [[1,0,0],[0,1,0],[0,0,1]]
logic.getCurrentScene().objects['race gate']['current_lap'] = 100.00
logic.getCurrentScene().objects['race gate']['lap'] = -1
lap = logic.getCurrentScene().objects['race gate']['lap']

if lap <= 0:
    logic.ghosts = []
else:
    if len(logic.ghosts)<lap:
        print("recording")
        print(len(logic.ghost))
        logic.ghost.append([owner.position,owner.orientation])
    
Beispiel #54
0
'''
--------------------------------------------------------------------------------------------------------
Translates the current camera to player cam - currently broken
getting orientation should be easy but it gets the inverse of what I need and inverting the matrix 
is spitting out an error
--------------------------------------------------------------------------------------------------------
'''
from bge import logic, render
import mathutils

sintel = logic.getCurrentScene().objects['sintel_col']
player_cam = logic.getCurrentScene().objects['player_camera']
sintel_cam_target = logic.getCurrentScene().objects['sintel_cam_target']
cam_defualt_pos = logic.getCurrentScene().objects['cam_defualt_pos']
#test_cam = logic.getCurrentScene().objects['test_cam']

slerp_factor = 0.0

scene = logic.getCurrentScene()

def init(cont):
	global from_quat, to_quat
	own = cont.owner
	
	current_cam = scene.active_camera
	#distance between player camera and the tracker
	dist = (own.position - player_cam.position)
	#set us at the proper position + orientation
	own.worldPosition = current_cam.worldPosition + dist
	own.localOrientation = current_cam.localOrientation.invert() # <------ doesn't work. can't explain that
	#where we are coming from
Beispiel #55
0
import bge.logic as logic
import math
import random
import os
import time
cont = logic.getCurrentController()
own = cont.owner
flowState = logic.flowState

playerRXFrequency = flowState.getRFEnvironment().getCurrentVRX().getFrequency()

errorLog = logic.getCurrentScene().objects['HUDError']
rxChannel = logic.getCurrentScene().objects['HUDRXChannel']
laps = logic.getCurrentScene().objects['HUDLapCount']
lastLap = logic.getCurrentScene().objects['HUDLastLap']
bestLap = logic.getCurrentScene().objects['HUDBestLap']
times = logic.getCurrentScene().objects['HUDLapTimes']
holeshot = logic.getCurrentScene().objects['HUDHoleshot']
countdown = logic.getCurrentScene().objects['HUDCountdown']
gForceCounter = logic.getCurrentScene().objects['HUDgForceCounter']
aspectRatioCropper = logic.getCurrentScene().objects['aspectRatioCropper']
#logic.flowState.setNotification(logic.getCurrentScene().objects['HUDNotification'])
logic.getCurrentScene(
).objects['HUDNotification']['Text'] = flowState.getNotification()['Text']

try:
    #let's try to display the channel the user is on
    ping = ""
    if (flowState.getGameMode() == flowState.GAME_MODE_MULTIPLAYER):
        ping = ", ping: " + str(int(flowState.getNetworkClient().ping)) + "ms"
    camera = logic.player['camera']
Beispiel #56
0
def looming():
    init_scale_up = [1.5, 1, 0]
    init_scale_down = [2, 1, 0]
    fin_scale = [0, 0, 0]
    speedscale = 1.0
    xuprescale = (2.34) * speedscale
    yuprescale = (1.56) * speedscale
    xdownrescale = (1.92) * speedscale
    ydownrescale = (0.96) * speedscale
    positions = np.array([(-10, 50, 90), (-10, 50, -15)])
    stop = settings.loom_interval - (
        settings.loom_grow_dur + settings.loom_maintain_dur
    )  # 30000-(grow_dur+maintain_dur)

    circle = GameLogic.getCurrentScene().objects["Circle"]
    if (GameLogic.Object['train_open'] or GameLogic.Object['file_open']) and (
            GameLogic.Object['loom_first_trial'] <
            settings.loom_first_trial_delay):
        GameLogic.Object['loom_first_trial'] += 1
    elif (GameLogic.Object['train_open'] or GameLogic.Object['file_open']):
        #print("Start looming stimulus presentation")
        #print(GameLogic.Object['loomcounter'])

        if GameLogic.Object['loomcounter'] == 0:
            tracked_speed = np.median(np.abs(GameLogic.Object['speed_tracker'])
                                      ) * 1e2 * GameLogic.getLogicTicRate()
            if tracked_speed > settings.loom_speed_threshold:
                # Start trial
                GameLogic.Object['puffthistrial'] = random.randint(0, 1)
                if settings.isloom_random:
                    GameLogic.Object['isloom'] = random.randint(0, 1)
                else:
                    GameLogic.Object['isloom'] = 1
                print(
                    "BLENDER: Looming stimulus trial starting - running detected.Puff: "
                    + str(GameLogic.Object['puffthistrial']))
                if settings.loom_random:
                    rand_pos_idx = random.randint(0, len(positions) - 1)
                else:
                    rand_pos_idx = 0
                GameLogic.Object['rand_pos_idx'] = rand_pos_idx
                circle.worldPosition = positions[rand_pos_idx]
                if rand_pos_idx == 0:
                    if GameLogic.Object['isloom']:
                        circle.localScale = init_scale_up
                    else:
                        circle.localScale = fin_scale
                elif rand_pos_idx == 1:
                    if GameLogic.Object['isloom']:
                        circle.localScale = init_scale_down
                    else:
                        circle.localScale = fin_scale
                GameLogic.Object['loomcounter'] += 1

        elif GameLogic.Object[
                'loomcounter'] < settings.loom_grow_dur + settings.loom_maintain_dur + stop:
            if GameLogic.Object['loomcounter'] < settings.loom_grow_dur:
                # Change scale during trial
                if (GameLogic.Object['rand_pos_idx'] == 0
                        and GameLogic.Object['isloom']):
                    circle.localScale.x += (xuprescale)
                    circle.localScale.y += (yuprescale)
                elif (GameLogic.Object['rand_pos_idx'] == 1
                      and GameLogic.Object['isloom']):
                    circle.localScale.x += (xdownrescale)
                    circle.localScale.y += (ydownrescale)
            elif GameLogic.Object[
                    'loomcounter'] > settings.loom_grow_dur + settings.loom_maintain_dur:
                # Stop trial and wait
                circle.localScale = fin_scale
            if settings.loom_airpuff_delay is not None:
                if (settings.puff_random and GameLogic.Object['puffthistrial']
                        == 1) or not settings.puff_random:
                    if GameLogic.Object['loomcounter']%settings.puffint == settings.loom_airpuff_delay and \
                    GameLogic.Object['puffcount'] < settings.puffnb:
                        airpuff_loom()
                        GameLogic.Object['puffcount'] += 1
                    else:
                        airpuff_loom_stop()

            GameLogic.Object['loomcounter'] += 1
        else:
            # Restart
            GameLogic.Object['loomcounter'] = 0
            GameLogic.Object['puffcount'] = 0

    else:
        circle.localScale = fin_scale

    if GameLogic.Object['train_open'] or GameLogic.Object['file_open']:
        gio.write_looming(circle)
from bge import logic
from link_scripts.PlayerConstants import ObjectType
from link_scripts.states.Look import start_firstLookView

scene = logic.getCurrentScene()


class PlayerObjectManager:
    def __init__(self, player):
        self.player = player
        self.mode = ObjectType.BOW
        self.use = False

    def useObject(self):
        if (self.player.gamepad.isItemXPressed()):
            self.use = True
            # For test go to bow
            start_firstLookView(self.player)
Beispiel #58
0
def Flame(particlelist):
    """
	Author: SolarLune (Josiah Lane)
	Date Updated: 4/26/11
	License: Custom - users of this script can use this script for any purpose, commercial or otherwise, with attribution.
	
	A generic particle handling script. Works for most kinds of particle effects.	
	"""

    sce = logic.getCurrentScene()
    cont = logic.getCurrentController()

    always = cont.sensors[0]
    freq = always.frequency + 1

    cam = sce.active_camera

    particles = particlelist[:]  # Make a copy of the array

    def Init(obj, override=0):

        if not 'init' in obj or override == 1:

            obj['init'] = 1
            obj['sf'] = 0.0

            if obj.parent == None:
                obj['scale'] = obj.scaling.copy()
            else:
                obj['scale'] = obj.localScale.copy(
                )  # Original scale of the particle

            if not 'emitter' in obj:  # Owner emitter object
                obj['emitter'] = None

            obj['time'] = 0.0  # Time before death

            obj['alpha'] = 0.0

            if not 'speed' in obj:
                obj['speed'] = [0.0, 0.0, 0.0]
            if not 'forcespd' in obj:  # Force speed
                obj['forcespeed'] = [0.0, 0.0, 0.0]

            if not 'friction' in obj:  # Default friction for the particle; if 1, then the smoke won't slow down
                obj['friction'] = [0.0, 0.0, 0.0]
            if not 'growrate' in obj:
                obj['growrate'] = 0.02  # Default growth rate

            obj['colorchange'] = 0
            obj.color = [1.0, 1.0, 0.0, obj.color[3]]

            if not 'cache' in obj:
                obj['cache'] = 0

            if not 'lod' in obj:
                obj['lod'] = 1
            if not 'loddist' in obj:
                obj['loddist'] = 10

            if not 'collide' in obj:
                obj['collide'] = 0
            if not 'collidevar' in obj:
                obj['collidevar'] = None

            if not 'startalpha' in obj:
                obj['startalpha'] = obj.color[
                    3]  # Original (starting) alpha (alpha to get up to when fading in)

            if not 'fadeout' in obj:
                obj['fadeout'] = 40.0

            if not 'fadein' in obj:
                obj['fadein'] = 0.0

            obj['fadingin'] = 0

            if obj['fadein'] > 0.0:
                obj.color = [obj.color[0], obj.color[1], obj.color[2],
                             0.0]  # Set the alpha to 0 to fade in from
                obj['fadingin'] = 1

            if not 'movelocal' in obj:
                obj['movelocal'] = 0

            obj['skip'] = 0  # Particle calculation LOD based on life

            if not 'life' in obj:
                obj['life'] = 40  # Default number of frames that the particle lives

            obj['frictionon'] = 0  # A simple check I do to make sure that friction is on; this reduces logic load on the CPU
            obj['forceon'] = 0  # Another simple check to make sure that force is on, reducing logic load
            obj['speedon'] = 0  # Another check for speed

            if obj['friction'][0] != 0 or obj['friction'][1] != 0 or obj[
                    'friction'][
                        2] != 0:  # Don't compute all this stuff if friction isn't on
                obj['frictionon'] = 1

            if obj['force'][0] != 0 or obj['force'][1] != 0 or obj['force'][
                    2] != 0:  # Don't compute all this stuff if force isn't on
                obj['forceon'] = 1

            if obj['speed'][0] != 0 or obj['speed'][1] != 0 or obj['speed'][
                    2] != 0:
                obj['speedon'] = 1

            obj['origscale'] = obj['scale'].copy()
            obj['origspd'] = obj['speed'][:]
            obj['origpos'] = obj.worldPosition.copy()

            if obj['emitter'] != None and not obj['emitter'].invalid:
                obj['origoff'] = obj['emitter'].worldPosition.copy(
                ) - obj.worldPosition.copy()
            else:
                obj['origoff'] = obj.worldPosition.copy()

            obj['origcolor'] = obj.color[:]

    for x in range(len(particles)):

        obj = particles[x]

        Init(obj)

        f = freq

        #emitter = obj['emitter']

        die = 0  # By default, the particle doesn't die, but later on, in the right circumstances, this variable will show that it should end

        ##### PARTICLE UPDATE #####

        obj['time'] += 1.0 * f

        if obj['frictionon']:

            obj['speed'][0] -= obj['speed'][0] * (obj['friction'][0] * f)
            obj['speed'][1] -= obj['speed'][1] * (obj['friction'][1] * f)
            obj['speed'][2] -= obj['speed'][2] * (obj['friction'][2] * f)

        spd = obj['speed']

        obj.applyMovement([spd[0] * f, spd[1] * f, spd[2] * f], 0)

        if (obj.getDistanceTo(cam) <= obj['loddist']
                and obj['lod'] == 1) or obj['lod'] == 0:

            if obj['growrate'] != 0:
                obj['sf'] += obj[
                    'growrate'] * f  # Scale the smoke by the particle's growth rate
                obj.scaling = [
                    obj['scale'].x + obj['sf'], obj['scale'].y + obj['sf'],
                    obj['scale'].z + obj['sf']
                ]

            alpha = obj['startalpha']

            if obj['time'] >= obj['life'] - obj['fadeout']:

                if obj['fadeout'] > 0.0 and obj['startalpha'] > 0.0:

                    rate = (-float(obj['startalpha']) /
                            float(obj['fadeout'])) * f
                    alpha = obj.color[3] + rate

            obj.color = [obj.color[0], obj.color[1], obj.color[2], alpha]

            if obj['colorchange'] == 0:
                if obj.color[1] > 0.5:

                    c = obj.color
                    c[1] -= 0.025 * f
                    obj.color = c

                else:
                    obj['colorchange'] = 1
            else:
                r = 0.025
                c = obj.color
                c[1] -= r * f
                c[2] -= r * f
                obj.color = c

        ##### PARTICLE DEATH #####

        if obj['fadeout'] == 1 and obj.color[3] <= 0.0:
            die = 1

        elif obj['time'] >= obj[
                'life']:  # If the particle is invisible or it has been alive for longer than it's life variable,
            die = 1

        elif not cam.pointInsideFrustum(obj.position) and obj['partcull']:
            die = 1

        if die:

            if obj['cache'] and not obj[
                    'emitter'].invalid:  # If the emitter still exists and caching is off

                del obj['init']  # Reinitialize the object
                obj['speed'] = obj[
                    'origspd'][:]  # And reset it, because the BGE will use the same particle again

                obj.worldPosition = obj['emitter'].worldPosition.copy(
                ) + obj['origoff']

                obj.scaling = obj['origscale'].copy()
                obj.color = obj['origcolor'][:]
                Init(obj)

                if obj['emitter']['partcache']:
                    obj['emitter']['cachedone'] = 1

            else:
                particlelist.remove(obj)
                obj.endObject()  # End the object

                if obj['emitter'] != None and not obj[
                        'emitter'].invalid:  # Tell the emitter that spawned you that you're gone
                    obj['emitter']['emitterpartamt'] -= 1
                    obj['emitter']['particles'].remove(obj)
Beispiel #59
0
def status_image():
    """
    Show the corrensponding Image for the status
    """
    imageHeight = windowHeight * 0.075
    imageWidth = imageHeight

    x = windowWidth * 0.35 - imageWidth / 2
    y = windowHeight * 0.45 - imageHeight / 2

    gl_position = [[x, y], [x + imageWidth, y],
                   [x + imageWidth, y + imageHeight], [x, y + imageHeight]]

    cam = logic.getCurrentScene().active_camera

    # get the suffix of the human to reference the right objects
    suffix = cam.name[-4:] if cam.name[-4] == "." else ""

    hand = objects['Hand_Grab.R' + suffix]

    # select the right Image
    if hand["selected"]:
        tex_id = closed_id
    else:
        tex_id = open_id

    view_buf = bgl.Buffer(bgl.GL_INT, 4)
    bgl.glGetIntegerv(bgl.GL_VIEWPORT, view_buf)
    view = view_buf.to_list() if hasattr(view_buf,
                                         "to_list") else view_buf.list
    # Save the state
    bgl.glPushAttrib(bgl.GL_ALL_ATTRIB_BITS)
    # Disable depth test so we always draw over things
    bgl.glDisable(bgl.GL_DEPTH_TEST)
    # Disable lighting so everything is shadless
    bgl.glDisable(bgl.GL_LIGHTING)
    # Unbinding the texture prevents BGUI frames from somehow picking up on
    # color of the last used texture
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)
    # Make sure we're using smooth shading instead of flat
    bgl.glShadeModel(bgl.GL_SMOOTH)
    # Setup the matrices
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glPushMatrix()
    bgl.glLoadIdentity()
    bgl.gluOrtho2D(0, view[2], 0, view[3])
    bgl.glMatrixMode(bgl.GL_MODELVIEW)
    bgl.glPushMatrix()
    bgl.glLoadIdentity()

    bgl.glEnable(bgl.GL_TEXTURE_2D)
    # Enable alpha blending
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
    # Bind the texture
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, tex_id)
    # Draw the textured quad
    bgl.glColor4f(1, 1, 1, 1)
    bgl.glEnable(bgl.GL_POLYGON_OFFSET_FILL)
    bgl.glPolygonOffset(1.0, 1.0)
    bgl.glBegin(bgl.GL_QUADS)
    for i in range(4):
        bgl.glTexCoord2f(texco[i][0], texco[i][1])
        bgl.glVertex2f(gl_position[i][0], gl_position[i][1])
    bgl.glEnd()
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)

    bgl.glPopMatrix()
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glPopMatrix()
    bgl.glPopAttrib()
Beispiel #60
0
"""
Basic Physics Constraint
------------------------
Example of how to create a hinge Physics Constraint between two objects.
"""
from bge import logic
from bge import constraints

# get object list
objects = logic.getCurrentScene().objects

# get object named Object1 and Object 2
object_1 = objects["Object1"]
object_2 = objects["Object2"]

# want to use Edge constraint type
constraint_type = 2

# get Object1 and Object2 physics IDs
physics_id_1 = object_1.getPhysicsId()
physics_id_2 = object_2.getPhysicsId()

# use bottom right edge of Object1 for hinge position
edge_position_x = 1.0
edge_position_y = 0.0
edge_position_z = -1.0

# rotate the pivot z axis about 90 degrees
edge_angle_x = 0.0
edge_angle_y = 0.0
edge_angle_z = 90.0