Example #1
0
def loadGenericObj(filepath, extension=None):
    #includes fixing file extension and doing inheritence
    if filepath is None:
        return {FILE_EXTENSION: extension, CLASS_TYPE: DEFAULT_CLASS_TYPE}
    filepathstr = toStringPath(filepath)  #turn into string
    filepathlist = toListPath(filepath)  #make sure we have a list too
    if extension is not None and extension not in filepathstr:
        filepathstr += extension
    if filepathstr not in LoadedData:
        obj = load_object_no_class(filepathstr, False)
        if PROP_KEY in list(obj.keys()):
            if obj[PROP_KEY] == filepathlist[-1]:
                debugMessage(
                    "infinitely recursive prop detected! Did you use prop instead of type?"
                )
                debugMessage(filepathstr)
            else:
                obj = updateNestedDict(
                    loadGenericObj(filepathlist[:-1] + [obj[PROP_KEY]],
                                   extension), obj)
            obj.pop(PROP_KEY)
        obj = _load_object_add_class(obj, filepathstr)
        LoadedData[filepathstr] = copy.deepcopy(obj)
    else:
        obj = copy.deepcopy(LoadedData[filepathstr])
    return obj
Example #2
0
def playAudio(file_path=None,
              channel="special",
              thread_loading=True,
              loop=False,
              start=0,
              end=None,
              loop_start=0,
              fade_in=None,
              fade_out=None,
              crossfade=None,
              start_paused=False):
    try:
        file_handle = loadResource(file_path)
    except ResourceUnavailableError as e:
        debugMessage(e)
        debugMessage("Couldn't load resource: " + file_path)
    else:
        event_loop = getGameScheduler()
        _currently_playing.append(
            asyncio.create_task(
                _play_from_file(file_handle,
                                event_loop,
                                thread_loading=thread_loading,
                                loop=loop,
                                start=start,
                                end=end,
                                loop_start=loop_start,
                                fade_in=fade_in,
                                fade_out=fade_out,
                                crossfade=crossfade,
                                start_paused=start_paused)))
Example #3
0
 def _setGlowImage(self, image_path):
     try:
         self.set_image_from_buffer(self._GetGlowTexID(image_path),
                                    *self._CreateTexture(image_path))
     except ResourceUnavailableError:
         debugMessage(
             "Failure to create glow image. Might be due to current incompatibility with dynamic textures (ttf text, etc)."
         )
Example #4
0
 def setupContainer(self, objname):
     if hasattr(self, objname):
         self._ContainerObjs = [
             objname
         ] + self._ContainerObjs  #done this way instead of insert to make sure it's a new list
     else:
         debugMessage(
             "you misspelled the name of your attribute in a container, or it doesn't exist yet: "
             + objname)
Example #5
0
 def create_font_size(self, font_size):
     if self.path is not None:
         try:
             self.font_sizes[font_size] = ImageFont.truetype(
                 loadResource(self.path), font_size)
         except ResourceUnavailableError:
             debugMessage(
                 "WARNING: Could not create font size due to resource error: %s"
                 % self.path)
             raise ResourceUnavailableError
Example #6
0
 def getActorByIndex(self, actorindex, suppress_error=False):
     try:
         return self.actors[actorindex]
     except KeyError:
         if not (suppress_error or self.destroyed):
             debugMessage(
                 "actor not found in scene when queried by index: " +
                 str(actorindex))
             raise
         return None
Example #7
0
 def __getattr__(self, name):
     for obj in self._ContainerObjs:
         try:
             return getattr(getattr(self, obj), name)
         except AttributeError:
             pass
         except RuntimeError:  #infinite loop detected:
             self.removeContainer(obj)
             debugMessage("Infinite loop detected in container. " + obj +
                          " key removed.")
     raise AttributeError("Attribute not found: " + name)
Example #8
0
def init():
    event.addGameCloseListener(close)

    if checkDebugOn():
        debugMessage("WARNING: Launching in debug mode")

    #setup main window and initialize drivers
    setupWindowBasic("logo.png")

    setupDrivers()
    
    initGamestate()

    initializeGameFrames(main_loop)
