def main(self): if self.info_part < len(self.info_order): self.info_text['Text'] = self.info_order[self.info_part] if self.delay_timer() and self.info_part != 2: self.info_part += 1 if self.info_part == 6: obj = self.scene.addObject("Enemy1.001", self, 0) self.info_part += 1 enemies = [e for e in self.scene.objects if "enemy" in e] if self.info_part > 6 and not len(enemies): self.info_text['Text'] = "Good. \nStart survival when\n you're ready." if self.info_part == 2: bullets = [i for i in self.scene.objects if "bullet" in i] if len(bullets): self.info_part += 1 self.delay_timer.reset() buttons = [i for i in logic.joysticks if i and 7 in i.activeButtons] if len(buttons): self.info_text.setVisible(False) self.press_start.setVisible(False) logic.getCurrentController().activate(self.actuators[0])
def tower_controller_run(): spawn_bullets = { "tower_mid_front":"spawn_bullet_mid_front", "tower_mid_mid":"spawn_bullet_mid_mid", "tower_mid_back":"spawn_bullet_mid_back", "tower_left_front":"spawn_bullet_left_front", "tower_left_mid":"spawn_bullet_left_mid", "tower_left_back":"spawn_bullet_left_back", "tower_right_front":"spawn_tower_right_front", "tower_right_mid":"spawn_tower_right_mid", "tower_right_back":"spawn_tower_right_back", "tower_home_left":"spawn_bullet_home_left", "tower_home_right":"spawn_bullet_home_right", "thai_tower_mid_front":"thai_spawn_bullet_mid_front", "thai_tower_mid_mid":"thai_spawn_bullet_mid_mid", "thai_tower_mid_back":"thai_spawn_bullet_mid_back", "thai_tower_left_front":"thai_spawn_bullet_left_front", "thai_tower_left_mid":"thai_spawn_bullet_left_mid", "thai_tower_left_back":"thai_spawn_bullet_left_back", "thai_tower_right_front":"thai_spawn_bullet_right_front", "thai_tower_right_mid":"thai_spawn_bullet_right_mid", "thai_tower_right_back":"thai_spawn_bullet_right_back", "thai_tower_home_left":"thai_spawn_bullet_home_left", "thai_tower_home_right":"thai_spawn_bullet_home_right", } scene = logic.getCurrentScene() cont = logic.getCurrentController() for tower_position in spawn_bullets.keys(): tower_controller(tower_position, spawn_bullets[tower_position],scene)
def main(): global credits_list global last_added_title cont = logic.getCurrentController() goto_menu = cont.actuators['goto_menu'] #title_font = logic.getCurrentScene().objects['title_font'] if own['names'] != True: if own['credits_start'] >=5: if credits_list != []: send_title() own['credits_start'] = 0 own['names'] = True else: cont.activate(goto_menu) else: if own['credits_start'] >=3.5: if names_list != []: send_name() own['credits_start'] = 0 else: own['names'] = False last_added_title['gone'] = True
def loadTemp(): cont = logic.getCurrentController() own = cont.owner file = open(path+'.#Temp.txt','r') line = file.readline().replace('\n','').split(',') own['score'] = int(line[0])
def load(): """Method called one time at the emitter generation""" cont = g.getCurrentController() obj = cont.owner obj['t'] = 0.0 # Emitter lifetime obj['pending'] = 0.0 # Number of pending particles to be emitted return
def Timer(): 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() 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()
def Explosion(): cont = logic.getCurrentController() obj = cont.owner scene = logic.getCurrentScene() tank_explosion = cont.sensors['Message1'] rocket_explosion = cont.sensors['Message2'] def Init(): if not 'init' in obj: obj['init'] = 1 obj['time'] = 0.0 #for i in range(1,26): #bit = scene.addObject('Bit', obj, 100) def Update(): if obj['time'] > 37.0: obj.endObject() #scene.objects['Effect1'].endObject() #scene.objects['Effect2'].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()
def main(): # get the current controller controller = logic.getCurrentController() vehobj = controller.owner # get vehicle constraint ID vehicleID = ConstraintID(controller) # set tire grip Tire_Grip(vehicleID) # set suspension compression Suspension_Compression(vehicleID) # set suspension damping Suspension_Damping(vehicleID) # set suspension stiffness Suspension_Stiffness(vehicleID) # set roll influence Roll_Influence(vehicleID)
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)
def __getattr__(self, name): match = re.search(self.get_function_name, name) if match is None: if name == "__all__": return [k for k in globals().keys() if not k.startswith("_")] try: return globals()[name] except KeyError: raise AttributeError(name) function_name = match.group(0) if function_name not in globals(): raise AttributeError(function_name) argument_match = re.search(self.get_arguments, name) if argument_match is None: arguments = "" else: arguments = argument_match.group(1) data = globals().copy() data["cont"] = logic.getCurrentController() return lambda: exec("{}(cont, {})".format(function_name, arguments), data)
def RocketInit(): cont = logic.getCurrentController() obj = cont.owner scene = logic.getCurrentScene() mouse = logic.mouse.events msshoot = mouse[events.LEFTMOUSE] def Init(): if not 'init' in obj: obj['init'] = 1 obj['atk'] = 10 obj['shottimer'] = 50.0 obj['dir'] = 0.0 def Update(): obj['shottimer'] += 1.0 if msshoot: if obj['shottimer'] >= 60.0: obj['shottimer'] = 0.0 rocket = scene.addObject('Rocket', obj) rocket['speed'] = 0.25 rocket['dir'] = obj['dir'] Init() Update()
def run(): controller = logic.getCurrentController() obj = controller.owner if not obj['hasInitialized']: print('trying to fetch merchants') render_merchants() obj['hasInitialized'] = True
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
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()
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()
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()
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()
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()
def findObject(self): """ Find a object in zone """ find = False cont = logic.getCurrentController() collision = cont.sensors['targetCollision'] # if detect if collision.positive: # Get all objects detected listObject = collision.hitObjectList # Choose the appropriate enemy for obj in listObject: if ( ('actif' in obj and obj['actif']) and find == False): self.targetObject = obj find = True # If find object apply if (find): logic.playerHUD.setTargetHUDState(True) self.updateTargetCursor(self.targetObject) else: logic.playerHUD.setTargetHUDState(False) self.targetObject = None # Return statement return find
def Bounce(my, front = 0.6, left = 0.2, right = 0.2, prop = 'wall'): cont = logic.getCurrentController() obj = cont.owner ori = obj.localOrientation[1].copy() ori.x *= -1 angle = math.atan2(ori.y,ori.x) * 57.2958 pos = obj.position toPosFront = (pos + ori) toPosLeft = (pos + ori) toPosRight = (pos + ori) toPosLeft.y = pos.y - (ori.x * left) + (ori.y * front) toPosLeft.x = pos.x - (ori.y * left) + (ori.x * front) toPosRight.y = pos.y + (ori.x * right) + (ori.y * front) toPosRight.x = pos.x + (ori.y * right) + (ori.x * front) colAngle = mathutils.Vector((0.0, 0.0, 0.0)) if obj.rayCast(toPosFront, pos, 0, prop, 1, 1)[0] != None: colAngle = obj.rayCast(toPosFront, pos, 0, prop, 1, 1)[2] elif obj.rayCast(toPosLeft, pos, 0, prop, 1, 1)[0] != None: colAngle = obj.rayCast(toPosLeft, pos, 0, prop, 1, 1)[2] elif obj.rayCast(toPosRight, pos, 0, prop, 1, 1)[0] != None: colAngle = obj.rayCast(toPosRight, pos, 0, prop, 1, 1)[2] #render.drawLine(obj.position, toPosFront, [0.0, 0.0, 1.0]) #render.drawLine(obj.position, toPosLeft, [0.0, 0.0, 1.0]) #render.drawLine(obj.position, toPosRight, [0.0, 0.0, 1.0]) return colAngle
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()
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']
def main(): # get the current controller controller = logic.getCurrentController() ##print(controller.sensors) vehobj = controller.owner # get vehicle constraint ID vehicleID = ConstraintID(controller) # brakes brakes,fxf_b,fxr_b = Brakes(vehicleID, controller,vehobj,mu) # gas & reverse Power( vehicleID, controller, brakes,vehobj,mu) # steering steerval = Steering(vehicleID, controller) alpha_f,alpha_r = getSlip(vehobj,steerval,f) #now we calculate the Dugoff tire Fy. TODO legitimate (or closer) Fz Fz = vehobj.mass/4*9.81 Fyf = dugoffFy(alpha_f,Fz,mu,fxf_b) fyf = abs(Fyf/Fz) Fyr = dugoffFy(alpha_r,Fz,mu,fxr_b) fyr = abs(Fyf/Fz) Tire_Grip2(vehicleID,vehobj,fyf,fyf,fyr,fyr)
def CountdownAction(): 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: for i in scenes: if 'Level%s' % level in i.name: i.resume() for i in scenes: if 'Score' in i.name: i.resume() for i in scenes: if 'Menu' in i.name: i.end() scene.end() obj['time'] += 1.0 Init() Update()
def Init(): cont = logic.getCurrentController() obj = cont.owner if not 'init' in obj: obj['init'] = 1 obj['var'] = 0 obj['time'] = 0
def main(): cont = gl.getCurrentController() player = cont.owner # la valeur de la propriete passee dans l'actuator vitesse = cont.actuators["speed_actuator"] # Recoit et traite valeur du GSR pour la rotation value = ManageSpeed.computeSpeed(gl.currentGSR) # Keyboard controlled (Debug) """ keyboard = gl.keyboard JUST_ACTIVATED = gl.KX_INPUT_JUST_ACTIVATED ACTIVE = gl.KX_SENSOR_ACTIVE if keyboard.events[bge.events.UPARROWKEY] == gl.KX_SENSOR_ACTIVE : value += .002 if keyboard.events[bge.events.DOWNARROWKEY] == gl.KX_SENSOR_ACTIVE : value -= .002 """ # update valeur vitesse dans la propriete vitesse.value = str(value) cont.activate(vitesse) # Rotation player.applyRotation((0, 0, player.get(vitesse.propName)), True)
def keyHandler(): cont = logic.getCurrentController() keys = cont.sensors["key"].events for key in keys: ## up arrow if key[0] == events.UPARROWKEY: logic.car["force"] = -15.0 ## down arrow elif key[0] == events.DOWNARROWKEY: logic.car["force"] = 10.0 ## right arrow elif key[0] == events.RIGHTARROWKEY: logic.car["steer"] -= 0.05 ## left arrow elif key[0] == events.LEFTARROWKEY: logic.car["steer"] += 0.05 ## Reverse elif key[0] == events.RKEY: if key[1] == 1: # re-orient car if logic.car["jump"] > 2.0: pos = logic.car.worldPosition logic.car.position = (pos[0], pos[1], pos[2]+3.0) logic.car.alignAxisToVect([0.0,0.0,1.0], 2, 1.0) logic.car.setLinearVelocity([0.0,0.0,0.0],1) logic.car.setAngularVelocity([0.0,0.0,0.0],1) logic.car["jump"] = 0 ## Spacebar elif key[0] == events.SPACEKEY: # hackish Brake if logic.car["speed"] > 2.0: logic.car["force"] = 15.0 if logic.car["speed"] < -2.0: logic.car["force"] = -15.0
def move(): cont =logic.getCurrentController() own = cont.owner animation = cont.actuators["animation"] minion = None if "team" in own: if own["team"]=="team2": minion = Minion( cont, animation, own, "Armature_creep_mid_team2", "creep_mid_action_team2" ) elif own["team"]=="team1": minion = Minion(cont, animation, own, "Armature_creep_mid_team1", "creep_action_mid_team1" ) if minion != None : minion.set_first_path("checkpoint_central1") minion.move_unit() minion.damaged() if own["hp"]<=0: minion.die_and_gold()
def swordTouchClang(self): cont = logic.getCurrentController() sens = cont.sensors['sword_touch_clang'] if ( sens.positive ): return True else: return False
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 displayResolution(): cont = logic.getCurrentController() rend = bge.render width = rend.getWindowWidth() height = rend.getWindowHeight() cont.owner["Text"] = "(" + str(width) + "x" + str(height) + ")"
def maxDesktopHeight(): cont = logic.getCurrentController() rend = bge.render cont.owner["desktopHeight"] = rend.getWindowHeight()
def main(): cont = logic.getCurrentController() owner = cont.owner viable_attacks = ( "Neutral", "Up Neutral", "Down Neutral", "Forward Neutral", "Up Jazz", "Down Jazz", "Forward Jazz", "Neutral Aerial", "Up Aerial", "Down Aerial", "Forward Aerial", "Back Aerial", ) message = owner.sensors["Message"] if message.positive: action_name = message.subjects[0] if action_name in viable_attacks: owner["attack_data"] = owner["frame_data"][action_name] owner["inAction"] = True owner["isAttacking"] = True if owner["inAction"]: attack_data = owner["attack_data"] phases = attack_data["phases"] for phase_name in phases: phase_data = attack_data[phase_name] active_frames = phase_data["active_frames"] current_frame = owner["Frame"] if current_frame in active_frames: hitboxes = phase_data["hitboxes"] for hitbox_num in hitboxes: hitbox_name = " ".join(["Wedge", "Hitbox", hitbox_num]) owner.sendMessage("Active!", "", hitbox_name) if owner["isAttacking"]: attack_data = owner["attack_data"] phases = attack_data["phases"] for phase_name in phases: phase_data = attack_data[phase_name] active_frames = phase_data["active_frames"] current_frame = owner["Frame"] if current_frame in active_frames: hitboxes = phase_data["hitboxes"] for hitbox_num in hitboxes: hit = False children = owner.children hitbox_name = " ".join(["Wedge", "Hitbox", hitbox_num]) hitbox = children[hitbox_name] hitbox_data_name = "_".join(["hitbox", "data", hitbox_num]) hitbox_data = phase_data[hitbox_data_name] hit_detection = hitbox.sensors["Hit Detection"] hit_objects = list(hit_detection.hitObjectList) for obj in hit_objects: if obj != owner.parent: damage = hitbox_data["damage"] obj["Percent"] += damage force_x = hitbox_data["force_x"] force_z = hitbox_data["force_z"] scaling = hitbox_data["scaling"] percent = obj["Percent"] force_x = force_x * scaling * percent force_z = force_z * scaling * percent if owner["Facing"] == "Left": force_x *= -1 obj.linearVelocity = [force_x, 0.0, force_z] percent_str = str(obj["Percent"]) percent_len = len(percent_str) spacing_dict = {1: " ", 2: " ", 3: ""} spacing = spacing_dict[percent_len] text = spacing + percent_str overlay = logic.getSceneList()[1] percent_text = overlay.objects["P2 Percent"] percent_text.text = text owner.sendMessage(str(damage), "", "P2 Percent") hit = True if hit: break if hit: owner["isAttacking"] = False break action_name = owner.getActionName() if action_name in ("Idle", ""): owner["inAction"] = False owner["isAttacking"] = False
def populate(room_list, room_4way, room_straight, room_end, room_corner, room_t, room_ceiling={0: None}, spawn_point=None, varying_size=0): """ Populates the in-game world with floor pieces according to the room that you feed into the function. room_list = a room list to check that's generated with a Gen...() function. room_4way - room_middle = dictionaries of room pieces to choose from. The numbered indices correspond to the numbers you fed into the generation function. Will be randomly chosen from to allow for some good-looking random level design. The dictionaries should look like: room_4way = {1:['Room4WayRock', 'Room4WayStone', 'Room4WayStone2', etc], 2:[...]} The number represents the cell type (i.e. a 1 on the grid will spawn one of the rooms in the 1 list) room_4way = a room with four exits (a cross shape) room_straight = a room with two exits across from each other; turned horizontally room_end = a room with one exit (a dead end); opens to the west. room_corner = a room with two exits (an L-shaped room); opens to the west and turns north (left). room_t = a room with three exits (a T-shaped room); facing "upside-down", so that the flat part faces south. room_ceiling = the same as above, but optional. This would be the objects to place on every null value (i.e. 0) spawn_point = the center of the map, usually; if left to None, it will be the calling object's world position. varying_size = if the size of the rooms is individual (i.e. each room can be different sizes), or if they're all the same NOTE: Each game object that gets spawned gets a property called rlg_info with information about its place in the level generation recorded in it. The rlg_info property has three keys: "shape", "pos", and "type". The "shape" key equals one of the RLG_POP_xxxxx constants, which dictates what shape the object spawned was supposed to be. The "pos" key equals the grid position in the random level map, with the Y-coordinate (or row) first, and the X-coordinate second. The "type" key equals what type of object was spawned based on the random level map's numbers (i.e. it's a 1 if it was spawned where a 1 was on the random level map). Returns a dictionary comprised of two keys: "spawned: A list of all room objects spawned "room_map": The room_list that you fed in, but with the values replaced by references to the room objects spawned (useful for storage and looking up a room in the list later) """ sce = logic.getCurrentScene() cont = logic.getCurrentController() obj = cont.owner spawned = [] rl = copy.deepcopy(room_list) if not varying_size: i = list(room_4way.keys())[0] r = room_4way[i] roomsize = get_dimensions(r[0])[0] for ry in range(len(room_list)): cy = abs( ry - (len(room_list) - 1) ) # We have to do this because otherwise, the check will go from bottom to top, incorrectly (the data will be turned around) for rx in range(len(room_list[ry])): if not room_list[ry][rx] in room_ceiling: # Not blank cell = room_list[ry][rx] sur = get_surrounding_cells(room_list, ry, rx) if sur['num'] == 1: # End roomchoice = random.choice(room_end[cell]) r = sce.addObject(roomchoice, obj) ori = r.orientation.to_euler() d = sur['cells'] if d['right']: ori.z = math.pi elif d['left']: ori.z = 0.0 elif d['up']: ori.z = -math.pi / 2.0 elif d['down']: ori.z = math.pi / 2.0 elif sur['num'] == 2: # Corner or Straight-through d = sur['cells'] if (d['left'] and d['right']) or (d['up'] and d['down']): straight = 1 else: straight = 0 if straight: roomchoice = random.choice(room_straight[cell]) r = sce.addObject(roomchoice, obj) ori = r.orientation.to_euler() if d['left'] and d['right']: ori.z = 0.0 elif d['up'] and d['down']: ori.z = math.pi / 2.0 else: roomchoice = random.choice(room_corner[cell]) r = sce.addObject(roomchoice, obj) ori = r.orientation.to_euler() if d['left'] and d['up']: ori.z = 0.0 elif d['left'] and d['down']: ori.z = math.pi / 2.0 elif d['right'] and d['up']: ori.z = -math.pi / 2.0 else: ori.z = math.pi elif sur['num'] == 3: # Middle roomchoice = random.choice(room_t[cell]) r = sce.addObject(roomchoice, obj) ori = r.orientation.to_euler() d = sur['cells'] if d['left'] and d['right'] and d['up']: ori.z = 0.0 elif d['left'] and d['up'] and d['down']: ori.z = math.pi / 2.0 elif d['right'] and d['up'] and d['down']: ori.z = -math.pi / 2.0 else: ori.z = math.pi else: # 4-way roomchoice = random.choice(room_4way[cell]) r = sce.addObject(roomchoice, obj) ori = r.orientation.to_euler() spawned.append(r) r.orientation = ori rlg_info = {'shape': None, 'type': cell, 'pos': (ry, rx)} if sur['num'] == 1: rlg_info['shape'] = RLG_POP_END elif sur['num'] == 2: if straight: rlg_info['shape'] = RLG_POP_STRAIGHT else: rlg_info['shape'] = RLG_POP_CORNER elif sur['num'] == 3: rlg_info['shape'] = RLG_POP_T_END else: rlg_info['shape'] = RLG_POP_4WAY r['rlg_info'] = rlg_info rl[ry][rx] = r if varying_size: roomsize = get_dimensions(r) halfmapw = math.floor(len(room_list[0]) / 2.0) * roomsize[0] halfmaph = math.floor(len(room_list) / 2.0) * roomsize[1] if spawn_point is None: spawn_point = list(obj.worldPosition) else: spawn_point = list(spawn_point) pos = [(rx * roomsize[0]) - (halfmapw) + spawn_point[0], (cy * roomsize[1]) - (halfmaph) + spawn_point[1], spawn_point[2]] r.worldPosition = pos else: # Blank, so it's a ceiling piece. if not room_ceiling[room_list[ry][rx]] is None: roomchoice = random.choice(room_ceiling[room_list[ry][rx]]) r = sce.addObject(roomchoice, obj) spawned.append(r) rl[ry][rx] = r rlg_info = { 'shape': RLG_POP_CEIL, 'type': room_list[ry][rx], 'pos': (ry, rx) } r['rlg_info'] = rlg_info halfmapw = math.floor( len(room_list[0]) / 2.0) * roomsize[0] halfmaph = math.floor(len(room_list) / 2.0) * roomsize[1] if spawn_point is None: spawn_point = list(obj.worldPosition) else: spawn_point = list(spawn_point) pos = [(rx * roomsize[0]) - (halfmapw) + spawn_point[0], (cy * roomsize[1]) - (halfmaph) + spawn_point[1], spawn_point[2]] r.worldPosition = pos return ({'spawned': spawned, 'room_map': rl})
def init(): global cont, own cont = logic.getCurrentController() own = cont.owner
def Gun(): cont = logic.getCurrentController() obj = cont.owner scene = logic.getCurrentScene() motion = cont.actuators['Motion'] obj['parent'] = scene.objects['Tank'] aim = scene.objects['TankAim'] rInit = scene.objects['RocketInit'] def Init(): if not 'init' in obj: obj['init'] = 1 obj['scale'] = 1 obj['time'] = 0 scene.addObject('LaserPoint',obj) def Update(): obj.worldPosition = obj['parent'].worldPosition #obj['time'] += 1 def MousePos(): x = int(render.getWindowWidth() / 2 - (logic.mouse.position[0] * render.getWindowWidth())) * obj['scale'] y = int(render.getWindowHeight() / 2 - (logic.mouse.position[1] * render.getWindowHeight())) * obj['scale'] return mathutils.Vector((-x, y, 0.6520)) toVect = MousePos() - obj.worldPosition #print (logic.mouse.position) obj.alignAxisToVect(toVect, 1, 1) obj.alignAxisToVect([0.0, 0.0, 1.0], 2, 1) """if MousePos()[0] < (-int(render.getWindowWidth()/2 - 100)): render.setMousePosition(110, int(render.getWindowHeight()/2) - int(MousePos()[1])) elif MousePos()[0] > (int(render.getWindowWidth()/2 - 100)): render.setMousePosition(render.getWindowWidth() - 110, int(render.getWindowHeight()/2) - int(MousePos()[1])) if MousePos()[1] < (-int(render.getWindowHeight()/2 - 100)): render.setMousePosition(int(render.getWindowWidth()/2) + int(MousePos()[0]), int(render.getWindowHeight() - 110)) elif MousePos()[1] > (int(render.getWindowHeight()/2 - 100)): render.setMousePosition(int(render.getWindowWidth()/2) + int(MousePos()[0]), 110)""" #logic.mouse.visible = True """#####################OLD AIMING SYSTEM BELOW################""" """def mousePos(): x = int(render.getWindowWidth() / 2 - (logic.mouse.position[0] * render.getWindowWidth())) * obj['scale'] return x if obj['time'] > 1: pos = mousePos() motion.useLocalDRot = False motion.dRot = (0.0, 0.0, pos) cont.activate(motion) """ #render.setMousePosition(int(render.getWindowWidth() / 2), int(render.getWindowHeight() / 2)) def Laser(): ray = obj.rayCast(aim, rInit, 500, '', 1, 0)[1] hitPos = [ray[0], ray[1], ray[2]] render.drawLine(rInit.worldPosition, hitPos, [1.0, 0.0, 0.0]) scene.objects['LaserPoint'].worldPosition = (mathutils.Vector((hitPos[0], hitPos[1], hitPos[2])) + (obj.rayCast(aim, rInit, 500, '', 1, 0)[2]*.25)) Init() Update() Laser()
def Player(): cont = logic.getCurrentController() obj = cont.owner scene = logic.getCurrentScene() motion = cont.actuators['Motion'] #Keyboard movement events key = logic.keyboard.events kbleft = key[events.AKEY] kbright = key[events.DKEY] kbup = key[events.WKEY] kbdown = key[events.SKEY] #Init function. Runs once. def Init(): if not 'init' in obj: obj['init'] = 1 obj['my'] = 0.0 obj['mx'] = 0.0 obj['maxspeed'] = .1 obj['accel'] = .01 obj['friction'] = 0.1 obj['hp'] = 10 scene.objects['CamMain']['players'] += 1.0 obj['explode'] = True obj['dir'] = 0.0 obj['trailTime'] = 0 #Update function. Runs every logic frame when TRUE level triggering is active def Update(): obj['trailTime'] += 1 #left/right motion if kbleft > 0: obj['mx'] += -obj['accel'] if obj['trailTime'] > 2: obj['trailTime'] = 0 scene.addObject('Trail', obj, 1000) elif kbright > 0: obj['mx'] += obj['accel'] if obj['trailTime'] > 2: obj['trailTime'] = 0 scene.addObject('Trail', obj, 1000) else: obj['mx'] *= (1-obj['friction']) #up/down motion if kbup > 0: obj['my'] += obj['accel'] if obj['trailTime'] > 2: obj['trailTime'] = 0 scene.addObject('Trail', obj, 1000) elif kbdown > 0: obj['my'] += -obj['accel'] if obj['trailTime'] > 2: obj['trailTime'] = 0 scene.addObject('Trail', obj, 1000) else: obj['my'] *= (1-obj['friction']) if AxisCheck(obj['my'], 1.0, 1.0, 1.0, 'wall')[0] != None: obj['my'] = 0 #Max speed obj['mx'] = Max(obj['mx'], obj['maxspeed'],-obj['maxspeed']) obj['my'] = Max(obj['my'], obj['maxspeed'],-obj['maxspeed']) motion.useLocalDLoc = False motion.dLoc = [obj['mx'], obj['my'] ,0.0] cont.activate(motion) def Animate(): ori = obj.orientation.to_euler() obj['dir'] = math.atan2(-obj['mx'], obj['my']) ori.z = obj['dir'] obj.orientation = ori def Death(): if obj['hp'] < 1: scene.addObject('Explosion',obj) logic.sendMessage('explosion', 'None') obj.endObject() scene.objects['TankGun'].endObject() scene.objects['CamMain']['players'] -= 1 Init() Update() Animate() Death()
def write_record_file(move, xtranslate, ytranslate, zrotate): time1 = time.time() dt = time1 - GameLogic.Object['time0'] arduino = GameLogic.Object['arduino'] controller = GameLogic.getCurrentController() own = controller.owner if GameLogic.Object['bcstatus'] == False: if arduino is not None: gc.write_arduino_nonblocking(arduino, b'u') if settings.has_comedi and ncl.has_comedi: ncl.set_trig(GameLogic.Object['outfrch'], 1) GameLogic.Object['bcstatus'] = True else: if arduino is not None: gc.write_arduino_nonblocking(arduino, b'd') if settings.has_comedi and ncl.has_comedi: ncl.set_trig(GameLogic.Object['outfrch'], 0) GameLogic.Object['bcstatus'] = False if GameLogic.Object['has_fw']: frametimefw = gc.parse_frametimes( GameLogic.Object['fwconn']) - GameLogic.Object['time0'] elif GameLogic.Object['has_usb3']: frametimefw = gc.parse_frametimes( GameLogic.Object['usb3conn']) - GameLogic.Object['time0'] if 'usb3conn2' in GameLogic.Object.keys(): frametimefw2 = gc.parse_frametimes( GameLogic.Object['usb3conn2']) - GameLogic.Object['time0'] frametimefw2 = -frametimefw2 - 10 frametimefw = np.concatenate((frametimefw, frametimefw2)) else: frametimefw = np.array([ 0, ]) GameLogic.Object['current_file'].write( np.array([ dt, xtranslate, ytranslate, zrotate, own.position[0], own.position[1], own.position[2], time1, own.orientation[0][0], own.orientation[0][1], own.orientation[0][2], own.orientation[1][0], own.orientation[1][1], own.orientation[1][2], own.orientation[2][0], own.orientation[1][2], own.orientation[2][2], len(move[0]), len(move[2]), len(frametimefw) ], dtype=np.float64).tostring()) # 0:x1, 1:y1, 2:x2, 3:y2, 4:t1, 5:t2, 6:dt1, 7:dt2 GameLogic.Object['current_file'].flush() for nm in range(len(move[0])): GameLogic.Object['current_file'].write( np.array([move[0][nm], move[1][nm], move[4][nm], move[6][nm]], dtype=np.float64).tostring()) for nm in range(len(move[2])): GameLogic.Object['current_file'].write( np.array([move[2][nm], move[3][nm], move[5][nm], move[7][nm]], dtype=np.float64).tostring()) if (len(move[0]) or len(move[2])): GameLogic.Object['current_file'].flush() if len(frametimefw) > 0: GameLogic.Object['current_file'].write(frametimefw.tostring()) GameLogic.Object['current_file'].flush()
def write_training_file(move, xtranslate, ytranslate, zrotate): # get controller controller = GameLogic.getCurrentController() own = controller.owner has_fw = GameLogic.Object['has_fw'] if has_fw: connfw = GameLogic.Object['fwconn'] else: connfw = None has_usb3 = GameLogic.Object['has_usb3'] if has_usb3: connusb3 = GameLogic.Object['usb3conn'] if 'usb3conn2' in GameLogic.Object.keys(): conn2usb3 = GameLogic.Object['usb3conn2'] else: conn2usb3 = None else: connusb3 = None conn2usb3 = None time1 = time.time() dt = time1 - GameLogic.Object['train_tstart'] arduino = GameLogic.Object['arduino'] if GameLogic.Object['bcstatus'] == False: if arduino is not None: gc.write_arduino_nonblocking(arduino, b'u') if settings.has_comedi and ncl.has_comedi: ncl.set_trig(GameLogic.Object['outfrch'], 1) GameLogic.Object['bcstatus'] = True else: if arduino is not None: gc.write_arduino_nonblocking(arduino, b'd') if settings.has_comedi and ncl.has_comedi: ncl.set_trig(GameLogic.Object['outfrch'], 0) GameLogic.Object['bcstatus'] = False if has_fw: frametimefw = gc.parse_frametimes(connfw) - GameLogic.Object['time0'] elif has_usb3: frametimefw = gc.parse_frametimes(connusb3) - GameLogic.Object['time0'] if conn2usb3 is not None: frametimefw2 = gc.parse_frametimes( conn2usb3) - GameLogic.Object['time0'] frametimefw2 = -frametimefw2 - 10 frametimefw = np.concatenate((frametimefw, frametimefw2)) else: frametimefw = np.array([ 0, ]) sys.stdout.write("%s\r" % (gu.time2str(dt))) GameLogic.Object['train_file'].write( np.array([dt, len(move[0]), len(move[2])], dtype=np.float32).tostring()) # 0:x1, 1:y1, 2:x2, 3:y2, 4:t1, 5:t2, 6:dt1, 7:dt2 GameLogic.Object['train_file'].flush() if len(move[0]): GameLogic.Object['train_file'].write( np.array([move[0].sum(), move[1].sum()], dtype=np.float32).tostring()) if len(move[2]): GameLogic.Object['train_file'].write( np.array([move[2].sum(), move[3].sum()], dtype=np.float32).tostring()) if len(move[0]) or len(move[2]): GameLogic.Object['train_file'].flush() GameLogic.Object['pos_file'].write( np.array([ xtranslate, ytranslate, zrotate, own.position[0], own.position[1], own.position[2], own.orientation[0][0], own.orientation[0][1], own.orientation[0][2], own.orientation[1][0], own.orientation[1][1], own.orientation[1][2], own.orientation[2][0], own.orientation[1][2], own.orientation[2][2], ], dtype=np.float64).tostring()) GameLogic.Object['pos_file'].flush()
# gl.f9 = gl.data[2] # if "/f10" in gl.data: # gl.f10 = gl.data[2] # Variables de la camara #if "/camx" in gl.data: # gl.camx = gl.data[2] #if "/camy" in gl.data: # gl.camy = gl.data[2] #if "/camz" in gl.data: # gl.camz = gl.data[2] #if "/cam" in gl.data: # gl.cam = gl.data[2] # controller = gl.getCurrentController() #owner = controller.owner #owner.localPosition = [0.3*gl.x, 0.3*gl.y, 2*gl.z] # Obtenemos los objetos de la escena scene = gl.getCurrentScene() #cubo = scene.objects["Cube"] #t1 = scene.objects["t1"] #t2 = scene.objects["t2"] #t3 = scene.objects["t3"] #t4 = scene.objects["t4"] #t5 = scene.objects["t5"] #t6 = scene.objects["t6"] #t7 = scene.objects["t7"]
def Rocket(): cont = logic.getCurrentController() obj = cont.owner scene = logic.getCurrentScene() motion = cont.actuators['Motion'] collision = cont.sensors['Collision'] dict = logic.globalDict level = dict['level'] rocket_collision = cont.sensors['Collision2'] def Init(): if not 'init' in obj: obj['init'] = 1 obj['hp'] = 1 if not 'speed' in obj: obj['speed'] = 0.0 if not 'dir' in obj: obj['dir'] = 0.0 obj['bounces'] = 0 obj['maxBounces'] = 1 obj['front'] = 0.62 obj['side'] = 0.21 obj['time'] = 0.0 def Update(): obj.worldPosition.z = 1 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) def BounceAngle(): if Bounce(obj['speed'], obj['front'], obj['side'], obj['side'], 'wall') != mathutils.Vector((0.0, 0.0, 0.0)): cont.activate(cont.actuators['Bounce']) if int(Bounce(obj['speed'], obj['front'], obj['side'], obj['side'], 'wall')[1]) == -1: #collision surface is on the X axis colAngle = math.atan2(Bounce(obj['speed'], obj['front'], obj['side'], obj['side'], 'wall')[0], Bounce(obj['speed'], obj['front'], obj['side'], obj['side'], 'wall')[1]) rocketAngle = math.atan2(obj.orientation[1][0], obj.orientation[1][1]) newAngle = -(rocketAngle - colAngle) ori = obj.orientation.to_euler() ori.z = newAngle obj.orientation = ori obj['bounces'] += 1 elif int(Bounce(obj['speed'], obj['front'], obj['side'], obj['side'], 'wall')[1]) == 1: #collision surface is on the X axis colAngle = math.atan2(Bounce(obj['speed'], obj['front'], obj['side'], obj['side'], 'wall')[0], Bounce(obj['speed'], obj['front'], obj['side'], obj['side'], 'wall')[1]) rocketAngle = math.atan2(obj.orientation[1][0], obj.orientation[1][1]) newAngle = math.pi - rocketAngle ori = obj.orientation.to_euler() ori.z = newAngle obj.orientation = ori obj['bounces'] += 1 elif int(Bounce(obj['speed'], obj['front'], obj['side'], obj['side'], 'wall')[0]) == 1: #collision surface is on the Y axis colAngle = math.atan2(Bounce(obj['speed'], obj['front'], obj['side'], obj['side'], 'wall')[0], Bounce(obj['speed'], obj['front'], obj['side'], obj['side'], 'wall')[1]) rocketAngle = math.atan2(obj.orientation[1][0], obj.orientation[1][1]) newAngle = -(math.pi/2) - (rocketAngle - colAngle) ori = obj.orientation.to_euler() ori.z = newAngle obj.orientation = ori obj['bounces'] += 1 elif int(Bounce(obj['speed'], obj['front'], obj['side'], obj['side'], 'wall')[0]) == -1: #collision surface is on the Y axis colAngle = math.atan2(Bounce(obj['speed'], obj['front'], obj['side'], obj['side'], 'wall')[0], Bounce(obj['speed'], obj['front'], obj['side'], obj['side'], 'wall')[1]) rocketAngle = math.atan2(obj.orientation[1][0], obj.orientation[1][1]) newAngle = (math.pi/2) - (rocketAngle - colAngle) ori = obj.orientation.to_euler() ori.z = newAngle obj.orientation = ori obj['bounces'] += 1 def Death(): if obj['bounces'] > obj['maxBounces']: obj.endObject() explosion = scene.addObject('Explosion',obj) logic.sendMessage('rocket_explosion', 'None') if rocket_collision.positive and obj['time'] < 30: dict['levelScore'] += 10 dict['rocket_kills'] += 1 scene.addObject('Plus_10',obj,40) scene.objects['Plus_10'].alignAxisToVect([1.0,0,0],0,1.0) if collision.positive: enemy = collision.hitObject if 'player' in enemy and obj['time'] < 5.0: pass else: if 'enemy' in enemy: logic.sendMessage('hit', 'None', str(enemy)) if 'hp' in enemy: enemy['hp'] -= 10 obj.endObject() explosion = scene.addObject('Explosion',obj) if obj['hp'] < 1: obj.endObject() if obj['time'] > 600: obj.endObject() obj['time'] += 1.0 def Message(): ori = obj.orientation[1].copy() ori.x *= -1 pos = obj.position toPos = pos + ori posL = obj.worldPosition + Scalar(obj.orientation[0], mathutils.Vector((-1,1,1)))*.5 posR = obj.worldPosition - Scalar(obj.orientation[0], mathutils.Vector((-1,1,1)))*.5 ray = obj.rayCast(toPos, obj, 10000, '', 1, 0) rayL = obj.rayCast(posL + Scalar(obj.orientation[1], mathutils.Vector((-1,1,1))), posL, 10000, '', 1, 0) rayR = obj.rayCast(posR + Scalar(obj.orientation[1], mathutils.Vector((-1,1,1))), posR, 10000, '', 1, 0) '''print("ray: ", ray[0]) print("rayL: ", rayL[0]) print("rayR: ", rayR[0]) print('*************************************')''' if ray[1] != None or rayL[1] != None or rayR[1] != None: hitPos = [ray[1][0], ray[1][1], ray[1][2]] hitPosL = [rayL[1][0], rayL[1][1], rayL[1][2]] hitPosR = [rayR[1][0], rayR[1][1], rayR[1][2]] #render.drawLine(obj.position, hitPos, [0.0, 1.0, 0.0]) #render.drawLine(posL, hitPosL, [0.0, 1.0, 0.0]) #render.drawLine(posR, hitPosR, [0.0, 1.0, 0.0]) if ray != None or rayL != None or rayR != None: if ray[0] != None: if Dist(ray[1], scene.objects['EvadeL'].worldPosition) > Dist(ray[1], scene.objects['EvadeR'].worldPosition): logic.sendMessage('hit_L', 'None', str(ray[0])) else: logic.sendMessage('hit_R', 'None', str(ray[0])) elif rayL[0] != None: if Dist(rayL[1], scene.objects['EvadeL'].worldPosition) > Dist(rayL[1], scene.objects['EvadeR'].worldPosition): logic.sendMessage('hit_L', 'None', str(rayL[0])) else: logic.sendMessage('hit_R', 'None', str(rayL[0])) elif rayR[0] != None: if Dist(rayR[1], scene.objects['EvadeL'].worldPosition) > Dist(rayR[1], scene.objects['EvadeR'].worldPosition): logic.sendMessage('hit_L', 'None', str(rayR[0])) else: logic.sendMessage('hit_R', 'None', str(rayR[0])) Init() Update() Message() BounceAngle() Death()
def wave_planar(wave_num=1, wave_rate_x=1, wave_rate_y=1, wave_height=1.0, scale_color=0, only_color=1, obj=None): """ Moves the vertices of the mesh around to give a waving effect. wave_num = how many waves to display on the mesh. Use a whole number >= 1 to increase the number of waves the mesh attempts to display. Note that you need enough detail on the mesh to accurately display the waves. Also note that numbers below 1 will display a part of a wave, and so will not loop correctly (when placed next to other instances of the same waving mesh). wave_rate = how many oscillations to make per second. wave_height = how high the waves should reach from the base Z value that the mesh starts with. scale_color = 0 means it will ignore the wave's vertex color channel. scale_color = 1 means it will scale the wave effect by the brightness of the wave's red vertex color. scale_color = 2 means it will scale the wave effect by the brightness of the wave's red vertex color binarily (on or off, if the channel's value is greater than 0.5). only_color = Only registers vertices to update if their red vertex color channel is greater than 0.5 obj = Object to influence. If None, then the object running this Python controller will be used. """ if obj is None: o = logic.getCurrentController().owner else: o = obj if not 'wave_planar_info' in o: o['wave_planar_info'] = {} o['wave_planar_info']['verts'] = {} o['wave_planar_info']['dimensions'] = get_dimensions( o, factor_in_scale=0)[0] for vert in get_all_vertices(o): if only_color: if vert.r > 0.5: o['wave_planar_info']['verts'][vert] = vert.getXYZ( ) # Only add the vertex to the list if it's red (cuts down processing) else: o['wave_planar_info']['verts'][vert] = vert.getXYZ() t = time.clock() d = o['wave_planar_info']['dimensions'].copy() d.magnitude /= 2 twrx = t * wave_rate_x twry = t * wave_rate_y if not scale_color: # Moving these if blocks outside of the vertex changes for vert in o['wave_planar_info']['verts']: osc_time_x = (twrx + ((vert.x / d.x) * wave_num)) * math.pi osc_time_y = (twry + ((vert.y / d.y) * wave_num)) * math.pi wave = ((math.sin(osc_time_x) + math.cos(osc_time_y) / 2) + 0.5) * wave_height vert.z = o['wave_planar_info']['verts'][vert].z + wave elif scale_color == 1: # Scale wave by vertex color for vert in o['wave_planar_info']['verts']: osc_time_x = (twrx + ((vert.x / d.x) * wave_num)) * math.pi osc_time_y = (twry + ((vert.y / d.y) * wave_num)) * math.pi wave = ((math.sin(osc_time_x) + math.cos(osc_time_y) / 2) + 0.5) * wave_height wave *= vert.r vert.z = o['wave_planar_info']['verts'][vert].z + wave else: # Scale wave by vertex color (binarily) for vert in o['wave_planar_info']['verts']: osc_time_x = (twrx + ((vert.x / d.x) * wave_num)) * math.pi osc_time_y = (twry + ((vert.y / d.y) * wave_num)) * math.pi wave = ((math.sin(osc_time_x) + math.cos(osc_time_y) / 2) + 0.5) * wave_height if vert.r < 0.5: wave = 0.0 vert.z = o['wave_planar_info']['verts'][vert].z + wave
# (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # 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 this program. If not, see <http://www.gnu.org/licenses/>. from bge import logic as g from bge import render as r import bgl import os cont = g.getCurrentController() own = cont.owner VertexShader = """ // Used later to determine the screen coordinates varying vec4 fragPos; // tangent, binormal, normal varying vec3 T, B, N; // Camera position and water point position (In the model space) varying vec3 viewPos, worldPos; // Vertex position in real and in view spaces varying vec3 pos, vPos; // World timer varying float timer; // Input Model matrix, used just to compute the water point position uniform mat4 ModelMatrix;
def Click(): cont = logic.getCurrentController() owner = cont.owner scene = logic.getCurrentScene() Cleared = 0 mines = 0 def setNeighborMine(x, y, z): #define area around mine lowX = max(x - 1, 1) highX = min(x + 2, 10) lowY = max(y - 1, 1) highY = min(y + 2, 10) lowZ = max(z - 1, 1) highZ = min(z + 2, 10) #loop through area around mine for i in range(lowX, highX): for j in range(lowY, highY): for k in range(lowZ, highZ): #the mine is not a neighbor to itself. if not (i == x and j == y and k == z): #count neighborMine 1 up for each neighbor Coord = str(i) + str(j) + str(k) o = scene.objects[str(Coord) + "Cube"] #if not neighbor is a mine. if not o['mine'] == True: o['neighborMine'] += 1 #o.color = (1, 0, 0, 1) def ColorSphere(o): if o['neighborMine'] == 1: o.color = (0, 1, 0, 1) #Green elif o['neighborMine'] == 2: o.color = (1, 1, 0, 1) #Yellow elif o['neighborMine'] == 3: o.color = (1, 0, 0, 1) #Red elif o['neighborMine'] == 4: o.color = (1, 0, 1, 1) #Magenta elif o['neighborMine'] == 5: o.color = (0, 0, 1, 1) #Blue else: o.color = (1, 1, 1, 1) #White def Init(): if not 'init' in owner: owner['init'] = 1 global Cleared global mines Cleared = 0 #loop through all spheres and set there mine status to False for i in range(1, 10): for j in range(1, 10): for k in range(1, 10): Coord = str(i) + str(j) + str(k) o = scene.objects[str(Coord) + "Cube"] o['mine'] = False o['neighborMine'] = 0 # set 10 random spheres to be mines. mines = 10 for i in range(1, 1 + mines): x = random.randrange(1, 10) y = random.randrange(1, 10) z = random.randrange(1, 10) o = scene.objects[str(x) + str(y) + str(z) + "Cube"] if o['mine'] == False: o['mine'] = True #o.color = (0, 0, 0, 1) i += 1 setNeighborMine(x, y, z) Init() def Clicked(x, y, z): global Cleared global mines Coord = str(x) + str(y) + str(z) o = scene.objects[str(Coord) + "Cube"] if o['Clicked'] == False: if o['mine'] == True: print("Game Over") #code to end game here! elif o['neighborMine'] != 0: o['Clicked'] = True Cleared += 1 ColorSphere(o) #o.color = (0, 1, 0, 1) if mines + Cleared == 729: print(str(Cleared) + " mines cleared! you won!!") else: print( str(Cleared) + " out of " + str(729 - mines) + " cleared, Still " + str(729 - mines - Cleared) + " to go") else: o['Clicked'] = True Cleared += 1 o.visible = False o.occlusion = False #define area around click lowX = max(x - 1, 1) highX = min(x + 2, 10) lowY = max(y - 1, 1) highY = min(y + 2, 10) lowZ = max(z - 1, 1) highZ = min(z + 2, 10) #loop through area around click for i in range(lowX, highX): for j in range(lowY, highY): for k in range(lowZ, highZ): #dont click itself if not (i == x and j == y and k == z): Coord = str(i) + str(j) + str(k) o = scene.objects[str(Coord) + "Cube"] if o['Clicked'] == False: Clicked(i, j, k) MouseOver = cont.sensors["MouseOver"] ob = MouseOver.hitObject MouseLeft = cont.sensors["MouseLeft"] if MouseLeft.positive and ob != None: loc = str(ob)[:3] x = loc[:1] y = loc[1:2] z = loc[2:3] Clicked(int(x), int(y), int(z)) #print("x=" +x+", y="+y+", z="+z) return (x, y, z)
def get_dimensions(object=None, roundit=3, offset=1, meshnum=0, factor_in_scale=1): """ Gets the dimensions of the object (what you see under dimensions in the properties window in the 3D menu). mesh = which mesh to use to get the object's dimensions. roundit = how far down to round the returned dimension values; set it to a negative number to not round the numbers off at all. offset = Whether or not to return the offset point of the dimensions (the center point); This negated (-offset, literally) is the origin point, generally. meshnum = The index of the mesh to use. Usually 0 is okay. factor_in_scale = If it should multiply the dimensions by the object's world scale. """ if object == None: object = logic.getCurrentController().owner s = object.worldScale mesh = object.meshes[meshnum] # print (dir(mesh)) verts = [[], [], []] originpos = [0, 0, 0] for mat in range(len(mesh.materials)): for v in range(mesh.getVertexArrayLength(mat)): vert = mesh.getVertex(mat, v) pos = vert.getXYZ() verts[0].append(pos[0]) verts[1].append(pos[1]) verts[2].append(pos[2]) verts[0].sort() verts[1].sort() verts[2].sort() if offset != 0: offsetpos = [ (verts[0][len(verts[0]) - 1] + verts[0][0]) / 2, (verts[1][len(verts[1]) - 1] + verts[1][0]) / 2, (verts[2][len(verts[2]) - 1] + verts[2][0]) / 2, ] size = [(verts[0][len(verts[0]) - 1] - verts[0][0]), (verts[1][len(verts[0]) - 1] - verts[1][0]), (verts[2][len(verts[0]) - 1] - verts[2][0])] if factor_in_scale: size = [size[0] * s[0], size[1] * s[1], size[2] * s[2]] if roundit >= 0: size = [ round(size[0], roundit), round(size[1], roundit), round(size[2], roundit), ] if offset: return (mathutils.Vector(size), mathutils.Vector(offsetpos)) else: return (mathutils.Vector(size), None)
def get_path_to(self, ending_point, starting_point=None, max_check_num=1000, cost_coefficient=None): if cost_coefficient is None: cost_coefficient = [1 for x in range(self.cost_num)] if starting_point is None: starting_point = logic.getCurrentController( ).owner.worldPosition.copy() goal = self.get_closest_node(ending_point) starting_node = self.get_closest_node(starting_point) def get_f_score(node): costs = [x * y for x, y in zip(node.costs, cost_coefficient)] return (starting_node.obj.position - node.obj.position ).magnitude + (node.obj.position - goal.obj.position).magnitude + sum(costs) if not goal: print( "ERROR: GOAL POSITION CANNOT BE REACHED FROM ANY NODE ON MAP.") return if not starting_node: print( "ERROR: STARTING NODE CANNOT BE REACHED FROM ANY NODE ON MAP.") return open_list = [starting_node] closed_list = [] exit_loop = False for x in range(max_check_num): open_list.sort(key=get_f_score) current_node = open_list.pop(0) closed_list.append(current_node) for neighbor in current_node.neighbors: if neighbor in closed_list: continue if neighbor not in open_list: neighbor.parent = current_node open_list.append(neighbor) if neighbor == goal: exit_loop = True # A path has been found break if exit_loop: break path = [] target_square = goal for x in range(1000): path.append(target_square) if target_square == starting_node: break target_square = target_square.parent path.reverse() # Go from the start to the goal if len(path): return Path(path) # Create a path object else: print("No path found")
from bge import logic cont = logic.getCurrentController() own = cont.owner own['Music'] = True print(own.actuators)
def main(): scene = logic.getCurrentScene() controller = logic.getCurrentController() obj = controller.owner if('my_xbox_controller' not in controller.owner.sensors): print(obj.name, 'only has these sensors attached', controller.owner.sensors) return # assumes a keyboard sensor has been created named 'my_keyboard' with use_pulse_true_level = True xbc = controller.owner.sensors['my_xbox_controller'] # make sure if len(xbc.axisValues) is not 6: print('xbc only has these axes: ', xbc.axisValues) return #handle the joystick and trigger axes left_x, left_y, left_trigger, right_x, right_y, right_trigger = ignore_deadzone(6000, xbc.axisValues) print(left_x, left_y, left_trigger, right_x, right_y, right_trigger , left_y/VALUE_MAX) # set the rotation with a damper from the right stick. args = ([x,y,z], use_local_coordinates]) obj.applyRotation([0, 0, -right_x/VALUE_MAX * 0.02], True) #set the movement with the left stick, args = ([x,y,z], use_local_coordinates]) obj.applyMovement([0, -left_y/VALUE_MAX * 0.08, 0], True) #handle the dpad / hat for dpad in xbc.hatValues: if dpad is 0: pass #the default state elif dpad is 1: print('N') elif dpad is 2: print('E') elif dpad is 3: print('NE') elif dpad is 4: print('S') elif dpad is 6: print('SE') elif dpad is 8: print('W') elif dpad is 9: print('NW') elif dpad is 12: print('SW') else: print(dpad, 'is not yet assigned') #handle the buttons for button in xbc.getButtonActiveList(): if button is 0: print('A') if obj.position.z <= 50: obj.position.z += 0.1 elif button is 1: print('B') elif button is 2: print('X') elif button is 3: print('Y') elif button is 4: print('LB') elif button is 5: print('RB') elif button is 6: print('BACK') elif button is 7: print('START') else: print(button, 'is not yet assigned') ''' for button down use logic.KX_INPUT_JUST_ACTIVATED (resolves to 1) for button hold use logic.KX_INPUT_ACTIVE (resolves to 2) for button up use logic.KX_INPUT_JUST_RELEASED (resolves to 3) ''' if(xbc.status == logic.KX_INPUT_JUST_ACTIVATED): print('use this section to do things only when a button is first pressed') if(xbc.status == logic.KX_INPUT_ACTIVE): print('use this section to do things only when a button is held') if(xbc.status == logic.KX_INPUT_JUST_RELEASED): print('use this section to do things only when a button is released')
import VideoTexture from bge import logic as GameLogic contr = GameLogic.getCurrentController() obj = contr.owner # -- Check if the "video" property has been defined in the object if 'video' not in obj: #-- Get the material that is using our texture #matID = VideoTexture.materialID(obj, 'MAa_video2014-02-20-17-41-16-163') # -- Create the video texture # GameLogic.video = VideoTexture.Texture(obj, matID) # Suppose 1st material is the video one obj['video'] = VideoTexture.Texture(obj, 0) # -- Get the path to the video file from the 'video_path' object property movie = GameLogic.expandPath(obj['video_path']) # -- Load the file obj['video'].source = VideoTexture.VideoFFmpeg(movie) # play video in loop obj['video'].source.repeat = -1 # -- play the video obj['video_was_playing'] = False # obj['video'].source.play()
def play(self, anim_name, reset_subimage_on_change=True): if not anim_name in self.anim_dict: print("ERROR: SpriteMap owner " + self.obj.name + " has no animation named " + anim_name + ".") return False elif len(self.anim_dict[anim_name]['animation']) < 2: print("ERROR: SpriteMap owner " + self.obj.name + "'s animation " + anim_name + " does not contain data " "for at least one frame of " "animation.") return False self.current_animation = anim_name if self.current_animation != self.prev_animation: self.on_animation_change(self, self.current_animation, self.prev_animation) # Callback if reset_subimage_on_change: self.subimage = 1.0 if self.adjust_by_sensor_frequency: freq = logic.getCurrentController().sensors[0].frequency + 1 else: freq = 1 if self.fps_lock: scene_fps = logic.getLogicTicRate() else: scene_fps = logic.getAverageFrameRate() if scene_fps == 0.0: scene_fps = logic.getLogicTicRate() if anim_name and anim_name in self.anim_dict: anim = self.anim_dict[anim_name]['animation'] anim_fps = self.anim_dict[anim_name]['fps'] target_fps = anim_fps / scene_fps if len( anim ) > 2: # Don't advance if there's only one cell to the animation if target_fps != 0.0: self.subimage += round(target_fps, 2) * freq subi = round(self.subimage, 4) if (self.subimage <= len(anim) - 2 and anim_fps > 0) or (self.subimage > 1.0 and anim_fps < 0): self.is_playing = True if self.anim_dict[anim_name][ 'loop']: # The animation is to be looped fin = 0 if len(anim) >= 2: while math.floor(subi) > len(anim) - 1: subi -= len(anim) - 1 fin = 1 while math.floor(subi) < 1.0: subi += len(anim) - 1 fin = 1 if fin: self.on_animation_finished( self) # Animation's finished because it's looping self.is_playing = True else: # No loop if subi >= len(anim) - 1 or subi < 1.0: if self.is_playing: self.on_animation_finished( self ) # Animation's finished because it's at the end of a # non-looping animation if len(anim) >= 2: subi = min(max(subi, 1.0), len(anim) - 1) else: subi = 1.0 self.is_playing = False if math.floor(subi) != math.floor(self.prev_subimage): self.on_subimage_change(self, math.floor(subi), math.floor(self.prev_subimage)) # Callback for subimage change self.subimage = subi else: print("ERROR: ANIMATION NAME " + anim_name + " NOT IN SPRITEMAP OR NOT STRING.") self.prev_animation = self.current_animation self.prev_subimage = self.subimage if self.obj.invalid: # You did something that killed the object; STOP PRODUCTION! print("ERROR: SPRITE MAP OPERATING ON NON-EXISTENT OBJECT!!!") return False return True
import bge.logic as logic import time import math import FSNObjects import copy from scripts.abstract.RaceState import RaceState scene = logic.getCurrentScene() owner = logic.getCurrentController().owner #logic.globalDict["playerQuad"] = owner flowState = logic.flowState def main(): try: logic.lastGhostUpdate except: logic.lastGhostUpdate = time.time() print("FOOOO BAR!") if abs(time.time() - logic.lastGhostUpdate) >= (1.0 / 120): #if True: logic.lastGhostUpdate = time.time() if (flowState.getGameMode() == flowState.GAME_MODE_SINGLE_PLAYER): lap = logic.flowState.getRaceState().getChannelLapCount(5658) if lap < 0: logic.ghosts = [] else: if len(logic.ghosts) - 1 < lap: ghostObject = addGhostQuad() ghostObject["lap"] = lap logic.ghosts.append(createGhostData(owner, ghostObject))
def Click(): #Diese Definition wird im Spiel aufgerufen cont = logic.getCurrentController() owner = cont.owner scene = logic.getCurrentScene() Cleared = 0 mines = 0 MaxX = 0 MaxY = 0 contr = bge.logic.getCurrentController() sens = contr.sensors['Message'] body = sens.subjects def setNeighborMine(x, y): #Platz neben der ausgewählten Mine festlegen lowX = max(x - 2, 1) highX = min(x + 2, 11) lowY = max(y - 2, 1) highY = min(y + 2, 11) for i in range(lowX, highX): for j in range(lowY, highY): if not (i == x and j == y): #Damit sich das Feld nicht selber mitzählt Coord = str(i) + ";" + str(j) o = scene.objects[str(Coord)] if not o['mine'] == True: #falls das ausgewählte Feld keine Mine ist... o['neighborMine'] += 1 def ChangePlate(o, x, y): object = str(o) if o['neighborMine'] == 1: #Das Feld hat eine Mine in der Nähe logic.sendMessage("1", "shot", object) elif o['neighborMine'] == 2: #Das Feld hat zwei Minen in der Nähe logic.sendMessage("2", "shot", object) elif o['neighborMine'] == 3: #Das Feld hat drei Minen in der Nähe logic.sendMessage("3", "shot", object) elif o['neighborMine'] == 4: #Das Feld hat vier Minen in der Nähe logic.sendMessage("4", "shot", object) elif o['neighborMine'] == 5: #Das Feld hat fünf Minen in der Nähe logic.sendMessage("5", "shot", object) elif o['neighborMine'] == 6: #Das Feld hat fünf Minen in der Nähe logic.sendMessage("6", "shot", object) else: #Das Feld hat keine Mine in der Nähe logic.sendMessage("0", "shot", object) minenzahl = str(o['neighborMine']) print("Unter der Platte: " + object + " sind/ist " + minenzahl + " Mine/n.") scene = bge.logic.getCurrentScene() cont = bge.logic.getCurrentController() own = cont.owner obj = scene.objects x = str(x) y = str(y) xy = (x + ";" + y) objdel = obj[xy] objdel.endObject() #Ausblenden des Objektes def Init(): if not 'init' in owner: owner['init'] = 1 global MaxX global MaxY global Cleared global mines Cleared = 0 MaxX = 10 + 1 MaxY = 10 + 1 #Alle Felder auf definieren for i in range(1, MaxX): for j in range(1, MaxY): Coord = str(i) + ";" + str(j) o = scene.objects[str(Coord)] o['mine'] = False o['neighborMine'] = 0 o['Clicked'] = False #10 Minen zufällig setzen mines = 10 for i in range(1, 1 + mines): x = random.randrange(1, MaxX) y = random.randrange(1, MaxY) o = scene.objects[str(x) + ";" + str(y)] if o['mine'] == False: o['mine'] = True i += 1 setNeighborMine(x, y) Init() #------------------ Start ------------------ def Clicked(x, y): global Cleared global mines Coord = str(x) + ";" + str(y) o = scene.objects[str(Coord)] if o['Clicked'] == False: #Gucken ob das Feld schon einmal geöffnet wurde if o['mine'] == True: #falls es noch nicht geöffnet wurde und eine Mine unter der Platte liegt print("Game Over") #Ende vom Spiel und Szenenwechsel scene.replace('GameOver') #zum GameOver Screen elif o['neighborMine'] != 0: #Wenn es ein benachbartes Feld gibt... o['Clicked'] = True Cleared += 1 ChangePlate(o, x, y) if mines + Cleared == 100: #Für den Counter und ob das Feld gelöst wurde print(str(Cleared) + " mines cleared! you won!!") else: print( str(Cleared) + " out of " + str(100 - mines) + " cleared, Still " + str(100 - mines - Cleared) + " to go") else: #Wenn das Feld noch nicht geöffnet wurde und es o['Clicked'] = True Cleared += 1 lowX = max(x - 1, 1) highX = min(x + 2, 10) lowY = max(y - 1, 1) highY = min(y + 2, 10) for i in range(lowX, highX): for j in range(lowY, highY): if not (i == x and j == y): Coord = str(i) + ";" + str(j) o = scene.objects[str(Coord)] if o['Clicked'] == False: Clicked( i, j) #Clicked für Nachbarplatten ausführen if body: #Wenn die Message, die das Script aufgerufen hat, etwas enthält... if not body[0] == "shot": #dass nicht "shot" ist #print ("Platten Name: ",body[0],"!") body = body[0].split(";") #print (body) x = body[0] y = body[1] #print ("x: ",x," y: ",y) Clicked(int(x), int(y)) #dann führe Clicked aus.
def Init(): cont = logic.getCurrentController() obj = cont.owner if not 'init' in obj: obj['init'] = 1 obj['var'] = 0
def __init__(self, stretch=True, spacing=3, reverse=False, vertex_axis="y", update_on_moving_only=False, trail_target_obj=None, trail_obj=None): """ Creates a Trail object. Trail objects influence the vertices of their mesh to react to a trail owner object's movements. Think of a light trail, or a cape. When the owner moves or jumps or whatever, the trail reacts accordingly. :param stretch: Bool - If the vertices of the trail should stretch and stay in their position until movement. Think of the difference between a trail from a light cycle from Tron, and a cape. The trail stretches (it starts with a "nub", and then gets longer as the cycle drives along). The cape, on the other hand, doesn't stretch (it's always the same length). :param spacing: Int - The number of frames between the movement and the vertex update (or the vertex update and the following vertex update). Higher spacing = more delayed reaction on the trail vertices, which means a more "rough" trail, and a longer trail when stretch is on. Lower spacing = less of a pronounced reaction on the trail vertices, and a smoother overall trail. Also, a shorter trail when stretch is on. :param reverse: Bool - If the trail should reverse it's orientation based on the movement of the trail owner. E.G. If reverse is on, and a sword swings left, its trail swings left too. :param vertex_axis: Str - The axis that the vertices of the trail move on, going away from the origin of the trail object's mesh. Should be "x", "y", or "z". :param update_on_moving_only: Bool - If the trail should update only when the object's moving. :param trail_target_obj: KX_GameObject reference - The object that influences the trail. The trail object will snap to the trail target object's position and orientation. If left to None, this will default to the trail object's parent. Although, to get the best results, the trail shouldn't be parented to its owner. See the example blend file. :param trail_obj: The object to manipulate to achieve a trail. If left to None, will default to the "calling" object. :return: Trail """ if not trail_obj: o = logic.getCurrentController().owner else: o = trail_obj assert isinstance(o, types.KX_GameObject) self.obj = o sce = self.obj.scene #if trail_mesh is None: mesh = self.obj.meshes[0] #else: # mesh = trail_mesh self.trail_axis = vertex_axis self.trail_verts = [] for mat in range(mesh.numMaterials): for v in range(mesh.getVertexArrayLength(mat)): vert = mesh.getVertex(mat, v) self.trail_verts.append(vert) # Get all verts self.vert_offsets = {} for vert in self.trail_verts: self.vert_offsets[vert] = vert.XYZ vert_pairs = {} for vert in self.trail_verts: if self.trail_axis.lower() == 'x': vert_y = round( vert.x, 2 ) # Round it off to ensure that verts that have very close X positions # (i.e. 0 and 0.01) get grouped together elif self.trail_axis.lower() == 'y': vert_y = round(vert.y, 2) else: vert_y = round(vert.z, 2) if vert_y not in vert_pairs: vert_pairs[vert_y] = [] vert_pairs[vert_y].append( vert) # Get the verts paired with their positions self.vert_pairs = [] for vp in vert_pairs: self.vert_pairs.append([vp, vert_pairs[vp]]) self.vert_pairs = sorted(self.vert_pairs, key=lambda x: x[0], reverse=True) self.target_positions = [] self.trail_stretch = stretch # Stretch the trail to 'fit' the movements self.trail_spacing = spacing # Number of frames between each edge in the trail self.trail_reverse = reverse # If the bending of the trail should be reversed self.update_on_moving_only = update_on_moving_only # Update the trail only when moving self.trail_counter = spacing # Number of frames between each 'keyframe' if not trail_target_obj: self.target = self.obj.parent else: self.target = trail_target_obj self.target_past_pos = self.target.worldPosition.copy() self.target_past_ori = self.target.worldOrientation.copy() for x in range(len(self.vert_pairs) * self.trail_spacing): self.target_positions.insert(0, [ self.target.worldPosition.copy(), self.target.worldOrientation.copy() ])
def add_light(light_type=LT_POINT, time=0, priority=0): """ Spawns a light that was pre-placed in a hidden layer. Note that the light must have a property present in it named "DynLight". It must be set to "Point", "Sun", "Hemi", or "Spot" for it to spawn in correctly. time = how long the light should stick around in frames priority = what priority the light should spawn with. Higher priorities will delete and re-create (overwrite, if you will) existing lights if not enough pre-made lights are present. Basically, priority allows you to spawn lights with low priority at non important places, like spawn 10 torches with lights at priority 0, and then spawn a light for the player with a priority of 1. Since it has a higher priority, the player's light will spawn, and one of the torches' lights will be deleted. """ sce = logic.getCurrentScene() obj = logic.getCurrentController().owner if not hasattr(logic, 'lights_used'): logic.lights_used = { # 'Point':{}, # 'Sun':{}, #'Hemi':{}, #'Spot':{}, } # Create a mapping of lamps with their types to spawners # for lt in logic.lights_used: for l in [ l for l in sce.objectsInactive if "DynLight" in l ]: # Loop through the lamps that have the string "Dyn" + the type in their name (i.e. Point lamps named "Point", "Point.001", etc.) if not l['DynLight'] in logic.lights_used: logic.lights_used[l['DynLight']] = {} logic.lights_used[l['DynLight']][l.name.lower()] = { 'reference': None, 'priority': 0 } # And set their "used" status to 0 if light_type == LT_POINT: lt = 'point' elif light_type == LT_SPOT: lt = 'spot' elif light_type == LT_SUN: lt = 'sun' else: lt = 'hemi' for l in logic.lights_used[lt]: # Then loop through all of the lamps light_dict = logic.lights_used[lt][l] if light_dict[ 'reference'] == None: # And when you find a lamp that hasn't been used light = sce.addObject(l, obj, time) # Create that lamp, light_dict['priority'] = priority light_dict[ 'reference'] = light # And set it to be used (mitts off to all other spawners until it's destroyed) return light # And then break out of the loop, returning the spawned light else: if light_dict['reference'].invalid: # If the lamp you've "found" is used, but doesn't exist or has been deleted, or has a lower priority # than intended, light = sce.addObject(l, obj, time) light_dict[ 'reference'] = light # Then re-use that one, rather than looking for another lamp light_dict['priority'] = priority return light # And then break out of the loop, returning the spawned light light_keys = list(logic.lights_used[lt].keys()) lights_pri = sorted(light_keys, key=lambda light_in_use: logic.lights_used[lt][ light_in_use]['priority']) for l in lights_pri: light_dict = logic.lights_used[lt][l] if light_dict['priority'] < priority: light_dict['reference'].endObject() light = sce.addObject(l, obj, time) light_dict['reference'] = light light_dict['priority'] = priority return light return None
def getOwner(): controller = logic.getCurrentController() object = controller.owner return object
return True return False def msg(*args): message = "" for i in args: message += str(i) if DEBUG_MESSAGES: print('[MouseMove] ' + message) ################################# # Module Execution entry point def main(): cont = logic.getCurrentController() own = cont.owner if 'mmc.core' not in own: own['mmc.core'] = Core(cont) else: own['mmc.core'].module() # Non-Module Execution entry point (Script) if logic.getCurrentController().mode == 0: main()
import GameLogic from bge import logic scene = logic.getCurrentScene() # Get the current game scene cont = logic.getCurrentController() # Get the controller executing this script obj = cont.owner # Get this object if not "Scattered" in obj: obj["Scattered"] = True locations = {} locations["level1"] = [ [[-76.9175,5.2857,-0.6],[0,0,0],'ZombieMaster'], [[-72.948,5.6023,-0.6],[0,0,0],'ZombieMaster'], [[1,1,-0.6],[0,0,0],'ZombieMaster'], [[-44.7737,-75.1513,-0.6],[0,0,0],'ZombieMaster'], [[58.2994,50.9079,-0.6],[0,0,0],'ZombieMaster'], [[29.8511,162.6793,-0.6],[0,0,0],'ZombieMaster'], [[79.7546,-70.7662,-0.6],[0,0,0],'ZombieMaster'], [[-18.8812,-99.864807,-0.6],[0,0,0],'ZombieMaster'], [[-76.0846,-87.9987,-0.6],[0,0,0],'ZombieMaster'], [[-85.4402,-95.4832,-0.6],[0,0,0],'ZombieMaster'], [[118.7712,161.3121,-0.6],[0,0,0],'ZombieMaster'], [[126.5892,136.8092,-0.6],[0,0,0],'ZombieMaster'], [[124.5881,155.7543,-0.6],[0,0,0],'ZombieMaster'], [[77.5589,-42.5318,-0.6],[0,0,0],'ZombieMaster'], [[-6.8085,165.5291,-0.6],[0,0,0],'ZombieMaster'], [[-91,68.2365,-0.6],[0,0,0],'ZombieMaster'], [[92.7706,60.6761,-0.6],[0,0,0],'ZombieMaster'], [[-64.1551,-51.9408,-0.6],[0,0,0],'ZombieMaster'], [[2,2,0],[0,0,0],'jerryCan'], [[-39.7,-32.9,0],[0,0,0],'jerryCan'],
def gui(): global markerIgnition global TimerSpeedTmOut global markerIgnitionStartTime global txtTimerSpeedTmOut cont = logic.getCurrentController() o = cont.owner if "init" not in o: markerIgnition = False #HG1 markerIgnitionStartTime = 0.0 o["C"] = compz.Compz() # THEME fuer die GUI: btnStyle = compz.Style( name="button", stylesPath=logic.expandPath("//Compz_Theme/default/")) panelStyle = compz.Style( name="panel", stylesPath=logic.expandPath("//Compz_Theme/default/")) listStyle = compz.Style( name="list", stylesPath=logic.expandPath("//Compz_Theme/default/")) entryStyle = compz.Style( name="entry", stylesPath=logic.expandPath("//Compz_Theme/default/")) sliderStyle = compz.Style( name="slider", stylesPath=logic.expandPath("//Compz_Theme/default/")) cbStyle = compz.Style( name="checkbox", stylesPath=logic.expandPath("//Compz_Theme/default/")) radioStyle = compz.Style( name="radio", stylesPath=logic.expandPath("//Compz_Theme/default/")) # ----------------------- # FUNCTION 'clickIgnition' - markerIgnition # ----------------------- def clickIgnition(sender): # , marker = 0 global markerIgnition #HG1 global markerIgnitionStartTime #Eric lst1.selectedIndex = 1 if markerIgnition: #markerIgnitionStartTime = o['TimerSpeedTmOut'] logic.getCurrentScene().objects["MeshPhase0"].color = [ 1.0, 0.45, 0.80, 1.0 ] #color ON valueSliderSpdThr.value = 0 btnIgnition.text = 'Ignition: OFF' markerIgnition = False else: o['TimerSpeedTmOut'] = 0.0 #new #markerIgnitionStartTime = o['TimerSpeedTmOut'] logic.getCurrentScene().objects["MeshPhase0"].color = [ 0.55, 0.87, 1.0, 1.0 ] #color OFF valueSliderSpdThr.value = 0 btnIgnition.text = 'Ignition: ON' markerIgnition = True markerIgnitionStartTime = o['TimerSpeedTmOut'] # ----------------------- # FUNCTION 'clickSpeedPlausibility' # ----------------------- def clickSpeedPlausibility(sender): global markerSpeedPlausibility print('sender: ' + str(sender)) print("Clicked on button markerSpeedPlausibility " + sender.text) print('markerSpeedPlausibility: ' + str(markerSpeedPlausibility)) text.text = sender.text if markerSpeedPlausibility == 'VALID': logic.getCurrentScene().objects["MeshPhase0"].color = [ 1.0, 0.45, 0.80, 1.0 ] #color ON markerSpeedPlausibility = 'VINALID' elif markerSpeedPlausibility == 'VINALID': logic.getCurrentScene().objects["MeshPhase0"].color = [ 0.55, 0.87, 1.0, 1.0 ] #color OFF markerSpeedPlausibility = 'VALID' print('markerSpeedPlausibility nach if: ' + str(markerIgnition)) # ----------------------- # FUNCTION 'clickActualClass' # ----------------------- def clickActualClass(sender): global markerActualClass # ----------------------- # FUNCTION 'valueSliderChange' - SpeedThresh # ----------------------- def valueSliderChangeSpeedThresh(sender): global intSpeed global markerSpeedThresh intSpeed = sender.value print('....................... sender: ' + str(sender)) print("Clicked on button valueSliderChange " + str(sender.value)) txtVehicleSpeed.text = "%.0f" % (intSpeed * 100) + ' km/h' # ----------------------- # FUNCTION 'valueSliderChange' - SpeedTmOutThresh # ----------------------- def valueSliderChangeSpeedTmOutThresh(sender): global intSpeedTmOut global markertxtSpeedTmOutThresh intSpeedTmOutThresh = sender.value print('....................... sender: ' + str(sender)) print("Clicked on button valueSliderChange " + str(sender.value)) txtSpeedTmOutThresh.text = "%.0f" % (intSpeedTmOutThresh * 100) + ' seconds' # ----------------------- # FUNCTION 'valueLst1Index' - ??? --------------------------------------------------------------- --------------------------------------------------------------- # ----------------------- def valueLst1Index(sender): print("Clicked lst1.item " + str(sender.items[2])) print("------------------------ sender.selectedIndex: " + str(sender.selectedIndex)) # ---------------------------------------------------------------- # linkes Panel - pan - # ---------------------------------------------------------------- pan = compz.Panel(panelStyle) pan.position = [5, 5] pan.width = 150 pan.height = 335 o["C"].addComp(pan) text = compz.Entry(style=entryStyle) # ------------------------------------------------------------------------------------------------------------------------------ # GUIb Layout block # ------------------------------------------------------------------------------------------------------------------------------ # ADD label lbl = pan.addComp(compz.Label("Input:")) lbl.row = 1 lbl.textAlignment = compz.TEXT_ALIGN_LEFT # ADD Buttons fuer Teile des linkes Panel: btnIgnition = compz.Button("Ignition: OFF", btnStyle) btnIgnition.events.set(compz.EV_MOUSE_CLICK, clickIgnition) btnIgnition.icon = compz.Icon( logic.expandPath("//Compz_Theme/control_play.png")) pan.addComp(btnIgnition) # ADD Buttons fuer Teile des linkes Panel: cbSpeedPlausibility = compz.CheckBox("SpeedPlausible", cbStyle) cbSpeedPlausibility.events.set(compz.EV_CHECK_STATE_CHANGED, clickSpeedPlausibility) pan.addComp(cbSpeedPlausibility) # ADD Buttons fuer Teile des linkes Panel: cbActualClass = compz.CheckBox("Occupied", cbStyle) cbActualClass.events.set(compz.EV_CHECK_STATE_CHANGED, clickActualClass) pan.addComp(cbActualClass) # ADD label lbl = pan.addComp(compz.Label("Limit Vehicle Speed:")) #lbl.row = 1 lbl.textAlignment = compz.TEXT_ALIGN_LEFT # Textfield: txtVehicleSpeed = compz.Entry(style=entryStyle) txtVehicleSpeed.readOnly = True pan.addComp(txtVehicleSpeed) valueSliderSpdThr = pan.addComp(compz.Slider(style=sliderStyle)) valueSliderSpdThr.precision = 2 valueSliderSpdThr.events.set(compz.EV_SLIDER_VALUE_CHANGE, valueSliderChangeSpeedThresh) # ADD label lbl = pan.addComp(compz.Label("Limit: SpeedTmOut")) #lbl.row = 1 lbl.textAlignment = compz.TEXT_ALIGN_LEFT # ADD Textfield: txtSpeedTmOutThresh = compz.Entry(style=entryStyle) txtSpeedTmOutThresh.readOnly = True pan.addComp(txtSpeedTmOutThresh) valueSliderSpdTmOutThr = pan.addComp(compz.Slider(style=sliderStyle)) valueSliderSpdTmOutThr.precision = 2 valueSliderSpdTmOutThr.events.set(compz.EV_SLIDER_VALUE_CHANGE, valueSliderChangeSpeedTmOutThresh) # ---------------------------------------------------------------- # rechtes Panel - gpan - : # ---------------------------------------------------------------- gpan = compz.Panel(panelStyle) gpan.position = [200, 5] # [1190, 5] gpan.width = 160 gpan.height = 335 #gpan.layout = compz.GridLayout() o["C"].addComp(gpan) # ADD label lbl0 = gpan.addComp(compz.Label("Output:")) #lbl0.row = 0 lbl0.textAlignment = compz.TEXT_ALIGN_LEFT # ADD Label: Textfield - SpeedTmOut: lblO1 = gpan.addComp(compz.Label("TimerSpeedTmOut:")) #lbl.row = 4 lblO1.textAlignment = compz.TEXT_ALIGN_LEFT # ADD Textfield - SpeedTmOut: txtTimerSpeedTmOut = compz.Entry(style=entryStyle) txtTimerSpeedTmOut.readOnly = True gpan.addComp(txtTimerSpeedTmOut) # ADD List lbl1 = gpan.addComp(compz.Label("Buffer Phase:")) #lbl1.row = 1 lbl1.textAlignment = compz.TEXT_ALIGN_LEFT lst1 = gpan.addComp(compz.List(listStyle)) #lst1.width = 60 lst1.height = 60 #lst1.rowSpan = 9 #lst1.columnSpan = 20 #lst1.row = 3 lst1.items.append("Phase 0") lst1.items.append("Phase 1") lst1.items.append("Phase 2") o["init"] = 1 else: o["C"].update() if markerIgnition: #HG1 #txtTimerSpeedTmOut.text = "%3.0f" % (o['TimerSpeedTmOut'] - markerIgnitionStartTime ) + ' seconds' #HG1 txtTimerSpeedTmOut.text = "%3.0f" % ( o['TimerSpeedTmOut']) + ' seconds' #HG1 new print('init - else - markerIgnitionStartTime: ' + str(markerIgnitionStartTime))
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)