def load_all_packages(root, dirn, console=None): sys.dont_write_bytecode=True info("Loading Plugins") #if console: post_and_flip(console, "| | | | | |", bold=1, color=(0,255,0)) if console: post_and_flip(console, "V V V Loading Plugins V V V", bold=1, color=(0,255,0)) load_plugins(root, dirn, console) info("Doing last plugin init...") for ext in root.extentions: root.extentions[ext].after_plugins_load() load_notifiers(root, dirn) if console: post_and_flip(console, "V V V Loading Other Files V V V", bold=1, color=(0,255,0)) for pattern in root.gamedb.json_extentions: safepost(console, "Loading Files That End With `"+pattern+"`", italic=1, color=(0,255,0)) load_assetkeys(root, dirn, console, pattern) if len(absroot.gamedb.delayed_load_files)>0: warning("After load_assetkeys there are "+str(len(absroot.gamedb.delayed_load_files))+" files that were not loaded because they had unmet dependencies... Listing:") for i in absroot.gamedb.delayed_load_files: warning(" "+str(i)) tasks.display_hanging_message("After load_assetkeys there are "+str(len(absroot.gamedb.delayed_load_files))+" files that were not loaded because they had unmet dependencies... Check log.", color=(255,255,0)) if console: post_and_flip(console, "LOADING FINISHED!", bold=1, italic=1, color=(0,255,0)) post_and_flip(console, "Loaded "+str(len(root.gamedb.assets))+" assets") post_and_flip(console, "Loaded "+str(len(root.item_factories))+" items") post_and_flip(console, "Loaded "+str(len(root.ship_factories))+" ships") post_and_flip(console, "Loaded "+str(root.dialog_manager.count_pools())+" speech pools ("+str(root.dialog_manager.count_speeches())+" speech instances distributed)") post_and_flip(console, "Loaded "+str(len(root.quest_factories))+" quests") post_and_flip(console, "Loaded "+str(len(root.sector_prototypes))+" sectors") time.sleep(2.5)
def play(self, track): self.stop() self.current_track = track tasks.display_hanging_message("You are now listening to " + track.name + "", time=5, color=(100, 255, 100)) self.channel.play(track.sound, fade_ms=1000)
def load_with_loader(self, node, basepath, path, console=None): # print node["type"] # print node["type"] in self.loaders.keys() # print try: debug("Applying loader:'" + node["type"] + "' infer from:'" + node["name"] + "'...") #print "Loading "+node["name"] self.metadata[node["name"]] = { "basepath": basepath, "apath": path, "udpath": path, "node": node, "refs": 0, "trefs": 0 } self.assets[str(node["name"])] = self.loaders[str( node["type"])](get_expanded_json(self, node), basepath, self.metadata[node["name"]]) except KeyError as e: error("Loader " + node["type"] + " not found! (probably)") exc_type, exc_value, exc_traceback = sys.exc_info() error("================ERROR LOG=====================") for i in traceback.format_exception(exc_type, exc_value, exc_traceback): error(i) if console: extention_loader.post_and_flip( console, "ASSETKEY ERROR! KeyError: '" + traceback.format_exception( exc_type, exc_value, exc_traceback)[-1] + "'", color=(255, 0, 0), bold=1) tasks.display_hanging_message( "An unknown error appeared while loading the asset `" + node.get("name", "[no name, this is probably the problem]") + "` [KeyError]: Check log (" + str(e) + ")", color=(255, 0, 0)) except BaseException as e: tasks.display_hanging_message( "An unknown error appeared while loading the asset `" + node.get("name", "[no name, this is probably the problem]") + "`: Check log (" + str(e) + ")", color=(255, 0, 0)) exc_type, exc_value, exc_traceback = sys.exc_info() error("================ERROR LOG=====================") for i in traceback.format_exception(exc_type, exc_value, exc_traceback): error(i) if console: extention_loader.post_and_flip( console, "ASSETKEY ERROR! KeyError: '" + traceback.format_exception( exc_type, exc_value, exc_traceback)[-1] + "'", color=(255, 0, 0), bold=1)
def play_tagged(self, tag): options=[] for track in absroot.music_tracks: if tag in track.tags: options.append(track) if options: self.play(random.choice(options)) self.playing_requested=True else: tasks.display_hanging_message("play_tagged cannot find anything tagged `"+tag+"`", color=(255,0,0))
def play_tagged(self, tag): options = [] for track in absroot.music_tracks: if tag in track.tags: options.append(track) if options: self.play(random.choice(options)) self.playing_requested = True else: tasks.display_hanging_message( "play_tagged cannot find anything tagged `" + tag + "`", color=(255, 0, 0))
def interdict_ok(root, title, content, button="ACCEPT", titlecolor=(255, 255, 255), textcolor=(0, 0, 0), buttoncolor=(0, 0, 255)): tasks.display_hanging_message( "Something started interdict_ok, Don't use that!", color=(255, 255, 0)) debug("Starting interdict_ok") warn("THIS MODULE IS DEPRECATED. USE UI_STATES INSTEAD") debug("T:" + title) debug("C:" + content) debug("B:" + button) screen = root.screen.screen x = 350 y = 150 gamedb = root.gamedb width = 600 offset = 20 wrapped = textwrap.wrap(content, 48) titlerender = gamedb.get_asset("font_standard_large").render( title, 1, titlecolor) buttonrender = gamedb.get_asset("font_standard_large").render( button, 1, buttoncolor) screen.blit(gamedb.get_asset("uia_ok_dialog"), (x, y)) screen.blit(titlerender, (x + 5, y + 30)) screen.blit(buttonrender, (x + 58, y + 314)) ok_collide = pygame.Rect( x + 25, y + 308, 170, 50 ) #pylygon.polygon.Polygon([(x+25,y+308), (x+191, y+308), (x+191,y+356), (x+72, y+356)]) #pygame.draw.rect(screen, (255,0,0), ok_collide.get_rect()) i = y + 60 for l in wrapped: line = gamedb.get_asset("font_sys_mono").render(l, 1, textcolor) try: screen.blit(line, (x + 5, i)) except TypeError: pass i += 20 run = 1 while not pygame.QUIT in [e.type for e in pygame.event.get()] and run: if pygame.mouse.get_pressed()[0]: if ok_collide.collidepoint(pygame.mouse.get_pos()): return True root.clock.tick() pygame.display.flip()
def goto_sector(self, x, y): info("Transitioning from sector ("+str(self.currentx)+","+str(self.currenty)+") to ("+str(x)+","+str(y)+")") if x in self.sectormap.keys(): if y in self.sectormap[x].keys(): sg_postevent(UE_CHANGE_SECTOR, galaxy=self, newx=x, newy=y) if type(self.currentx) == int: self.get_sector().unload() self.currentx=x self.currenty=y self.get_sector().load() sg_postevent(UE_CHANGE_SECTOR_FINISH, galaxy=self) return error("Sector not defined! (No change made)") tasks.display_hanging_message("ERROR: Tried to move to a nonexistant sector (no change made)", color=(255,255,0))
def process_events(self, events): for e in events: if e.type == pygame.KEYDOWN: if e.key == self.root.settings["keybindings"]["prev_item"]: self.player.selected_wep -= 1 if self.player.selected_wep == -1: self.player.selected_wep = len( self.player.hardpoints) - 1 elif e.key == self.root.settings["keybindings"]["next_item"]: self.player.selected_wep += 1 if self.player.selected_wep == len(self.player.hardpoints): self.player.selected_wep = 0 elif e.key == pygame.K_HOME: self.entities.append( ship.create_ship(self.root, "destroyer_transport_test", 1000, 1000)) self.entities[-1].targeted = self.player self.entities[-1].rigidbody.x = 0 self.entities[-1].rigidbody.y = 0 self.player.targeted = self.entities[-1] elif e.key == pygame.K_i: self.root.state_manager.start_interdicting( "inventory", {"ship": self.player}) elif e.key == pygame.K_BACKQUOTE: pass #hiding window elif e.key == pygame.K_ESCAPE: self.root.state_manager.start_interdicting( "generic_ui", self.root.gamedb("sgcui_settings")) elif e.key == pygame.K_F5: serialize.save_game(self.root, "saves/quicksave.sgs") tasks.display_hanging_message("Quicksaving...") elif e.key == pygame.K_F9: serialize.load_game(self.root, "saves/quicksave.sgs") tasks.display_hanging_message("Quickloading...") elif e.type == pygame.VIDEORESIZE: print e print "gsresize" print debug("GameState resize") self.parralax_scroller.bindall(self.root.renderspace_size) elif e.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed( )[0]: for entitiy in self.entities: if entitiy.can_be_targeted: if self.root.screen.get_t_rect( entitiy.rotated_rect).collidepoint( pygame.mouse.get_pos()): self.player.targeted = entitiy for ext in self.root.extentions: self.root.extentions[ext].event_state("game", e)
def load_file(self, basepath, dirn, filen, console, pattern): #print sorted(self.assets.keys()) #print filen with open(dirn + "/" + filen, 'r') as fp: json_data = json.load(fp) if not "require" in json_data: json_data["require"] = [] #json_data["require"].extend(jsonutil.get_inserts(json_data)) # <-- Causes assetkeys that define A and then reference it in B to never load #print json_data["require"] for dep in json_data["require"]: if not self.has_asset(dep): # print dep debug("Dependency '" + dep + "' not met, aborting for now...") for config in self.delayed_load_files: if config[0] == basepath and config[1] == dirn and config[ 2] == filen: # print "already found" return self.delayed_load_files.append( (basepath, dirn, filen, console, pattern, dep)) # print "actually added" return if pattern in self.extention_loaders: debug("Loading " + dirn + "/" + filen + " (matched pattern " + pattern + ") using all known loaders") extention_loader.safepost( console, "Loading " + dirn + "/" + filen + " --> " + ", ".join( [f.func_name for f in self.extention_loaders[pattern]])) for loader in self.extention_loaders[pattern]: try: loader(json_data, basepath, dirn, filen, console) except BaseException as e: tasks.display_hanging_message( "An unknown error appeared while loading the file `" + dirn + "/" + filen + "` : Check log (" + str(e) + ")", color=(255, 0, 0)) for config in self.delayed_load_files: if config[0] == basepath and config[1] == dirn and config[ 2] == filen: del self.delayed_load_files[self.delayed_load_files.index( config)] for delayed in self.delayed_load_files: if self.has_asset(delayed[-1]): self.load_file(*delayed[:-1])
def interdict_yn(root, title, content, buttont="YES", buttonf="NO", titlecolor=(255,255,255), textcolor=(0,0,0), buttoncolort=(0,0,255), buttoncolorf=(0,0,255)): tasks.display_hanging_message("Something used interdict_yn, Don't use that!", color=(255,255,0)) debug("Starting interdict_yn") warn("THIS MODULE IS DEPRECATED. USE UI_STATES INSTEAD") debug("T:"+title) debug("C:"+content) debug("BT:"+buttont) debug("BF:"+buttonf) screen=root.screen.screen x=350 y=150 gamedb=root.gamedb width=600 offset=20 wrapped=textwrap.wrap(content, 48) titlerender=gamedb.get_asset("font_standard_large").render(title, 1, titlecolor) buttonrendert=gamedb.get_asset("font_standard_large").render(buttont, 1, buttoncolort) buttonrenderf=gamedb.get_asset("font_standard_large").render(buttonf, 1, buttoncolorf) screen.blit(gamedb.get_asset("uia_yn_dialog"), (x,y)) screen.blit(titlerender, (x+5,y+30)) screen.blit(buttonrendert, (x+58,y+314)) screen.blit(buttonrenderf, (x+406,y+314)) t_collide=pygame.Rect(x+25, y+308, 170, 50)#pylygon.polygon.Polygon([(x+25,y+308), (x+191, y+308), (x+191,y+356), (x+72, y+356)]) f_collide=pygame.Rect(x+404, y+308, 170, 50) i=y+60 for l in wrapped: line=gamedb.get_asset("font_sys_mono").render(l, 1, textcolor) try: screen.blit(line, (x+5,i)) except TypeError: pass i+=20 run=1 while not pygame.QUIT in [e.type for e in pygame.event.get()] and run: if pygame.mouse.get_pressed()[0]: if t_collide.collidepoint(pygame.mouse.get_pos()): return True if f_collide.collidepoint(pygame.mouse.get_pos()): return False root.clock.tick() pygame.display.flip()
def process_events(self, events): for e in events: if e.type==pygame.KEYDOWN: if e.key == self.root.settings["keybindings"]["prev_item"]: self.player.selected_wep-=1 if self.player.selected_wep==-1: self.player.selected_wep=len(self.player.hardpoints)-1 elif e.key == self.root.settings["keybindings"]["next_item"]: self.player.selected_wep+=1 if self.player.selected_wep==len(self.player.hardpoints): self.player.selected_wep=0 elif e.key == pygame.K_HOME: self.entities.append(ship.create_ship(self.root, "destroyer_transport_test", 1000, 1000)) self.entities[-1].targeted=self.player self.entities[-1].rigidbody.x=0 self.entities[-1].rigidbody.y=0 self.player.targeted=self.entities[-1] elif e.key == pygame.K_i: self.root.state_manager.start_interdicting("inventory", {"ship":self.player}) elif e.key == pygame.K_BACKQUOTE: pass #hiding window elif e.key == pygame.K_ESCAPE: self.root.state_manager.start_interdicting("generic_ui", self.root.gamedb("sgcui_settings")) elif e.key == pygame.K_F5: serialize.save_game(self.root, "saves/quicksave.sgs") tasks.display_hanging_message("Quicksaving...") elif e.key == pygame.K_F9: serialize.load_game(self.root, "saves/quicksave.sgs") tasks.display_hanging_message("Quickloading...") elif e.type==pygame.VIDEORESIZE: print e print "gsresize" print debug("GameState resize") self.parralax_scroller.bindall(self.root.renderspace_size) elif e.type==pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]: for entitiy in self.entities: if entitiy.can_be_targeted: if self.root.screen.get_t_rect(entitiy.rotated_rect).collidepoint(pygame.mouse.get_pos()): self.player.targeted=entitiy for ext in self.root.extentions: self.root.extentions[ext].event_state("game", e)
def load_file(self, basepath, dirn, filen, console, pattern): #print sorted(self.assets.keys()) #print filen with open(dirn+"/"+filen, 'r') as fp: json_data=json.load(fp) if not "require" in json_data: json_data["require"]=[] #json_data["require"].extend(jsonutil.get_inserts(json_data)) # <-- Causes assetkeys that define A and then reference it in B to never load #print json_data["require"] for dep in json_data["require"]: if not self.has_asset(dep): # print dep debug("Dependency '"+dep+"' not met, aborting for now...") for config in self.delayed_load_files: if config[0]==basepath and config[1]==dirn and config[2]==filen: # print "already found" return self.delayed_load_files.append((basepath, dirn, filen, console, pattern, dep)) # print "actually added" return if pattern in self.extention_loaders: debug("Loading "+dirn+"/"+filen+" (matched pattern "+pattern+") using all known loaders") extention_loader.safepost(console, "Loading "+dirn+"/"+filen+" --> "+", ".join([f.func_name for f in self.extention_loaders[pattern]])) for loader in self.extention_loaders[pattern]: try: loader(json_data, basepath, dirn, filen, console) except BaseException as e: tasks.display_hanging_message("An unknown error appeared while loading the file `"+dirn+"/"+filen+"` : Check log ("+str(e)+")", color=(255,0,0)) for config in self.delayed_load_files: if config[0]==basepath and config[1]==dirn and config[2]==filen: del self.delayed_load_files[self.delayed_load_files.index(config)] for delayed in self.delayed_load_files: if self.has_asset(delayed[-1]): self.load_file(*delayed[:-1])
def load_with_loader(self, node, basepath, path, console=None): # print node["type"] # print node["type"] in self.loaders.keys() # print try: debug("Applying loader:'"+node["type"]+"' infer from:'"+node["name"]+"'...") #print "Loading "+node["name"] self.metadata[node["name"]]={"basepath":basepath, "apath":path, "udpath":path, "node":node, "refs":0, "trefs":0} self.assets[str(node["name"])]=self.loaders[str(node["type"])](get_expanded_json(self, node), basepath, self.metadata[node["name"]]) except KeyError as e: error("Loader "+node["type"]+" not found! (probably)") exc_type, exc_value, exc_traceback = sys.exc_info() error("================ERROR LOG=====================") for i in traceback.format_exception(exc_type, exc_value, exc_traceback): error(i) if console: extention_loader.post_and_flip(console, "ASSETKEY ERROR! KeyError: '"+traceback.format_exception(exc_type, exc_value, exc_traceback)[-1]+"'", color=(255,0,0), bold=1) tasks.display_hanging_message("An unknown error appeared while loading the asset `"+node.get("name", "[no name, this is probably the problem]")+"` [KeyError]: Check log ("+str(e)+")", color=(255,0,0)) except BaseException as e: tasks.display_hanging_message("An unknown error appeared while loading the asset `"+node.get("name", "[no name, this is probably the problem]")+"`: Check log ("+str(e)+")", color=(255,0,0)) exc_type, exc_value, exc_traceback = sys.exc_info() error("================ERROR LOG=====================") for i in traceback.format_exception(exc_type, exc_value, exc_traceback): error(i) if console: extention_loader.post_and_flip(console, "ASSETKEY ERROR! KeyError: '"+traceback.format_exception(exc_type, exc_value, exc_traceback)[-1]+"'", color=(255,0,0), bold=1)
def load_plugin(root, fname, console): if not ".PYC" in fname.upper(): debug("Load plugin '"+fname+"'") key=fname.replace("\\", "").replace(".", "") sys.path.append(os.path.dirname(os.path.realpath(fname))) try: exec key+" = imp.load_source('"+key+"', fname)" except BaseException as e: tasks.display_hanging_message("Loading of "+fname+" failed: "+str(e), color=(255,0,0)) return debug("Key mapped as '"+key+"' ") for funcname in eval("dir("+key+")"): if funcname.upper().startswith("INIT"): debug("Run init '"+fname+"'::"+funcname) if console: post_and_flip(console, "Initilizing Plugin `"+fname+"`::"+funcname, color=(255,255,255)) try: retdat=eval(key+"."+funcname+"(root, console)") debug("It returned: "+str(retdat)) if retdat==False: warning( "Loading of '"+funcname+"' from '"+fname+"' failed: False") tasks.display_hanging_message("Loading of "+fname+"::"+funcname+" failed: False", color=(255,0,0)) except BaseException as e: tasks.display_hanging_message("Loading of "+fname+"::"+funcname+" failed: "+str(e), color=(255,0,0)) sys.path.remove(sys.path[-1])
def play(self, track): self.stop() self.current_track=track tasks.display_hanging_message("You are now listening to "+track.name+"", time=5, color=(100,255,100)) self.channel.play(track.sound, fade_ms=1000)
[splash_texts.extend(x) for x in absroot.gamedb.get_startswith("splashes_")] splash_text = random.choice(splash_texts) while run: events = pygame.event.get() root.last_events_len = len(events) fpsgraph.event(events) fpsgraph.update(absroot=absroot) for ext in root.extentions: for e in events: try: root.extentions[ext].event_root(e) except BaseException as e: tasks.display_hanging_message( "An unknown error appeared in the event callback for `" + ext + "`: Check log (" + str(e) + ")", color=(255, 0, 0)) try: root.extentions[ext].tick(root.state_manager.current) except BaseException as e: tasks.display_hanging_message( "An unknown error appeared in the tick for `" + ext + "`: Check log (" + str(e) + ")", color=(255, 0, 0)) for e in events: if e.type == pygame.QUIT: debug("Shutting Down") info("Writing an autosave to autosave.sgs") serialize.save_game(root, "saves/autosave.sgs") debug("--Save completed, dying")