Example #9
0
 def updateCameraSprites(self):
     x = self.getX()
     y = self.getY()
     if self._oldx != x or self._oldy != y:
         for key, sprite in list(self.camera_sprites.items()): #cast to list so we can remove keys if there's an exception
             try:
                 sprite().updateWithCamera(x,y)
                 #method(sprite(), x, y)
             except Exception as e:
                 debugMessage(e)
                 debugMessage("Camera sprite update function broke. Removed object that was following the camera? deleting")
                 self.removeCameraSprite(key)
         self._oldx = x
         self._oldy = y
Example #10
0
def runDelayedEvents():
    global _currently_running_events
    _currently_running_events = True
    for priority, data in list(_delayed_events.items()): #listified to prevent errors when undelaying things in a delayed action
        for key, val in list(data.items()):
            listener, args, kwargs, ID = val
            try:
                listener(*args, **kwargs)
            except:
                import traceback
                from kaiengine.debug import debugMessage
                debugMessage("Error in delayed event.")
                traceback.print_exc()
    _removeAllDelayEvents()
    _currently_running_events = False
Example #11
0
 def setFocus(self, child):
     #pass None to clear focus
     try:
         ID = child.id
     except AttributeError:
         ID = child
     if ID != self._focused_child_id:
         oldfocus = self.getFocusedChild()
         if oldfocus:
             oldfocus._loseFocus()
         self._focused_child_id = ID
         if ID is not None:
             if ID in self._children:
                 self.getChild(ID)._gainFocus()
             else:
                 debugMessage("Probable error: child ID not found when setting focus: " + str(ID))
                 self._focused_child_id = None
Example #12
0
def _realtimeEventRun(event, *args, **kwargs):
    try:
        event.listener(getGameScheduler().time() - event.scheduler_time, *args,
                       **kwargs)
    except:
        from kaiengine.debug import debugMessage
        import traceback
        debugMessage(
            "Something broke with a scheduled realtime listener; deleting it.")
        traceback.print_exc()
        event.repeating = False  #stop it from repeating
    _cleanupRealtimeScheduledEvent(event.eventid)
    if not event._destroyed:
        if event.repeating:
            _scheduleRealtimeWithEvent(event, *args, **kwargs)
        else:
            _destroyRealtimeEvent(event.eventid)
Example #13
0
def setupWindow(fullscreen=None, x=None, y=None, fake_fullscreen=None):
    from . import settings
    #initial setup of the main window
    if fake_fullscreen is None:
        try:
            fake_fullscreen = settings.getValue(
                DYNAMIC_SETTINGS_FAKE_FULLSCREEN)
        except:
            pass
    if fake_fullscreen:
        x, y = sGraphics.getScreenResolution()
        try:
            multiplier = x / settings.getValue(
                DYNAMIC_SETTINGS_WINDOW_DIMENSIONS)[0]
            ymultiplier = y / settings.getValue(
                DYNAMIC_SETTINGS_WINDOW_DIMENSIONS)[1]
            if multiplier != ymultiplier:
                debugMessage(
                    "WARNING: screen aspect ratio does not match for fake fullscreen! Setting to lower of possible values to avoid cutoff."
                )
                multiplier = min(multiplier, ymultiplier)
        except:
            debugMessage(
                "WARNING: Error calculating multiplier for fake fullscreen (also check DYAMIC_SETTINGS_WINDOW_DIMENSIONS):\nWidth {0}\nHeight{1}"
                .format(x, y))
            multiplier = 1
        setGlobalScaling(multiplier)
        settings.setValue(DYNAMIC_SETTINGS_GLOBAL_SCALING, multiplier)
        sGraphics.graphicsInitWindow(
            main_window(x, y, None, fake_fullscreen=True))

        #TODO: location to correct one for 2nd monitors, etc
        getWindow().set_location(0, 0)
    else:
        if x is None:
            x = int(
                settings.getValue(DYNAMIC_SETTINGS_WINDOW_DIMENSIONS)[0] *
                settings.getValue(DYNAMIC_SETTINGS_GLOBAL_SCALING))
        if y is None:
            y = int(
                settings.getValue(DYNAMIC_SETTINGS_WINDOW_DIMENSIONS)[1] *
                settings.getValue(DYNAMIC_SETTINGS_GLOBAL_SCALING))
        if fullscreen is None:
            fullscreen = settings.getValue(DYNAMIC_SETTINGS_FULLSCREEN)
        sGraphics.graphicsInitWindow(main_window(x, y, fullscreen))
