def loadMap(zone, name): path = "game/resources/map/" + zone + "/" + name + ".json" try: getValues = json.load(open(path)) returnValues = [] returnValues.append([ int(getValues["entries"]["default"]), int(getValues["map"]["events"]) ]) returnValues.append(getValues["collision"][0]) returnValues.append(getValues["entries"]) returnValues.append(getValues["entities"][0]) returnValues.append(getValues["layers"]) returnValues.append(getValues["map"]["tileset"]) return returnValues except json.decoder.JSONDecodeError: Logger.error("MapLoading", "Can't load the map " + path) exit()
def error(self, error): # When error, replace the current texture by the error texture Logger.error( "Texture", "Error while loading texture n°" + str(self.id) + " (" + self.path.replace(self.PATH, '') + ')') Logger.bold("Error returned :") print(" " + str(error) + "\n")
def saveConfig(): ConfigToSave = {"config": Config.values} with open(Config.MAIN_CONFIG_PATH, 'w') as outfile: json.dump(ConfigToSave, outfile, indent=" ") Logger.success("Config", "Configuration file saved successfully !")
def run(self): self.loop = True try: self.conn.connect((self.ip, self.port)) self.me = str(self.conn.getsockname()[1]) self.isConnect = True except socket.timeout as e: Logger.warning( "Client", "Error when connecting to the server (" + str(self.ip) + ":" + str(self.port) + ")") print(e) self.isConnect = False except ConnectionRefusedError as e: Logger.warning("Client", "Connection refused") print(e) self.isConnect = False self.setTimeout(0.02) # Loop where at each time, client will see if # it must send a message to the server and will try # to receive data from the server while self.loop: if self.wantSend: self.theadSend() self.wantSend = False self.receive() self.disconnection()
def addToTest(entityId): # If the entity is not yet in the table of test if not entityId in EntityManager.entitiesCol: EntityManager.entitiesCol.append(entityId) else: Logger.error("EnManager", "AddToTest() Error, with " + EntityManager.entities[ entityId.id].type + " entity adding two same id : " + str(entityId.id))
def status(): Logger.info("EnManager", "\n status with len(" + str(EntityManager.len) + ") :\n") for e in EntityManager.entities: Logger.info( "EnManager", "Entity" + str(e.entityId.id) + ", entityType" + e.type)
def addActive(eventIndex, entityId): if not entityId in EventManager.toActive[eventIndex]: EventManager.toActive[eventIndex].append(entityId) else: Logger.error( "EvManager", "Tow entities have the same ID " + str(eventIndex) + ", with id : " + str(entityId.id))
def rem(eventIndex, entityId): if entityId in EventManager.toActive[eventIndex]: EventManager.toActive[eventIndex].remove(entityId) else: Logger.error( "EvManager", "Unknown entity " + str(eventIndex) + ", with id : " + str(entityId.id))
def saveInputs(): InputsToSave = {"inputs": Config.inputs} with open(Config.KEYBOARD_CONFIG_PATH, 'w') as outfile: json.dump(InputsToSave, outfile, indent=" ") Logger.success("Config", "Key configuration file saved successfully !")
def unload(self, status=True): # Security when error with unloaded textures if self.correctLoaded: gl.glDeleteTextures(self.id) self.correctLoaded = False if status: Logger.info("Texture -", "Texture n°" + str(self.id) + " unloaded")
def removeToTest(entityId): if entityId in EntityManager.entitiesCol: EntityManager.entitiesCol.remove(entityId) else: Logger.error( "EnManager", "RemoveToTest() Error " + EntityManager.entities[entityId.id].type + " entity want to be remove from entityCol, id : " + str(entityId.id))
def addA(args): # Insert in args to define the entity the id with checkPlace args.insert(entitycollision.EntityCollision.ARGS_ID, EntityManager.checkPlace()) result = LoadEntity.instance(args) if result[0] == "True": EntityManager.addWithId(result[1]) else: # No error can append when un-resettable entity in the reset of the map can't be init a time again if not result[1] == "No Error": Logger.error("LoadEntity", str(result[1]) + "\n" + str(args))
def unload(): for key in TextureManager.textures: TextureManager.textures[key].unload() TextureManager.textures = {} # If there are still textures, the code will warn this if len(TextureManager.textures) > 0: Logger.error("TextureManager", "Error at the end of the program ->") TextureManager.state() else: Logger.info("TextureManager", "No remaining textures")
def setDisplayLayer(self, layer): if self.displayLayer != layer: # Delete the old id registered if the class was registered if not self.displayLayer == -1: self.em.removeToDipslay(self.displayLayer, self.entityId) # Security if layer >= 0 and layer <= 2: self.displayLayer = layer self.em.addToDisplay(self.displayLayer, self.entityId) else: Logger.error( "EnDrawable", "Invalid layer (" + str(layer) + ") for " + str(self.type) + " with id " + str(id))
def init(): Logger.info("GameManager", "Created") # Init systems TextureManager.init() TextManager.init() InputManager.init(Config.inputs) GameManager.cam = camera.Camera( 70.0, [0, 0, -2 ]) # FOV 70, Precise position of cam to render 18 * 12 tiles ShaderManager.init() GameManager.setCurrentScreen("menuscreen", [True]) GameManager.createCurrentScreen()
def init(): colorama.init() Logger.info("Game", "Started") print("") Config.load() Window.beginTime = time.time() # Initializing GLFW if not glfw.init(): Logger.error("GLFW", "Failed to init GLFW") exit() Window.create() # the window # Init game manager gm.GameManager.init()
def rem(info): id = info[0].id # Unload the entity EntityManager.entities[id].unload() del EntityManager.entities[id] EntityManager.len = len(EntityManager.entities) # Print the removing ? if info[1]: Logger.info("EnManager", "Remove entity n°" + str(id)) if id != len(EntityManager.entities): for i in range(id, EntityManager.len): EntityManager.entities[i].entityId.id -= 1
def isMap(zone, map, entry): path = "game/resources/map/" + zone + "/" + map + ".json" state = os.path.isfile(path) if not state: Logger.error( "MapLoading", "The map : " + str(map) + " in zone: " + str(zone) + " doesn't exists") return False else: value = json.load(open(path)) try: ok = value["entries"][str(entry)] return True except KeyError: Logger.error( "MapLoading", "The map : " + str(map) + " in zone: " + str(zone) + " has no entry point " + str(entry)) return False
def loop(): gl.glClearColor(0.05, 0.05, 0.05, 1.0) # Black color ticks = 0 frames = 0 frameTime = time.time_ns() secondTime = time.time_ns() lag = 0.0 # This clock system enticipate lags while not glfw.window_should_close(Window.window): lag += time.time_ns() - frameTime frameTime = time.time_ns() gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) # Clear the window if time.time_ns() - secondTime >= Window.SECOND: if Config.values["general"]["debug"]: glfw.set_window_title( Window.window, "Moteur jeu en python | FPS:" + str(frames) + "; TPS:" + str(ticks)) ticks = 0 frames = 0 secondTime = time.time_ns() while lag >= Window.TICK_TIME: gm.GameManager.update() # Update() lag -= Window.TICK_TIME ticks += 1 gm.GameManager.display() # Display() frames += 1 glfw.swap_buffers(Window.window) glfw.poll_events() Window.frame += 1 Logger.setFrame(Window.frame)
def loadServerConfig(): try: # Try to load the server configuration from file Config.server = json.load(open(Config.SERVER_CONFIG_PATH)) except json.decoder.JSONDecodeError: # If it fails, ask for overwrite (or it will use a default server configuration) Config.createDefaultServerConfig( Config.yes( Logger.format( "Config", "Failed to parse the server config file ! Do you want to recreate it and delete the old one ?" )))
def loadInputs(): try: # Try to load the keyboard configuration from file inputsFile = json.load(open(Config.KEYBOARD_CONFIG_PATH))['inputs'] Config.inputs = inputsFile except json.decoder.JSONDecodeError: # If it fails, ask for overwrite (or it will use a default keyboard configuration) Config.createDefaultInputs( Config.yes( Logger.format( "Config", "Failed to parse the key config file ! Do you want to recreate it and delete the old one ?" )))
def loadConfig(): try: # Try to load the configuration from file configFile = json.load(open(Config.MAIN_CONFIG_PATH))['config'] Config.values = configFile except json.decoder.JSONDecodeError: # If it fails, ask for overwrite (or it will use a default configuration) Config.createDefaultConfig( Config.yes( Logger.format( "Config", "Failed to parse the config file ! Do you want to recreate it and delete the old one ?" )))
def loadImage(self, image): try: # Open the image flippedImage = image.transpose(img.FLIP_TOP_BOTTOM) imgData = flippedImage.convert("RGBA").tobytes() self.width = image.width self.height = image.height # Upload to openGL try: self.id = gl.glGenTextures(1) self.bind() gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, self.width, self.height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, imgData) Logger.info( "Texture +", "Texture n°" + str(self.id) + " loaded (" + self.path.replace(self.PATH, '') + ")") self.correctLoaded = True except Exception as error: gl.glDeleteTextures(self.id) self.error(error) return False except Exception as error: self.error(error) return False
def checkServerConfig(): import os # Check if the "data" folder exists (and create it if necessary) path = Config.DATA_FOLDER if not (os.path.exists(path)) and not (os.path.isdir(path)): Logger.info("Config", "Creating '%s' folder..." % path) try: os.mkdir(path) Logger.success("Config", "Done !") except OSError: Logger.error("Config", "Creation of the directory %s failed" % path) exit() # Check if the server configuration file exists (and create it if necessary) path = Config.SERVER_CONFIG_PATH if not (os.path.exists(path)): Logger.info( "Config", "A configuration file needs to be created to connect to the server" ) Config.createDefaultServerConfig()
def createDefaultServerConfig(overwrite=True): if Config.yes( Logger.format( "Config", "Do you want to use the default server configuration ? ")): # We set default values for the server configuration Config.server = {"ip": "127.0.0.1", "port": 34141} else: # We ask for server configuration values Config.server = { "ip": input( "[1/2] What is the IP or the domain name of the server ? " ), "port": input( "[2/2] On which port runs the server (by default, 34141) ? " ) } # We overwrite the server configuration if needed if overwrite: Config.saveServerConfig()
def exit(): gm.GameManager.unload() glfw.terminate() print("") Logger.info("Game", "Closed") sys.exit()
def check(): import os # Check if the "data" folder exists (and create it if necessary) path = Config.DATA_FOLDER if not (os.path.exists(path)) and not (os.path.isdir(path)): Logger.info("Config", "Creating '%s' folder..." % path) try: os.mkdir(path) Logger.success("Config", "Done !") except OSError: Logger.error("Config", "Creation of the directory %s failed" % path) exit() # Check if the "data/config" folder exists (and create it if necessary) path = Config.DATA_FOLDER + "/config" if not (os.path.exists(path)) and not (os.path.isdir(path)): Logger.info("Config", "Creating '%s' folder..." % path) try: os.mkdir(path) Logger.success("Config", "Done !") except OSError: Logger.error("Config", "Creation of the directory %s failed" % path) exit() # Check if the main configuration file exists (and create it if necessary) path = Config.MAIN_CONFIG_PATH if not (os.path.exists(path)): Logger.info("Config", "Creating the user-specific configuration file...") Config.createDefaultConfig() # Check if the keyboard configuration file exists (and create it if necessary) path = Config.KEYBOARD_CONFIG_PATH if not (os.path.exists(path)): Logger.info( "Config", "Creating the user-specific key configuration file...") Config.createDefaultInputs()
def saveServerConfig(): with open(Config.SERVER_CONFIG_PATH, 'w') as outfile: json.dump(Config.server, outfile, indent=" ") Logger.success("Config", "Server configuration file saved successfully !")
def state(): Logger.info("TeManager", "Textures currently loaded :") print("=" * 45) for key in TextureManager.textures: print("Texture " + key) print("=" * 45)