def __init__(self): self.main = logic.getSceneList()[0].objects["Main"] # Setup player self.player = Hero([8, 2, 0]) # Setup enemies locs = ((-8, 7, 0), (-8, 2, 0), (-8, -3, 0)) self.enemies = [] for i in locs: enemy = Enemy(i) enemy.enemy_target = self.player self.enemies.append(enemy) # Give the player something to shoot at self.player.enemy_target = self.enemies[0] # Input with open(logic.expandPath('//input.conf')) as f: self.inputs = input.InputSystem(f, logic.expandPath('//joyconfs')) # UI self.ui = bgui_bge_utils.System() self.ui.load_layout(CombatLayout, self) self.prev_time = time.time()
def load(self, styleFile): """ Loads a style from a JSON file Raises: Exception: If no texture regions are present in the style file. """ sfile = {} with open(styleFile) as fp: sfile = json.load(fp) if "font" in sfile: self.font = Font(logic.expandPath(sfile["font"])) else: self.font = Font() if "text_color" in sfile: self.text_color = sfile["text_color"] if "disabled_text_color" in sfile: self.disabled_text_color = sfile["disabled_text_color"] if "regions" not in sfile or "image" not in sfile: raise Exception("Invalid Style file.") img = ImageTexture(logic.expandPath(sfile["image"])) for name, np in sfile["regions"].items(): if name in self.textures: continue region = np[0] lp, rp, bp, tp = np[1] self.textures[name] = NinePatch(img, lp, rp, bp, tp, region)
def getLocalDirectory(): """ Returns the directory where local data can be stored. By default the same directory than the game. If there is no write acces then a directory inside the user folder. """ global _local_data_directory if _local_data_directory == None: game_name = os.path.normpath(logic.expandPath('//..//')) game_name = game_name[game_name.rfind(os.sep)+len(os.sep):] try: path = logic.expandPath("//../") f = open(path + "config.txt", 'a') _local_data_directory = path except PermissionError: from sys import platform as _platform if _platform == "linux" or _platform == "linux2" or _platform == "darwin": path = os.getenv("HOME") + "/.local/share/" + game_name + '/' elif _platform == "win32" or _platform == "cygwin": import ctypes.wintypes CSIDL_PERSONAL = 5 # My Documents SHGFP_TYPE_CURRENT = 0 # Get current, not default value buf= ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH) ctypes.windll.shell32.SHGetFolderPathW(None, CSIDL_PERSONAL, None, SHGFP_TYPE_CURRENT, buf) path = buf.value + os.sep + "My Games" + os.sep _local_data_directory = path + game_name + os.sep else: f.close() if os.path.isdir(_local_data_directory): return _local_data_directory else: path = _local_data_directory os.makedirs(path) import shutil shutil.copyfile(logic.expandPath("//../config.txt"), path + "config.txt") return path
def __init__(self, obj=None): self.obj = obj self.callback = None self.true_start_file = None self.frame = 0 self.speaker = None if obj == None: logic.LibLoad(logic.expandPath("//core/misc/screen.blend"), 'Scene') obj = self.obj = logic.getCurrentScene().objects["__CORE__Screen"] obj.visible = False try: t = obj.meshes[0].materials[0].textures[0] if t == None: raise Exception except Exception: try: logic.LibLoad(logic.expandPath("//core/misc/screen.blend"), 'Mesh') obj.replaceMesh("__CORE__Screen") except Exception: utils.debug( "Video not set, " + obj.name + " object is not a screen. Make sure it has a texture to an image file. " ) self.play = self.no_play self.replaceTexture = self.no_replaceTexture
def __init__(self, ob): self.obj = ob self.last_update = self.start_time = time.time() self.end_time = None print("Attaching player controller to", ob) self.engine_sound = aud.device().play(aud.Factory(logic.expandPath("//../sounds/engine.ogg")).loop(-1)) self.bg_music = aud.device().play(aud.Factory(logic.expandPath("//../sounds/Circus Waltz FX.ogg")).loop(-1))
def main(): obj = logic.getCurrentController().owner #Creating the core game class obj["myGame"] = Game(logic.expandPath("//tiles.caconf"), logic.expandPath("//map.camap"), logic.expandPath("//defaultStack.caconf")) #Creating an instance to handle the events obj["GameEvents"] = GameEvents(obj["myGame"], "map.camap") myGame = obj["myGame"]
def init(): """init function - runs once""" # create a new font object, use external ttf file font_path = logic.expandPath('//text/Big_Bottom_Cartoon_AD.ttf') italic_font_path = logic.expandPath('//text/Big_Bottom_Cartoon_Italic_AD.ttf') # store the font indice - to use later logic.font_id = blf.load(font_path) logic.font_id_italic = blf.load(italic_font_path) # set the font drawing routine to run every frame scene = logic.getCurrentScene() scene.post_draw = [write]
def filepath(self, path): self._filepath = path try: with open(logic.expandPath('//' + path), 'r', encoding = "UTF-8") as f: self.raw_data = f.read() except UnicodeDecodeError: with open(logic.expandPath('//' + path), 'r', encoding = "Windows-1252") as f: self.raw_data = f.read() if self.filepath.endswith(".srt"): format = ".srt" elif self.filepath.endswith(".sub"): format = ".sub" else: raise ValueError("Subtitle file format not supported.") self.parse(format)
def image(self, img, id): """ Add image to the infobar Arguments: img -- image filename to use (do not use logic.expandPath()) id -- a numerical id for infobar. Infobar items are sorted in order of id. To overwrite/update an item, reuse the id """ aspect = get_image_aspect(logic.expandPath("//"+img)) self.items[id] = bgui.image.Image(self, id, logic.expandPath("//"+img), aspect=aspect, size=[0,0.9], pos=[0,0], options=bgui.BGUI_DEFAULT | bgui.BGUI_CENTERY) self.items[id].frozen = True self.items[id].visible = True
def _parseStyle(self, name, data): keys = list(data.keys()) if not isinstance(data, dict): print("\"data\" must be a dict.") return None skin = None font = None if "skin" in keys: skin = logic.expandPath(data["skin"]) if "font" in keys: font = logic.expandPath(data["font"]) self.styles[name] = Style(skin, font)
def save_options(cont): """ Save options from the globalDict to file. """ path = expandPath("//") ############################ ######## INITIALIZE ######## ############################ for sen in cont.sensors: if type( sen ) == bge.types.SCA_MouseSensor and "options" in globalDict.keys(): try: # Open file from disk with open(path + "options.json", "w") as open_file: # Write file to disk json.dump(globalDict["options"], open_file) # Warning message print("Options saved to options.json") except: # Warning message print("Can't save options to options.json") pass
def widget(cont): own = cont.owner scene = own.scene camera = scene.active_camera over = cont.sensors['Over'] lmb = cont.sensors['LMB'] game_path = expandPath('//Intro.blend') if not over.positive: own.color[3] = 0.7 if over.positive: own.color[3] = 0.9 if own.groupObject and lmb.positive: if 'Command' in own.groupObject: commands = own.groupObject['Command'].split(' | ') for command in commands: try: exec(command) except: print('X Cannot eval expression:', command)
def map_list(cont): # Basic own = cont.owner scene = own.scene # Sensors s_autostart = cont.sensors['autostart'].positive # Objects o_spawner = own # Properties p_maps_path = expandPath('//maps/') p_maps_list = os.listdir( p_maps_path ) p_maps_list = [i for i in p_maps_list if i.endswith('.dwmap')] if s_autostart: if len(p_maps_list) > 0: for i in p_maps_list: added_item = scene.addObject('group_file_existing_map') added_item.groupMembers['file_existing_map'].worldPosition = o_spawner.worldPosition added_item.groupMembers['file_existing_map']['description'] = i added_item.groupMembers['file_existing_map'].childrenRecursive['file_existing_map_text']['Text'] = i.replace('.dwmap', '') added_item.groupMembers['file_existing_map'].childrenRecursive['file_delete_existing_map']['map_file'] = i o_spawner.worldPosition[1] -= 11 pass
def do(): filepath = logic.expandPath('//stages/') + logic.globalDict['stage'] + '/' setupGroundHeight(filepath) setupMapDimensions() switchMapMesh(filepath)
def load_database(cont): """ Initialize data saved in database file. """ own = cont.owner path = expandPath("//") # Sensors s_always = [ sen for sen in cont.sensors if type(sen) == bge.types.SCA_AlwaysSensor ][0].positive ############################ ######## INITIALIZE ######## ############################ if s_always: if not "state" in globalDict.keys(): globalDict["state"] = {"player": {}, "actors": {}, "world": {}} try: with open(path + "database.json", "r") as open_file: # Initialize database in globalDict globalDict["database"] = json.load(open_file) # Warning message print("Database loaded from database.json") except: print("Error loading database.json. Try to reinstall the game") pass
def span_pokemon(self): print('SPAAAWN') pokeball = scene.objects['pokeball'] pokeball.suspendDynamics() files = '//sound//pokeball_sound_effects_mp3cut_1.wv' files_path = logic.expandPath(files) sound = aud.Factory.file(files_path) device = aud.device() device.volume = 0.01 device.play(sound) pokebalOpenSpawn = scene.addObject('pokeball_spawner', pokeball, 800) pokebalOpenSpawn.playAction('pokeball_spawner_action', 0, 60, 0, speed=2) spawedPok = [ x for x in scene.objects if x.name == 'Charizard_sskeleton' ] if len(spawedPok) == 0: pokemon = scene.addObject('Charizard_skeleton', pokebalOpenSpawn, 12500) pokemon.localOrientation = self.avatar.localOrientation pokemon.worldPosition[2] += 3 pokemon.playAction('pokemon_grow', 0, 60, 0) pokemon['jump'] = False pokemon['name'] = 'charizard' self.avatar = pokemon
def __init__(self, path): self.worldPosition = [0,0,0] self.visible = True self.path = path self.fullpath = logic.expandPath("//../data/" + path) self.texture = texture.ImageFFmpeg(self.fullpath) self.clipping = None self._tex_id = glGenTextures(1) self.size = [0, 0] bgl.glTexEnvf(bgl.GL_TEXTURE_ENV, bgl.GL_TEXTURE_ENV_MODE, bgl.GL_MODULATE) self.reload() self.texco = [(0, 0), (1, 0), (1, 1), (0, 1)] self.color = [1, 1, 1, 1] x = render.getWindowWidth()/2 y = render.getWindowHeight()/2 size = [50, 50] width = size[0] height = size[1] self._size = [width, height] # The "private" position returned by setter self._position = [x, y] self._last_position = self._position self.calculate_glposition() module.scene_gui.post_draw.append(self.draw) self.scale = 0.5, 0.5
def __init__(self, path): self.worldPosition = [0, 0, 0] self.visible = True self.path = path self.fullpath = logic.expandPath("//../data/" + path) self.texture = texture.ImageFFmpeg(self.fullpath) self.clipping = None self._tex_id = glGenTextures(1) self.size = [0, 0] bgl.glTexEnvf(bgl.GL_TEXTURE_ENV, bgl.GL_TEXTURE_ENV_MODE, bgl.GL_MODULATE) self.reload() self.texco = [(0, 0), (1, 0), (1, 1), (0, 1)] self.color = [1, 1, 1, 1] x = render.getWindowWidth() / 2 y = render.getWindowHeight() / 2 size = [50, 50] width = size[0] height = size[1] self._size = [width, height] # The "private" position returned by setter self._position = [x, y] self._last_position = self._position self.calculate_glposition() module.scene_gui.post_draw.append(self.draw) self.scale = 0.5, 0.5
def main(): #defualt settings cfg_screen_width = '1024' cfg_screen_height = '768' cfg_fullscreen = 'True' try: load_settings = open('sintel_config.ini', 'r') #load screen width cfg_screen_width = load_settings.readline() cfg_screen_width = cfg_screen_width[0:-1] #screen height cfg_screen_height = load_settings.readline() cfg_screen_height = cfg_screen_height[0:-1] #fullscreen option cfg_fullscreen = load_settings.readline() cfg_fullscreen = cfg_fullscreen load_settings.close() except: pass prog = logic.expandPath("//sintel_win.exe") if cfg_fullscreen == 'True': args = [" -f -c sintel_win.exe"] else: args = [" -w -c sintel_win.exe"] print(os.execvp(prog, (prog, ) + tuple(args)))
def main(): cont = logic.getCurrentController() owner = cont.owner # Insert material name material_name = "Stock Mode Button" matID = texture.materialID(owner, "MA" + material_name) tex = texture.Texture(owner, matID, 0) click = cont.sensors["Click"] mouse_over = cont.sensors["Mouse Over"] if click.positive and mouse_over.positive: objects = logic.getCurrentScene().objects props = objects["Properties"] stock_mode = props["Stock Mode"] if stock_mode == "Stock All": new_stock_mode = "Stock Pick" image_path = "stock_pick.png" else: new_stock_mode = "Stock All" image_path = "stock_all.png" props["Stock Mode"] = new_stock_mode os.chdir(logic.expandPath("//")) tex.source = texture.ImageFFmpeg(image_path) owner["texture_property"] = tex tex.refresh(True)
def play(self, sound, positional=True, loop=0, volume=1): """ Play a sound :param sound: The sound to be played. If it's a string, it will build a factory from the file at that relative path, otherwise, it should be a factory. :type sound: str or aud.Factory :param positional: Whether or not to use 3D positional audio. Defaults to True. :type positional: bool :param loop: Number of times to loop the sound. Negative == infinity. :type loop: int :param volume: The volume. 1.0 = 100% :type loop: float :returns: aud.Handle handle of the sound to be played """ if type(sound) == str: sound = logic.expandPath("//" + sound) sound = aud.Factory(sound) sound.loop(loop) sound.volume(volume) handle = self._device.play( sound ) # if positional == False leave relative and keep position at [0,0,0] if positional == True: handle.relative = False self._collection.append(handle) return handle
def getRandomFileTrack(self): """ Returns a random filename with ``.mp3`` extension. """ current_song = os.path.basename(self.audiofile.filepath) path = logic.expandPath("//../data/" + self.directory) files = [x for x in os.listdir(path) if x.endswith(".mp3") and current_song != x] if files: return utils.choice(files) else: return current_song
def main(): #defualt settings cfg_screen_width = '1024' cfg_screen_height = '768' cfg_fullscreen = 'True' try: load_settings = open('sintel_config.ini', 'r') #load screen width cfg_screen_width = load_settings.readline() cfg_screen_width = cfg_screen_width[0:-1] #screen height cfg_screen_height = load_settings.readline() cfg_screen_height = cfg_screen_height[0:-1] #fullscreen option cfg_fullscreen = load_settings.readline() cfg_fullscreen = cfg_fullscreen load_settings.close() print ('loaded properly', cfg_fullscreen) except: pass prog = logic.expandPath("//sintel_linux") if cfg_fullscreen == 'True': args = [" -f -c sintel_linux"] else: args = [" -w -c sintel_linux"] print( os.execvp(prog, (prog,) + tuple(args)))
def main(): cont = logic.getCurrentController() owner = cont.owner if "Video" in owner: video = owner["Video"] video.refresh(True) else: #Insert material name. mat = "Movie" matID = texture.materialID(owner, "MA" + mat) video = texture.Texture(owner, matID) owner["Video"] = video #Insert path to movie file. movie_path = "" path = logic.expandPath('//' + movie_path) video.source = texture.VideoFFmpeg(path) video.source.play()
def start_training_file(): # Start recordings create_train_dir(settings.gAnimal) fn = get_next_trainname("move") fn_events = fn[:-4] + "events" fn_pos = fn[:-4] + "position" sys.stdout.write("BLENDER: Writing training to:\n") sys.stdout.write(" %s\n" % fn) sys.stdout.write(" %s\n" % fn_events) GameLogic.Object['train_file'] = open(fn, 'wb') GameLogic.Object['event_file'] = open(fn_events, 'wb') GameLogic.Object['pos_file'] = open(fn_pos, 'wb') if settings.looming: GameLogic.Object['current_loomfile'] = open( fn[:-5] + "_loom", 'wb') if settings.has_licksensor_piezo: GameLogic.Object['current_lickfile'] = open( fn[:-5] + "_lick", 'wb') GameLogic.Object['current_fwfile'] = fn[:-4] + "avi" if GameLogic.Object['has_fw']: gc.safe_send(GameLogic.Object['fwconn'], "begin%send" % GameLogic.Object['current_fwfile'], "BLENDER: Couldn't start video; resource unavailable\n") GameLogic.Object['train_tstart'] = time.time() GameLogic.Object['train_open'] = True # Copy current settings: fn_settings_py = fn[:-4] + "_settings.py" blenderpath = GameLogic.expandPath('//') shutil.copyfile('%s/py/settings.py' % blenderpath, fn_settings_py) # line break for printing time: sys.stdout.write("\n")
def filepath(self, path): self._filepath = path if path.endswith(".rpy"): self.parser = RenPyParser(logic.expandPath("//" + path)) else: raise RuntimeError( "The InteractiveText behavior only supports .rpy files. ")
def main(): cont = logic.getCurrentController() owner = cont.owner message = owner.sensors["Message"] if message.positive: subject = message.subjects[0] matID = texture.materialID(owner, "MA" + "Stage Card") tex = texture.Texture(owner, matID, 0) cwd = logic.expandPath("//") os.chdir(cwd) os.chdir("../../2D Art Files/UI Textures/Stage Card Textures") texture_path_dict = { "-2": "/Rock_Concert_card.png", "-1": "/game_test_card.png", "0": "/random_stage_card.png", "1": "/Belair_Estate_card.png", "2": "/Sunset_Pier_card.png", } texture_path = texture_path_dict[subject] new_cwd = os.getcwd() image_path = new_cwd + texture_path tex.source = texture.ImageFFmpeg(image_path) owner["texture_property"] = tex tex.refresh(True)
def saveScores(): _file = Path(expandPath('//scores.dat')) _file = _file.resolve() if _file.exists() else _file with open(_file.as_posix(), 'wb') as openedFile: openedFile.write(zlib.compress(str(globalDict['Scores']).encode(), 1)) print('> Scores written to:', _file.name)
def main(): cont = logic.getCurrentController() owner = cont.owner secondary = owner.sensors["Secondary"] if secondary.positive and owner["Character Selected"]: owner["Character Selected"] = False objects = logic.getCurrentScene().objects select_character_text = objects["Select Character Text"] select_character_text.text = "SELECT CHARACTER" character_portrait_glow = objects["Character Portrait Glow"] character_portrait_glow.visible = False character_portrait = objects["Character Portrait"] matID = texture.materialID(character_portrait, "MA" + "Character Portrait") tex = texture.Texture(character_portrait, matID, 0) # Specify path to image. os.chdir(logic.expandPath("//")) os.chdir("../Rendered Images/Character Portraits") cwd = os.getcwd() image_path = cwd + "/black.png" tex.source = texture.ImageFFmpeg(image_path) owner["texture_property"] = tex tex.refresh(True)
def play(self, video, callback=None): """ Plays a video on this screen, also makes the *speaker* aviable. :param string video: The relative path (from the data folder) of the video to use. :param function callback: Function to call once the video ends. """ #Video path = logic.expandPath("//" + video) if not os.path.isfile(path): raise FileNotFoundError(path + " doesn't exist") self.video = texture.Texture(self.obj, 0) self.video.source = texture.VideoFFmpeg(path) self.video.source.scale = True self.video.source.play() module.video_playback_list.append(self) #Audio try: self.speaker = AudioFile() self.speaker = self.speaker.play(video) except RuntimeError: pass #Callback self.callback = callback return self
def play(self, sound, positional=True, loop=0, volume=1): """ Play a sound :param sound: The sound to be played. If it's a string, it will build a factory from the file at that relative path, otherwise, it should be a factory. :type sound: str or aud.Factory :param positional: Whether or not to use 3D positional audio. Defaults to True. :type positional: bool :param loop: Number of times to loop the sound. Negative == infinity. :type loop: int :param volume: The volume. 1.0 = 100% :type loop: float :returns: aud.Handle handle of the sound to be played """ if type(sound) == str: sound = logic.expandPath("//" + sound) sound = aud.Factory(sound) sound.loop(loop) sound.volume(volume) handle = self._device.play(sound) # if positional == False leave relative and keep position at [0,0,0] if positional == True: handle.relative = False self._collection.append(handle) return handle
def playVideo(obj, video_path): matID = texture.materialID(obj, 'IMplaceholder.jpg') logic.video = texture.Texture(obj, matID) movie = logic.expandPath(video_path) logic.video.source = texture.VideoFFmpeg(movie) logic.video.source.play()
def init_new_data(): scene = bge.logic.getCurrentScene() if not 'map' in globalDict.keys(): first_map = expandPath('//maps/') + [m for m in os.listdir(expandPath('//maps/')) if m.endswith('.dwmap')][0] with open(first_map, 'r') as open_file: globalDict['map'] = litev(open_file.read()) # Map if globalDict['map'] == {}: globalDict['map'] = default_map.copy() #pprint(globalDict) pass
def filepath(self, path): self._filepath = path try: with open(logic.expandPath("//" + path), "r", encoding="UTF-8") as f: self.raw_data = f.read() except UnicodeDecodeError: with open(logic.expandPath("//" + path), "r", encoding="Windows-1252") as f: self.raw_data = f.read() if self.filepath.endswith(".srt"): format = ".srt" elif self.filepath.endswith(".sub"): format = ".sub" else: raise ValueError("Subtitle file format not supported.") self.parse(format)
def switchMesh(obj, model): # Load mesh into memory only if it isn't already loaded filepath = logic.expandPath('//models/') + model + '.blend' if filepath not in logic.LibList(): logic.LibLoad(filepath, 'Mesh') # Switch objects mesh obj.replaceMesh(model)
def play(self, filepath=None, loop=False, volume=None, pitch=1, callback=None, transition=(3, 2, 3)): """ Method to play an audio file. If an audio file is being played while calling this, it will be replaced by a new one. During the transation a *fadeOut->FadeIn* effect will occur. :param string filepath: Relative path (from the data folder) of the audio file to use. :param bool loop: If true the audio will be played in loop. :param float volume: The volume of the audio file relative to the master device. (Default = 1.0) :param float pitch: The pitch. :param function callback: Function to call once the playback ends. :param tuple transition: The times for the fade effect during transations. In order: Duration of the fadeout, time for the fadein to start, duration of the fadein. In sconds. """ if self.waiting == True: # Replace sound that will be played. self.filepath = filepath return if self.playing == True: # FadeOut this sound and fadeIn the new one. x, y, z = transition dummy = self.moveInstance() dummy.fadeOut(x, stop=True) if filepath: self.filepath = filepath self.waiting = True sequencer.Wait(y, lambda: self._transition_callback(z)) self.callback = callback return self.callback = callback if not filepath: filepath = self.filepath else: self.filepath = filepath path = logic.expandPath("//../data/" + filepath) factory = aud.Factory(path) try: self.factory = factory self.handle = device.play(self.factory) # It sends a callback that will play the music on a new theread. self.handle.pitch = pitch if volume == None: self.volume = self._volume else: self.volume = volume if loop: self.handle.loop_count = -1 except: if os.path.isfile(path) == False: utils.debug("Audio File, Not Found: " + path) else: raise RuntimeException("AudioFile Load Error: " + path) self.playing = True module.low_frequency_callbacks.append(self.update) return self
def start_record_file(): # Start recordings fn, fnfw = get_next_filename("bin") sys.stdout.write("BLENDER: Writing to:\n") sys.stdout.write(" %s\n" % fn) GameLogic.Object['file_open'] = True GameLogic.Object['current_file'] = open(fn, 'wb') GameLogic.Object['current_movfile'] = fn[:-3] + "avi" if settings.looming: GameLogic.Object['current_loomfile'] = open( fn[:-4] + "_loom", 'wb') if settings.has_licksensor_piezo: GameLogic.Object['current_lickfile'] = open( fn[:-4] + "_lick", 'wb') GameLogic.Object['current_fwfile'] = fnfw[:-3] + "avi" GameLogic.Object['current_ephysfile'] = fn[:-3] + "h5" GameLogic.Object['current_settingsfile'] = fn[:-4] + "_settings.txt" write_settings(GameLogic.Object['current_settingsfile']) fn_events = fn[:-4] + "_events" GameLogic.Object['event_file'] = open(fn_events, 'wb') sys.stdout.write(" %s\n" % GameLogic.Object['current_movfile']) sys.stdout.write(" %s\n" % GameLogic.Object['current_ephysfile']) # start ephys and video recording: if settings.has_webcam: gc.safe_send(GameLogic.Object['vidconn'], "begin%send" % GameLogic.Object['current_movfile'], "BLENDER: Couldn't start video; resource unavailable\n") if GameLogic.Object['has_fw']: gc.safe_send(GameLogic.Object['fwconn'], "begin%send" % GameLogic.Object['current_fwfile'], "BLENDER: Couldn't start video; resource unavailable\n") if settings.has_comedi and ncl.has_comedi: gc.safe_send(GameLogic.Object['comediconn'], "begin%send" % GameLogic.Object['current_ephysfile'], "BLENDER: Couldn't start electrophysiology; resource unavailable\n") # Wait for comedi to initialize the channels before triggering datadec = "" while datadec.find('primed')==-1: try: data = GameLogic.Object['comediconn'].recv(1024) datadec = data.decode('latin-1') print(data) except: pass print("found") ncl.set_trig(outtrigch, 1) # get ephys start time: GameLogic.Object['ephysstart'] = (parse_ephystimes(GameLogic.Object['comediconn'])-GameLogic.Object['time0'])[0] else: # TODO: get correct intan ephys start time GameLogic.Object['ephysstart'] = time.time()-GameLogic.Object['time0'] # Copy current settings: fn_settings_py = fn[:-4] + "_settings.py" blenderpath = GameLogic.expandPath('//') shutil.copyfile('%s/py/settings.py' % blenderpath, fn_settings_py)
def init(): """init function - runs once""" # create a new font object font_path = logic.expandPath('//fonts/CabinSketch.ttf') logic.font_id = blf.load(font_path) # set the font drawing routine to run scene = logic.getCurrentScene() scene.post_draw = [draw_names]
def finish_line(): if not logic.car["ended"]: print("META!!!") name = username.Username(ROOT).get() map_time = logic.car["time"] H = highscore.Highscore(logic.expandPath("//")) H.add_score(name, map_time) print("{} completó en {}".format(name, map_time)) logic.car["ended"] = True
def __init__(self, filepath): self.relative_path = filepath self.path = logic.expandPath("//../data/" + filepath) self.objects = {} #e.j: mygen.objects["MyObjName"][3].worldOrientation... self.ids = [] with open(self.path, "rb") as input: self.data = input.read() if self.relative_path in ObjectGenerator.all: raise KeyError("A generator with path " + filepath + "already exists.") else: ObjectGenerator.all[self.relative_path] = self
def setupParties(own): # Get list of parties partiesDir = logic.expandPath('//parties') partyNames = [x[2] for x in os.walk(partiesDir)][0] # NOTE(kgeffen) Strip off '.json' from each file (.json is last 5 chars) parties = [name[:-5] for name in partyNames if name.endswith('.json')] own['party1'] = parties own['party2'] = copy.deepcopy(parties)
def getRandomFileTrack(self): """ Returns a random filename with any extension. """ current_song = os.path.basename(self.audiofile.filepath) path = logic.expandPath("//" + self.directory) files = [ x for x in os.listdir(path) if current_song != x and not x in self.ignore ] if files: return utils.choice(files) else: return current_song
def theme(self, v): self._theme = v if self._theme != None: for k, v in self._theme.items(): if k != "PGUI_SKIN": path = v["image"] v["image"] = Image(logic.expandPath(path)) for k, c in self.controls.items(): c.theme = self._theme
def getBlendFilepath(): """ Returns the blend file absolute filepath, including the name. """ try: from bpy import data return data.filepath except ImportError: import sys path = [x for x in sys.argv if x.endswith(".blend") or x.endswith(".blend~")][0] if path[-1] == '~': path = path[:-1] return logic.expandPath("//" + os.path.basename(path))
def select(own): field = FIELDS[ own['fieldNum'] ] # TODO(kgeffen) Break up these if/elifs into methods found by dictionary if field == 'party': pass elif field == 'addSkill': # Append to current list of skills that skill selected, # if unit doesn't already have that skill and has less skills than max commands = own['units'][0]['commands'][0] if len(commands) < MAX_SKILLS: command = own['addSkill'][0] if command not in commands: commands.append(command) elif field == 'removeSkill': commands = own['units'][0]['commands'][0] if len(commands) != 0: commands.pop(0) elif field == 'button': button = BUTTONS[ own['buttonNum'] ] if button == 'exit': returnToMainScreen() elif button == 'save': filepath = logic.expandPath('//parties/') + own['party'] + '.json' with open(filepath, 'w') as outfile: json.dump(own['units'], outfile) own.sendMessage('partiesChanged') returnToMainScreen() elif button == 'delete': # Delete the json that has this parties information party = logic.globalDict['party'] filepath = logic.expandPath('//parties/') + party + '.json' os.remove(filepath) own.sendMessage('partiesChanged') returnToMainScreen()
def main(): import sys sys.path.append(logic.expandPath("//Scripts")) import Game import Player logic.game = Game.Game( [Player.Player(0, "Roosendal"), Player.Player(1, "Toon")]) logic.begin = 1 logic.game.initGame()
def init(): """init function - runs once""" # create a new font object, use external ttf file font_path = logic.expandPath('//Zeyada.ttf') # store the font indice - to use later logic.font_id = blf.load(font_path) # set the font drawing routine to run every frame scene = logic.getCurrentScene() scene.post_draw = [write]
def texture_new(self, new_tex): ''' Application de la nouvelle texture''' # Nouvelle source self.url = gl.expandPath(new_tex) print("Path du fichier", new_tex, "=", self.url) self.new_source = texture.ImageFFmpeg(self.url) # Remplacement self.obj_texture.source = self.new_source self.obj_texture.refresh(False)
def addActiveUnits(): filepath = logic.expandPath('//stages/') + logic.globalDict['stage'] + '/' + STAGE_DATA_FILENAME # Load all of stage's data from file data = None with open(filepath) as stageDataFile: data = json.load(stageDataFile) # Add active units to field for unit in data['activeUnits']: unitControl.object.add(unit)
def init(): # create a new font object, use external ttf file font_path = logic.expandPath('//assets/fonts/LiberationMono-Regular.ttf') # store the font indice - to use later logic.font_id = blf.load(font_path) # set the font drawing routine to run every frame scene = logic.getCurrentScene() scene.post_draw = [write] logic.text_buffer = []
def __init__(self, gobj): super().__init__(gobj) self.device = aud.device() sound = logic.expandPath("//sounds/enemy_hurt.ogg") factory = aud.Factory(sound) self.factory = aud.Factory.buffer(factory) self.collision = self.gobj.collision self.state("damage_calc")
def addInactiveUnits(): for i in [1, 2]: filepath = logic.expandPath('//parties/') + logic.globalDict['party' + str(i)] + '.json' # Load all of stage's data from file with open(filepath) as partyData: inactiveUnits = json.load(partyData) for unit in inactiveUnits: unit['align'] = ALIGNS[i - 1] unit['team'] = i logic.globalDict['inactiveUnits'].append(unit)
def set_netmode(self, netmode): # Load configuration print("Loading network information from {}".format(DATA_PATH)) file_path = logic.expandPath("//{}".format(DATA_PATH)) # self.configuration_file_names = {path.splitext(f)[0] for f in listdir(file_path)} main_definition_path = path.join(file_path, "main.definition") # Load network information with open(main_definition_path, "r") as file: world_settings = load(file) self.network_update_interval = 1 / world_settings['tick_rate'] self.metric_interval = world_settings['metric_interval'] print("Set netmode", Netmodes[netmode]) self.world = World(netmode, logic.getLogicTicRate(), file_path) logic.world = self.world if netmode == Netmodes.server: port = world_settings['port'] self.world.rules = Rules() else: port = 0 self.network_manager = NetworkManager(self.world, "", port) # Time since last sent self.time_since_sent = 0.0 # Set network as active update function self.on_step = self.step_network self.cleanup = lambda: self.network_manager.stop() self._listeners['METHOD_INVOKE'] = self._on_invoke_method self._listeners['RPC_INVOKE'] = self._on_invoke_rpc self._listeners['PAWN_REASSOCIATE'] = self._on_controller_reassign self._listeners['SELF_MESSAGE'] = self._on_self_message self._listeners['SCENE_MESSAGE'] = self._on_scene_message self._listeners['PAWN_ASSOCIATE'] = self._on_controller_assign self._listeners['TO_NEW_PAWN'] = self._on_new_pawn_message if netmode == Netmodes.client: self._listeners['CONNECT_TO'] = self._on_connect_to # Set network state self._update_network_state() logic.sendMessage(encode_subject("NETWORK_INIT")) print("Network started")
def setMiniMap(self, name): mini_map = objects['mini_map'] imagePath = logic.expandPath('//../textures/hud/maps/' + name) matID = bge.texture.materialID(mini_map, "MAminiMap") # get the texture tex = bge.texture.Texture(mini_map, matID) logic.texture = tex # get image used as the texture source logic.texture.source = bge.texture.ImageFFmpeg(imagePath) # display the image logic.texture.refresh(False) # Display plane mini_map.setVisible(True)
def setup(cont): own = cont.owner if cont.sensors['start'].positive: '''Read party data from json''' partyName = logic.globalDict['party'] filepath = logic.expandPath('//parties/') + partyName + '.json' with open(filepath) as partyFile: own['units'] = json.load(partyFile) own['party'] = partyName '''Read list of valid classes from json''' filepath = logic.expandPath('//script/classes.json') with open(filepath) as classesFile: own['class'] = json.load(classesFile) '''Read list of commands to add from json''' filepath = logic.expandPath('//releasedCommands.json') with open(filepath) as commandsFile: own['addSkill'] = json.load(commandsFile)
def setup(cont): own = cont.owner if cont.sensors['start'].positive: logic.globalDict['mute'] = False # Get list of names of all stages stagesDir = logic.expandPath('//stages') stageNames = [x[1] for x in os.walk(stagesDir)][0] own['stages'] = stageNames setupParties(own) own['players'] = PLAYERS