Example #14
0
 def add_font(self, font_path, font_size=None):
     font_path = fontglobals.getFontPath(font_path)
     if font_path not in self.fonts:
         if TTF_EXTENSION == os.path.splitext(font_path)[1]:
             if font_size is None:
                 font_size = MENU_TEXT_SIZE
             self.fonts[font_path] = TTFFont(font_path, font_size)
             return
         if GRAPHIC_FONT_EXTENSION == os.path.splitext(font_path)[1]:
             self.fonts[font_path] = GraphicFont(font_path)
             return
         if GRAPHIC_FONT_2_EXTENSION == os.path.splitext(font_path)[1]:
             self.fonts[font_path] = GraphicFont2(font_path)
             return
         if GRAPHIC_FONT_3_EXTENSION == os.path.splitext(font_path)[1]:
             self.fonts[font_path] = GraphicFont3(font_path)
             return
         debugMessage("Font not found: " + font_path)
         debugMessage("Did you remember to include the extension?")
Example #15
0
 def setAnimation(self, anikey = None, reset = True, default = None, starting_time = 0.0):
     if anikey is None:
         anikey = self.default_ani
     if anikey in self.animations:
         self._set_animation(anikey, reset, starting_time)
     else:
         errorstring = ""
         if default is None: #suppress printing this error if a default was defined
             errorstring = str(anikey) + " animation key not found. "
         if default is False: #passing a false will skip changing the animation at all
             return
         else:
             default = self.default_ani
         if default in self.animations:
             self._set_animation(default,reset, starting_time)
         else:
             errorstring += "Moreover, default key " + str(default) + " not found."
         if errorstring:
             debugMessage(errorstring)
Example #16
0
def dumpScreenshot(screenshotPath=None, screenshotDir=None):
    """Take a screenshot and save it to a specified or default path."""
    originalDir = os.getcwd()
    try:
        screenshot = takeScreenshot()
        if screenshotDir is not None:
            os.chdir(screenshotDir)
        if screenshotPath is None:
            index = 1
            while os.path.exists("screenshot%05i.png" % index):
                index += 1
            screenshotPath = "screenshot%05i.png" % index
        try:
            screenshot.save(screenshotPath)
        except IOError as e:
            debugMessage("Screenshot I/O error({0}): {1}".format(
                e.errno, e.strerror))
    finally:
        os.chdir(originalDir)
Example #17
0
def init():
    event.addGameCloseListener(close)

    if checkDebugOn():
        debugMessage("WARNING: Launching in debug mode")
    setupWindowBasic("logo.png")

    setupDrivers()
    keyevents.InitKeys()
    AGE.InitGame()

    AGE.SetMapDimensions(40, 40)
    AGE.SetTile([10, 0], GRASS_LAYER, 0, 0, 40, 40, COLOR_GREEN,
                COLOR_DARK_GREEN)  # fill with grass
    AGE.InstantFadeIn()

    gamestate.glob.init()
    #AGE.SetBackgroundColor(COLOR_DARK_GREEN)

    initializeGameFrames(main_loop)
Example #18
0
def createGraphic(path, layer=-1, *args, **kwargs):
    #generic loader for all graphic types
    if path is None:
        return createSprite(path, layer, *args, **kwargs)
    path = toStringPath(path)
    ext = os.path.splitext(path)[1]
    if ext == PNG_EXTENSION:
        return createSprite(path, layer, *args, **kwargs)
    if ext == GRAPHIC_OBJECT_EXTENSION:
        return createGraphicObject(path, layer, *args, **kwargs)
    if ext == LABEL_OBJECT_EXTENSION:
        return createLabelObject(path, layer, *args, **kwargs)
    if ext == BORDERED_SPRITE_EXTENSION:
        return createBorderedSprite(path, layer, *args, **kwargs)
    if ext == MULTI_SPRITE_EXTENSION:
        return createMultiSprite(path, layer, *args, **kwargs)
    debugMessage("graphic of unsupported format: " + path)
    if len(ext) == 0:
        debugMessage("You forgot to include the extension, methinks")
    return None
Example #19
0
def findClasses(classdict, packname, defaultclass):
    if not classdict:
        try:
            pack = loadPackage(packname)
        except Exception as e:
            import traceback
            traceback.print_stack()
            debugMessage(e)
            return None
        #debugMessage(pack.__dict__)
        #debugMessage(os.listdir(pack.__path__[0]))
        classdict[DEFAULT_CLASS_TYPE] = defaultclass
        for importer, modname, ispkg in pkgutil.iter_modules(pack.__path__, pack.__package__ + "."):
            mod = importlib.import_module(modname, ".")
            if mod and hasMainClass(mod):
                try:
                    classdict[mod.MainClass.type] = mod.MainClass
                except AttributeError:
                    #hackish way to get rid of the package name from __name__ but oh well
                    classdict[os.path.splitext(mod.__name__)[1][1:]] = mod.MainClass
    return classdict
Example #20
0
 def call_listener(self, *args, **kwargs):
     try:
         return self.listener(*args, **kwargs)
     except Exception as e:
         debugMessage(traceback.format_exc())
         debugMessage("something broke with an event listener; deleting it")
         debugMessage(e)
         self.delete_me = True
Example #21
0
 def saveToFile(self):
     try:
         serialized = self._altered_values
         jsondumps(serialized)
     except Exception as e:
         from kaiengine.debug import debugMessage
         debugMessage("Settings serialization error:")
         debugMessage(e)
     else:
         try:
             jsondump(serialized, toStringPath(self.getFullFilepath()))
         except Exception as e:
             from kaiengine.debug import debugMessage
             debugMessage("Settings file save error:")
             debugMessage(e)
Example #22
0
 def endHangTime(self):
     self.unschedule(self.endHangTime)
     scene_type = None
     args = None
     kwargs = None
     while scene_type is None:
         try:
             data = self._next_scenes.pop(0)
         except IndexError:
             break
         try:
             scene_type, args, kwargs = data
         except ValueError:
             from kaiengine.debug import debugMessage
             debugMessage(
                 "Cannot unpack scene data. Requires 3 arguments (scene_type, args, kwargs)."
             )
             debugMessage(data)
     if scene_type is None:
         self.fadeToPreviousScene(self._fade_out_time)
     else:
         kwargs["next_scenes"] = self._next_scenes
         self.fadeToScene(scene_type, self._fade_out_time, True, args,
                          kwargs)
Example #23
0
def finishAnimationCapture(savePath=None):
    """Complete animation capture and save frames to disk."""
    global screenshot_data
    unschedule(_captureAnimation)  #unschedule if needed
    if not screenshot_data:  #check if we don't have any available capture data
        return

    if savePath is None:
        index = 1
        while os.path.exists("animation%05i.gif" % index):
            index += 1
        savePath = "animation%05i.gif" % index

    try:
        screenshot_data[0].save(savePath,
                                save_all=True,
                                append_images=screenshot_data[1:],
                                loop=0,
                                duration=25)
    except IOError as e:
        debugMessage("Animation I/O error({0}): {1}".format(
            e.errno, e.strerror))

    screenshot_data = []
Example #24
0
 def loadActors(self):
     for actordict in self.actor_list:
         try:
             newactor = self.getActorFactory(actordict)(actordict.pop(
                 ACTOR_TYPE, None), self)
             pos = actordict.pop(ACTOR_POS)
             self.addActor(newactor)
             newactor.setPos(*pos)
             newsprite = actordict.pop(ACTOR_SPRITE, None)
             if newsprite != "" and newsprite != None:
                 newactor.setSprite(newsprite)
             newactor.setExtraData(actordict)
         except Exception as e:
             debugMessage("Failed to create map actor!")
             debugMessage(e)
             debugMessage(actordict)
Example #25
0
 def loadTilemap(self):
     self.clearMapTiles()
     for tile in self.tile_data_list:
         try:
             pos = tuple(tile[MAPTILE_POS])
             self.tile_data_map[pos] = self.createMapTileData(
                 maptile_data=tile)
         except KeyError:
             debugMessage("Map tile data lacked position.")
             debugMessage(str(tile))
     for layer, tilelist in self.tile_graphic_dict.items():
         layer = int(layer)  #since probably a string
         for tile in tilelist:
             try:
                 pos = tuple(tile[MAPTILE_POS])
                 tilechild = self.addChild(
                     self.createMapTileGraphic(maptile_data=tile), False)
                 self.tile_graphics_map[layer][pos] = tilechild.id
                 tilechild.setElementPosition(pos[0] * self.tile_width,
                                              pos[1] * self.tile_height)
             except KeyError:
                 debugMessage("Map tile graphic lacked position.")
                 debugMessage(str(tile))
Example #26
0
 def call_listener(self):
     if self._unscheduled:
         self.delete_me = True
         return
     if self.paused:
         return
     try:
         if self.listener(*self.args, **self.kwargs):
             self.delete_me = True
     except Exception as e:
         from kaiengine.debug import debugMessage
         debugMessage(traceback.format_exc())
         debugMessage(
             "something broke with a scheduled listener; deleting it")
         debugMessage(e)
         self.delete_me = True
     if not self.repeating:
         self.delete_me = True
Example #27
0
SHADERS_AVAILABLE = True

try:
    base_vertex_shader = shaders.compileShader(BASE_VERTEX_SHADER,
                                               GL_VERTEX_SHADER)
    base_screen_vertex_shader = shaders.compileShader(BASE_SVERTEX_SHADER,
                                                      GL_VERTEX_SHADER)
    overlay_vert = shaders.compileShader(OVERTEX_SHADER, GL_VERTEX_SHADER)

    base_fragment_shader = shaders.compileShader(BASE_FRAG_SHADER,
                                                 GL_FRAGMENT_SHADER)
    base_post_shader = shaders.compileShader(BASE_SFRAG_SHADER,
                                             GL_FRAGMENT_SHADER)
    overlay_frag = shaders.compileShader(OFRAG_SHADER, GL_FRAGMENT_SHADER)
except RuntimeError:
    debugMessage("WARNING: OpenGL 3.0 not supported; trying fallback shaders")
    SHADERS_AVAILABLE = False

    base_vertex_shader = shaders.compileShader(COMPAT_VERT_SHADER,
                                               GL_VERTEX_SHADER)
    base_screen_vertex_shader = shaders.compileShader(COMPAT_SVERT_SHADER,
                                                      GL_VERTEX_SHADER)
    overlay_vert = shaders.compileShader(COMPAT_OVERTEX_SHADER,
                                         GL_VERTEX_SHADER)

    base_fragment_shader = shaders.compileShader(COMPAT_FRAG_SHADER,
                                                 GL_FRAGMENT_SHADER)
    base_post_shader = shaders.compileShader(COMPAT_SFRAG_SHADER,
                                             GL_FRAGMENT_SHADER)
    overlay_frag = shaders.compileShader(COMPAT_OFRAG_SHADER,
                                         GL_FRAGMENT_SHADER)
Example #28
0
 def text_to_image_buffer(self, text, font_size):
     debugMessage(
         "text_to_image_buffer not supported for graphical fonts. Path: " +
         str(self.path) + "; returning None")
     return 0, 0, None
Example #29
0
 def requestOwnRemoval(self):
     try:
         self.getParent().removeChild(self.id)
     except AttributeError:
         debugMessage("Top-level element tried to request own removal:\n  {}\n  {}".format(self.id, str(self)))
Example #30
0
 def destroyed(self, val):
     debugMessage(
         "destroyed cannot be set outside of the destroy() method.")