Example #1
0
def getResource(name, binary=False):
    """
    Attempts to retrieve the bytes of the given resource. If multiple packages
    contain the resource, the copy in the alphabetically latest package is
    returned. Returns C{None} if the given resource is not known by any package.

    @param name: The path + filename of the resource to retrieve.
    @type name: C{str}
    
    @param binary: If C{True}, then an attempt will be made to open the resource
    in binary mode. This probably only has an effect if the file is in a
    directory package. Resources from archive packages are always binary.
    @type binary: C{bool}
    
    @return: C{str} or C{None}
    """
    # see if we've already loaded this resource
    if name in __resTable:
        return __resTable[name]

    # we need to load it
    parole.info('Loading resource: "%s"', name)
    bytes = None

    # go through all packages until we find one with the resource
    # we need. The packages list should already be in the proper order
    for (package, f, g) in packages:
        try:
            bytes = __getResourceFrom(name, package, binary)
            parole.debug('"%s" found in "%s"', name, package)
            break
        except __NotFound, e:
            parole.debug('"%s" not found in "%s"', name, package)
Example #2
0
def getShader(scriptName):
    """
    Attempts to retrieve a L{Shader} object resource. 
    
    @param scriptName: 
    Should name a resource that is a python script. The script should, upon
    execution, create a global (to itself) object C{theShader}, which is
    expected to be an instance of L{Shader}. This object is what is retrieved
    and cached by this function.
    @type scriptName: C{str}

    @return: L{Shader} or C{None}
    """
    # Return any cached copy of the desired shader object
    if (scriptName, 'theShader') in __resTable:
        return __resTable[(scriptName, 'theShader')]

    parole.info('Loading shader "%s"', scriptName)

    theShader = getObject(scriptName, 'theShader')
    if theShader and not isinstance(theShader, parole.Shader):
        parole.error(
            'Shader definition script bound "theShader" to non-Shader')
        return None

    # The shader definition worked and we have a bona fide Shader object
    # getObject should have already cached it
    return theShader
Example #3
0
def getResource(name, binary=False):
    """
    Attempts to retrieve the bytes of the given resource. If multiple packages
    contain the resource, the copy in the alphabetically latest package is
    returned. Returns C{None} if the given resource is not known by any package.

    @param name: The path + filename of the resource to retrieve.
    @type name: C{str}
    
    @param binary: If C{True}, then an attempt will be made to open the resource
    in binary mode. This probably only has an effect if the file is in a
    directory package. Resources from archive packages are always binary.
    @type binary: C{bool}
    
    @return: C{str} or C{None}
    """
    # see if we've already loaded this resource
    if name in __resTable:
        return __resTable[name]

    # we need to load it
    parole.info('Loading resource: "%s"', name)
    bytes = None

    # go through all packages until we find one with the resource
    # we need. The packages list should already be in the proper order
    for (package, f, g) in packages:
        try:
            bytes = __getResourceFrom(name, package, binary)
            parole.debug('"%s" found in "%s"', name, package)
            break
        except __NotFound, e:
            parole.debug('"%s" not found in "%s"', name, package)
Example #4
0
def getSound(name):
    """
    Attempts to retrieve the given sound resource as a PyGame C{Sound} object.
    The file can either be an uncompressed WAV or an OGG file.

    @return: C{pygame.mixer.Sound} or C{None}

    @param name: The path + filename of the sound resource to retrieve. 
    @type name: C{str}
    """
    # Return any cached copy of the texture surface object
    if name in __resTable:
        return __resTable[name]

    parole.info('Loading sound "%s"', name)

    # name should be a resource whose bytes are loadable by pygame's mixer
    # module
    bytes = getResource(name, binary=True)
    if not bytes:
        return None

    sound = None

    # Create a file-like object which pygame can use to read the bytes of
    # the sound
    soundf = cStringIO.StringIO(bytes)

    # Attempt to load the sound
    try:
        sound = pygame.mixer.Sound(soundf)
    except Exception, e:
        parole.error('Unable to load sound "%s": %s', name, e)
        return None
Example #5
0
def getSound(name):
    """
    Attempts to retrieve the given sound resource as a PyGame C{Sound} object.
    The file can either be an uncompressed WAV or an OGG file.

    @return: C{pygame.mixer.Sound} or C{None}

    @param name: The path + filename of the sound resource to retrieve. 
    @type name: C{str}
    """
    # Return any cached copy of the texture surface object
    if name in __resTable:
        return __resTable[name]

    parole.info('Loading sound "%s"', name)

    # name should be a resource whose bytes are loadable by pygame's mixer
    # module
    bytes = getResource(name, binary=True)
    if not bytes:
        return None

    sound = None

    # Create a file-like object which pygame can use to read the bytes of
    # the sound
    soundf = cStringIO.StringIO(bytes)

    # Attempt to load the sound
    try:
        sound = pygame.mixer.Sound(soundf)
    except Exception, e:
        parole.error('Unable to load sound "%s": %s', name, e)
        return None
Example #6
0
def __init():
    """
    Initializes the resource module. Detects and loads all resource pakcages 
    in the gamedir directory. Automatically called during engine 
    startup -- user code shouldn't need to use this function.
    """
    global __gameDir, __inInit
    __inInit = True
    __resTable.clear()

    parole.conf.notify(__onConfigChange, True)
    __gameDir = parole.conf.resource.gamedir

    # Score some packages
    while len(packages):
        packages.pop()
    suff = parole.conf.resource.packsuffix
    for root, dirs, files in os.walk(__gameDir):
        if root == __gameDir:
            if bool(parole.conf.resource.allowdirs):
                packages.extend([(dir, None, __getResourceFromDir) for dir in dirs if dir.endswith(suff)])
            for arch in files:
                if not arch.endswith(suff):
                    continue
                if not zipfile.is_zipfile(os.sep.join([__gameDir, arch])):
                    parole.error("Ignoring bad archive resource package: %s: Not dir or zip.", arch)
                    continue
                # archf = None
                try:
                    archf = zipfile.ZipFile(os.sep.join([__gameDir, arch]), "r")
                    parole.info("archf = %r", archf)
                except Exception, e:
                    parole.error("Ignoring bad archive resource package: %s: %s", arch, e)
                    continue
                packages.append((arch, archf, __getResourceFromArch))
Example #7
0
def getShader(scriptName):
    """
    Attempts to retrieve a L{Shader} object resource. 
    
    @param scriptName: 
    Should name a resource that is a python script. The script should, upon
    execution, create a global (to itself) object C{theShader}, which is
    expected to be an instance of L{Shader}. This object is what is retrieved
    and cached by this function.
    @type scriptName: C{str}

    @return: L{Shader} or C{None}
    """
    # Return any cached copy of the desired shader object
    if (scriptName, "theShader") in __resTable:
        return __resTable[(scriptName, "theShader")]

    parole.info('Loading shader "%s"', scriptName)

    theShader = getObject(scriptName, "theShader")
    if theShader and not isinstance(theShader, parole.Shader):
        parole.error('Shader definition script bound "theShader" to non-Shader')
        return None

    # The shader definition worked and we have a bona fide Shader object
    # getObject should have already cached it
    return theShader
Example #8
0
 def toggleActive(self):
     """
     Toggles whether the console is visible and accepting input.
     """
     if not self.active:
         display.scene.add(self)
         parole.pushUIEventHandler((self.cmdMap, self.readLine))
         self.active = True
         parole.info('Console activated.')
     else:
         display.scene.remove(self)
         parole.popUIEventHandler()
         self.active = False
         parole.info('Console deactivated.')
Example #9
0
 def toggleActive(self):
     """
     Toggles whether the console is visible and accepting input.
     """
     if not self.active:
         display.scene.add(self)
         parole.pushUIEventHandler((self.cmdMap, self.readLine))
         self.active = True
         parole.info('Console activated.')
     else:
         display.scene.remove(self)
         parole.popUIEventHandler()
         self.active = False
         parole.info('Console deactivated.')
Example #10
0
File: base.py Project: gdos/parole
def __unloadModules(modules):
    # give modules a chance to clean up, unregister for events, config
    # notifications, etc.
    parole.info('Unloading modules: %s', ', '.join(modules))
    if 'resource' in modules:   
        parole.resource.__unload()
    if 'input' in modules:      
        parole.input.__unload()
    if 'display' in modules:    
        parole.display.__unload()
    if 'shader' in modules:     
        parole.shader.__unload()
    if 'console' in modules:    
        parole.console.__unload()
    if 'map' in modules:
        parole.map.__unload()
Example #11
0
def clearResource(name):
    """
    Clears the cache of the given resource. Any future retrieval of the 
    resource will result in an actual disk read. The resource may not actually
    be freed from memory if any user code still contains references to it.
    Furthermore, it won't actually be freed until the next sweep of Python's
    garbage collector.

    @param name: The path + filename of the resource to clear from the cache.
    @type name: C{str}
    """
    parole.info("Clearing resource: %s", name)
    if name in __resTable:
        del __resTable[name]
    else:
        parole.warn("Can't clear unknown resource: %s", name)
Example #12
0
def __unloadModules(modules):
    # give modules a chance to clean up, unregister for events, config
    # notifications, etc.
    parole.info('Unloading modules: %s', ', '.join(modules))
    if 'resource' in modules:
        parole.resource.__unload()
    if 'input' in modules:
        parole.input.__unload()
    if 'display' in modules:
        parole.display.__unload()
    if 'shader' in modules:
        parole.shader.__unload()
    if 'console' in modules:
        parole.console.__unload()
    if 'map' in modules:
        parole.map.__unload()
Example #13
0
def clearResource(name):
    """
    Clears the cache of the given resource. Any future retrieval of the 
    resource will result in an actual disk read. The resource may not actually
    be freed from memory if any user code still contains references to it.
    Furthermore, it won't actually be freed until the next sweep of Python's
    garbage collector.

    @param name: The path + filename of the resource to clear from the cache.
    @type name: C{str}
    """
    parole.info('Clearing resource: %s', name)
    if name in __resTable:
        del __resTable[name]
    else:
        parole.warn("Can't clear unknown resource: %s", name)
Example #14
0
def getFont(name, size):
    """
    Attempts to retrieve the given font resource as a PyGame Font object.

    @return: C{pygame.font.Font} or C{None}

    @param name: The path + filename of the font resource to retrieve. Must name
    a font file in a format that PyGame can read (e.g., TrueType).
    @type name: C{str}
    """
    # Return any cached copy of the font object
    if (name, size) in __resTable:
        return __resTable[(name, size)]

    parole.info('Loading font "%s" %spt', name, size)

    # name should be a resource whose bytes are loadable by pygame's font
    # module
    bytes = getResource(name, binary=True)
    if not bytes:
        parole.error('"%s" names an empty font resource.', name)
        return None

    parole.debug("Got font bytes. (len=%d)", len(bytes))
    font = None

    # Create a file-like object which pygame can use to read the bytes of
    # the font file
    # pygame 1.9.1release segfaults when reading a font from cStringIO
    # fontf = cStringIO.StringIO(bytes)
    # Workaround:
    import tempfile

    tmpf = tempfile.NamedTemporaryFile(delete=False)
    tmpf.write(bytes)
    tmpf.close()
    fontf = tmpf.name

    # Attempt to load the font
    try:
        parole.debug("Parsing font bytes...")
        font = pygame.font.Font(fontf, size)
    except Exception, e:
        parole.error('Unable to load font "%s" %pt: %s', name, size, e)
        return None
Example #15
0
def getFont(name, size):
    """
    Attempts to retrieve the given font resource as a PyGame Font object.

    @return: C{pygame.font.Font} or C{None}

    @param name: The path + filename of the font resource to retrieve. Must name
    a font file in a format that PyGame can read (e.g., TrueType).
    @type name: C{str}
    """
    # Return any cached copy of the font object
    if (name, size) in __resTable:
        return __resTable[(name, size)]

    parole.info('Loading font "%s" %spt', name, size)

    # name should be a resource whose bytes are loadable by pygame's font
    # module
    bytes = getResource(name, binary=True)
    if not bytes:
        parole.error('"%s" names an empty font resource.', name)
        return None

    parole.debug('Got font bytes. (len=%d)', len(bytes))
    font = None

    # Create a file-like object which pygame can use to read the bytes of
    # the font file
    # pygame 1.9.1release segfaults when reading a font from cStringIO
    #fontf = cStringIO.StringIO(bytes)
    # Workaround:
    import tempfile
    tmpf = tempfile.NamedTemporaryFile(delete=False)
    tmpf.write(bytes)
    tmpf.close()
    fontf = tmpf.name

    # Attempt to load the font
    try:
        parole.debug('Parsing font bytes...')
        font = pygame.font.Font(fontf, size)
    except Exception, e:
        parole.error('Unable to load font "%s" %pt: %s', name, size, e)
        return None
Example #16
0
def getModule(name, addToSysModules=True):
    """
    Loads a script resource and returns it as a module object.

    @param name:
    Should name a resource that is a python 
    script. The script will be loaded and executed, and a new module object will
    be constructed from its global namespace.
    @type name: C{str}

    @param addToSysModules:
    If C{True}, the loaded module will also be added to C{sys.modules}, as if
    it were truly imported.
    @type addToSysModules: C{bool}

    @return: C{module}. The module's name will be derived from that of the script
    resource, with directories corresponding to packages. For example,
    C{"scripts/util.py"} results in a module called C{"scripts.util"}.
    """
    # Return any cached copy of the desired object
    if name in __resTable:
        return __resTable[name]

    modName = name.replace(".py", "").replace("/", ".")
    parole.info('Loading script "%s" as module %s...', name, modName)

    scriptNamespace = __runScript(name)

    # set up the module object
    moduleObj = imp.new_module(modName)
    moduleObj.__dict__.update(scriptNamespace)

    # The script worked and we have a bona fide module
    # Cache it and return it
    __resTable[name] = moduleObj

    # add to sys.modules if requested
    if addToSysModules:
        if moduleObj not in sys.modules:
            sys.modules[moduleObj.__name__] = moduleObj

    return moduleObj
Example #17
0
def getModule(name, addToSysModules=True):
    """
    Loads a script resource and returns it as a module object.

    @param name:
    Should name a resource that is a python 
    script. The script will be loaded and executed, and a new module object will
    be constructed from its global namespace.
    @type name: C{str}

    @param addToSysModules:
    If C{True}, the loaded module will also be added to C{sys.modules}, as if
    it were truly imported.
    @type addToSysModules: C{bool}

    @return: C{module}. The module's name will be derived from that of the script
    resource, with directories corresponding to packages. For example,
    C{"scripts/util.py"} results in a module called C{"scripts.util"}.
    """
    # Return any cached copy of the desired object
    if name in __resTable:
        return __resTable[name]

    modName = name.replace('.py', '').replace('/', '.')
    parole.info('Loading script "%s" as module %s...', name, modName)

    scriptNamespace = __runScript(name)

    # set up the module object
    moduleObj = imp.new_module(modName)
    moduleObj.__dict__.update(scriptNamespace)

    # The script worked and we have a bona fide module
    # Cache it and return it
    __resTable[name] = moduleObj

    # add to sys.modules if requested
    if addToSysModules:
        if moduleObj not in sys.modules:
            sys.modules[moduleObj.__name__] = moduleObj

    return moduleObj
Example #18
0
def __onConfigChange(conf):
    global consoleKey, ps1, ps2, font, lowerbound, conShader, historyFile, \
        logFile

    parole.info('Console key: %s', conf.console.consoleKey)
    consoleKey = conf.console.consoleKey

    parole.info('Console PS1: "%s"', conf.console.ps1)
    if frame:
        frame.ps1 = conf.console.ps1

    parole.info('Console PS2: "%s"', conf.console.ps2)
    if frame:
        frame.ps2 = conf.console.ps2

    parole.info('Console history file: "%s"', conf.console.historyFile)
    historyFile = conf.console.historyFile

    parole.info('Console log file: "%s"', conf.console.logFile)
    logFile = conf.console.logFile
Example #19
0
File: main.py Project: gdos/parole
def updateFunc():
    parole.info('Game code started!')

    # Display a message in a box
    m = messageBox("You have a working skeleton game.\nYou may begin to "
                   "customize it.\nPress 'q' to quit, or '~' for the\n"
                   "interactive console")
    yield

    # Wait for the user to press 'q'
    # Use peekKeyPresses() instead of getKeyPresses() so that we don't steal
    # keypresses from the console, in case the user activates it.
    while 'q' not in parole.input.peekKeyPresses():
        yield

    # remove our message box from the display
    parole.display.scene.remove(m)

    # quit
    raise parole.ParoleShutdown
Example #20
0
def __onConfigChange(conf):
    global consoleKey, ps1, ps2, font, lowerbound, conShader, historyFile, \
        logFile

    parole.info('Console key: %s', conf.console.consoleKey)
    consoleKey = conf.console.consoleKey

    parole.info('Console PS1: "%s"', conf.console.ps1)
    if frame:
        frame.ps1 = conf.console.ps1

    parole.info('Console PS2: "%s"', conf.console.ps2)
    if frame:
        frame.ps2 = conf.console.ps2

    parole.info('Console history file: "%s"', conf.console.historyFile)
    historyFile = conf.console.historyFile

    parole.info('Console log file: "%s"', conf.console.logFile)
    logFile = conf.console.logFile
Example #21
0
def __setMode():
    global __modeDirty, __displaySurf, __workSurf, __lastDepth, __clearedSurf
    __modeDirty = False
    resolution = (int(parole.conf.display.width), int(parole.conf.display.height))
    fs = bool(parole.conf.display.fullscreen)
    hw = bool(parole.conf.display.hwaccel)
    depth = parole.conf.display.depth
    if depth not in __validDepths:
        error("Bad value for display.depth: %s. Should be one of %s.", depth, ", ".join(__validDepths))
        depth = __lastDepth
    else:
        __lastDepth = depth

    flags = 0
    if fs:
        flags |= pygame.FULLSCREEN

    if hw:
        flags |= pygame.HWSURFACE
        flags |= pygame.DOUBLEBUF

    parole.debug("Creating display surface...")
    __displaySurf = pygame.display.set_mode(resolution, flags, depth)
    parole.debug("... bingo!")
    # __clearedSurf = pygame.Surface(resolution).convert_alpha()
    # clearSurface(__clearedSurf, __clearedSurf.get_rect())

    if hw:
        __workSurf = pygame.Surface(resolution, pygame.SWSURFACE, __displaySurf)
    else:
        __workSurf = None

    parole.info(
        "New mode: %s %s %sx%sx%s",
        hw and "HW" or "SW",
        fs and "Fullscreen" or "Window",
        resolution[0],
        resolution[1],
        depth,
    )
Example #22
0
def __init():
    """
    Initializes the resource module. Detects and loads all resource pakcages 
    in the gamedir directory. Automatically called during engine 
    startup -- user code shouldn't need to use this function.
    """
    global __gameDir, __inInit
    __inInit = True
    __resTable.clear()

    parole.conf.notify(__onConfigChange, True)
    __gameDir = parole.conf.resource.gamedir

    # Score some packages
    while len(packages):
        packages.pop()
    suff = parole.conf.resource.packsuffix
    for root, dirs, files in os.walk(__gameDir):
        if root == __gameDir:
            if bool(parole.conf.resource.allowdirs):
                packages.extend([(dir, None, __getResourceFromDir) \
                        for dir in dirs if dir.endswith(suff)])
            for arch in files:
                if not arch.endswith(suff): continue
                if not zipfile.is_zipfile(os.sep.join([__gameDir, arch])):
                    parole.error(
                        'Ignoring bad archive resource package: %s: Not dir or zip.',
                        arch)
                    continue
                #archf = None
                try:
                    archf = zipfile.ZipFile(os.sep.join([__gameDir, arch]),
                                            'r')
                    parole.info('archf = %r', archf)
                except Exception, e:
                    parole.error(
                        'Ignoring bad archive resource package: %s: %s', arch,
                        e)
                    continue
                packages.append((arch, archf, __getResourceFromArch))
Example #23
0
def exportResource(name, destination):
    """
    Exports the named resource to the given destination on disk.
    C{destination} should be the full path plus filname to which the
    byte-contents of the named resource should be copied.

    This function can be useful for extracting a sound resource from a zip
    package and writing it to disk as a standalone file so that
    it can be used by C{pygame.mixer.music}, for instance.
    """
    parole.info('Exporting resource "%s" to "%s".', name, destination)

    bytes = getResource(name, binary=True)
    if not bytes:
        parole.error('exportResource: resource "%s" not found.', name)

    destf = None
    try:
        destf = open(destination, "wb")
        destf.write(bytes)
    except IOError, e:
        parole.error('exportResource: IOError while writing resource "%s" to' ' "%s": %s', name, destination, e)
Example #24
0
def getTexture(name):
    """
    Attempts to retrieve the given texture resource as a PyGame C{Surface}
    object.

    @todo: Return a dummy texture if not found.

    @return: C{pygame.Surface} or C{None}

    @param name: The path + filename of the texture resource to retrieve. Must
    name an image file in a format that PyGame can read (png, jpeg, tiff, etc.).
    @type name: C{str}
    """
    # Return any cached copy of the texture surface object
    if name in __resTable:
        return __resTable[name]

    parole.info('Loading texture "%s"', name)

    # name should be a resource whose bytes are loadable by pygame's image
    # module
    bytes = getResource(name, binary=True)
    if not bytes:
        return None

    tex = None

    # Create a file-like object which pygame can use to read the bytes of
    # the texture
    texf = cStringIO.StringIO(bytes)

    # Attempt to load the texture
    try:
        tex = pygame.image.load(texf, name).convert()
    except Exception, e:
        # TODO: return a dummy "not found" texture
        parole.error('Unable to load texture "%s": %s', name, e)
        return None
Example #25
0
def __setMode():
    global __modeDirty, __displaySurf, __workSurf, __lastDepth, __clearedSurf
    __modeDirty = False
    resolution = (int(parole.conf.display.width),
                  int(parole.conf.display.height))
    fs = bool(parole.conf.display.fullscreen)
    hw = bool(parole.conf.display.hwaccel)
    depth = parole.conf.display.depth
    if depth not in __validDepths:
        error('Bad value for display.depth: %s. Should be one of %s.', depth,
              ', '.join(__validDepths))
        depth = __lastDepth
    else:
        __lastDepth = depth

    flags = 0
    if fs:
        flags |= pygame.FULLSCREEN

    if hw:
        flags |= pygame.HWSURFACE
        flags |= pygame.DOUBLEBUF

    parole.debug('Creating display surface...')
    __displaySurf = pygame.display.set_mode(resolution, flags, depth)
    parole.debug('... bingo!')
    #__clearedSurf = pygame.Surface(resolution).convert_alpha()
    #clearSurface(__clearedSurf, __clearedSurf.get_rect())

    if hw:
        __workSurf = pygame.Surface(resolution, pygame.SWSURFACE,
                                    __displaySurf)
    else:
        __workSurf = None

    parole.info('New mode: %s %s %sx%sx%s', hw and 'HW' or 'SW',
                fs and 'Fullscreen' or 'Window', resolution[0], resolution[1],
                depth)
Example #26
0
def getObject(scriptName, objName):
    """
    Retrieves a python object defined in the given python script 
    resource.

    @param scriptName:
    Should name a resource that is a python 
    script. The script should, upon execution, create a global (to itself) 
    object with the name C{objName}.
    @type scriptName: C{str}

    @param objName:
    The name of the object created in the script's global namespace to return.

    @return: C{object}
    """
    # Return any cached copy of the desired object
    if (scriptName, objName) in __resTable:
        return __resTable[(scriptName, objName)]

    parole.info('Loading object "%s" from "%s"', objName, scriptName)

    scriptNamespace = __runScript(scriptName)
    if not scriptNamespace:
        parole.error('Failed to load object "%s" from "%s"', objName,
                     scriptName)
        return None

    if objName not in scriptNamespace:
        parole.error('Script "%s" did not bind "s"', scriptName, objName)
        return None

    obj = scriptNamespace[objName]

    # The script worked and we have a bona fide object
    # Cache it and return it
    __resTable[(scriptName, objName)] = obj
    return obj
Example #27
0
def getTexture(name):
    """
    Attempts to retrieve the given texture resource as a PyGame C{Surface}
    object.

    @todo: Return a dummy texture if not found.

    @return: C{pygame.Surface} or C{None}

    @param name: The path + filename of the texture resource to retrieve. Must
    name an image file in a format that PyGame can read (png, jpeg, tiff, etc.).
    @type name: C{str}
    """
    # Return any cached copy of the texture surface object
    if name in __resTable:
        return __resTable[name]

    parole.info('Loading texture "%s"', name)

    # name should be a resource whose bytes are loadable by pygame's image
    # module
    bytes = getResource(name, binary=True)
    if not bytes:
        return None

    tex = None

    # Create a file-like object which pygame can use to read the bytes of
    # the texture
    texf = cStringIO.StringIO(bytes)

    # Attempt to load the texture
    try:
        tex = pygame.image.load(texf, name).convert()
    except Exception, e:
        # TODO: return a dummy "not found" texture
        parole.error('Unable to load texture "%s": %s', name, e)
        return None
Example #28
0
def resetGame():
    global player
    time = parole.time()
    player = Player()
    map, playerPos = mapgen.makeDungeonMap(data)
    map[playerPos].add(player)
    time = (parole.time() - time) or 1
    parole.info('Map creation time (%s x %s): %sms => %s tiles per second.',
                map.cols, map.rows, time, 
                (float(map.cols*map.rows) / float(time))*1000.0)
    data['outdoors'] = None
    data['outdoorsStairs'] = playerPos
    data['dungeon'] = map
    data['dungeonStairs'] = None
    data['currentMap'] = map
    data['mapframe'].setMap(map)
    data['mapframe'].bindVisibilityToFOV(player, 16, remember=True)
    data['fov'] = True
    data['memory'] = True
    light = parole.map.LightSource(colors['White'], 2.0)
    light.apply(map, player.pos)
    data['light'] = light
    data['mapframe'].centerAtTile(player.pos)
Example #29
0
def getObject(scriptName, objName):
    """
    Retrieves a python object defined in the given python script 
    resource.

    @param scriptName:
    Should name a resource that is a python 
    script. The script should, upon execution, create a global (to itself) 
    object with the name C{objName}.
    @type scriptName: C{str}

    @param objName:
    The name of the object created in the script's global namespace to return.

    @return: C{object}
    """
    # Return any cached copy of the desired object
    if (scriptName, objName) in __resTable:
        return __resTable[(scriptName, objName)]

    parole.info('Loading object "%s" from "%s"', objName, scriptName)

    scriptNamespace = __runScript(scriptName)
    if not scriptNamespace:
        parole.error('Failed to load object "%s" from "%s"', objName, scriptName)
        return None

    if objName not in scriptNamespace:
        parole.error('Script "%s" did not bind "s"', scriptName, objName)
        return None

    obj = scriptNamespace[objName]

    # The script worked and we have a bona fide object
    # Cache it and return it
    __resTable[(scriptName, objName)] = obj
    return obj
Example #30
0
def exportResource(name, destination):
    """
    Exports the named resource to the given destination on disk.
    C{destination} should be the full path plus filname to which the
    byte-contents of the named resource should be copied.

    This function can be useful for extracting a sound resource from a zip
    package and writing it to disk as a standalone file so that
    it can be used by C{pygame.mixer.music}, for instance.
    """
    parole.info('Exporting resource "%s" to "%s".', name, destination)

    bytes = getResource(name, binary=True)
    if not bytes:
        parole.error('exportResource: resource "%s" not found.', name)

    destf = None
    try:
        destf = open(destination, 'wb')
        destf.write(bytes)
    except IOError, e:
        parole.error(
            'exportResource: IOError while writing resource "%s" to'
            ' "%s": %s', name, destination, e)
Example #31
0
File: input.py Project: gdos/parole
def __onConfigChange(conf):
    r = int(conf.input.repeat)
    if r != 0:
        pygame.key.set_repeat(r, r)
    else:
        pygame.key.set_repeat()
    parole.info("Keyboard repeat delay: %sms", r)

    parole.info("Use shiftmap: %s", conf.input.useShiftmap)
    parole.info("Shiftmap: %s", conf.input.shiftmap.name)
Example #32
0
def __onConfigChange(conf):
    r = int(conf.input.repeat)
    if r != 0:
        pygame.key.set_repeat(r, r)
    else:
        pygame.key.set_repeat()
    parole.info('Keyboard repeat delay: %sms', r)

    parole.info('Use shiftmap: %s', conf.input.useShiftmap)
    parole.info('Shiftmap: %s', conf.input.shiftmap.name)
Example #33
0
def __onConfigChange(conf):
    global __gameDir
    parole.info('Resource package suffix: %s', conf.resource.packsuffix)
    if not __inInit:
        parole.warn('New package suffix will take effect on restart.')
    parole.info('Allowdirs: %s', conf.resource.allowdirs)
    if not __inInit:
        parole.warn('New resource.allowdirs will take effect on restart.')
    __gameDir = conf.resource.gamedir
    parole.info('Game directory: %s', __gameDir)
Example #34
0
def __onConfigChange(conf):
    global __gameDir
    parole.info("Resource package suffix: %s", conf.resource.packsuffix)
    if not __inInit:
        parole.warn("New package suffix will take effect on restart.")
    parole.info("Allowdirs: %s", conf.resource.allowdirs)
    if not __inInit:
        parole.warn("New resource.allowdirs will take effect on restart.")
    __gameDir = conf.resource.gamedir
    parole.info("Game directory: %s", __gameDir)
Example #35
0
def __onConfigChange(conf):
    global __modeDirty, __clearColor
    for key in __lastModeConfs.keys():
        if conf.display[key] != __lastModeConfs[key]:
            __modeDirty = True
            __lastModeConfs[key] = conf.display[key]
            parole.info("New value for display.%s: %s", key, __lastModeConfs[key])

    pygame.time.set_timer(parole.GeneralUpdateEvent, conf.display.generalUpdateDelay)
    parole.info("General display update delay: %s", conf.display.generalUpdateDelay)

    __clearColor = parseColor(conf.display.clearColor)
    parole.info("Display clear color: %s", __clearColor)

    if __modeDirty:
        parole.debug("Config changed; mode dirty")
Example #36
0
def __init():
    """
    Initializes the console module. Automatically called during engine 
    startup - user code shouldn't need to use this function.
    """
    global frame, stdout, stderr, logHandler, interpreter, history, historyPos

    parole.conf.notify(__onConfigChange, True)

    # Initialize the console command history
    history = []
    historyPos = 0

    # Create the console frame shader.
    frame = ConsoleFrame(parole.conf.console.height,
                         resource.getFont('fonts/monaco.ttf', 10),
                         parole.conf.console.ps1, parole.conf.console.ps2)

    # Write the intro banner to the console
    frame.write(banner)
    frame.flush()

    # Start logging to the console (INFO level)
    parole.info('Begin logging to console...')
    logHandler = logging.StreamHandler(frame)
    logHandler.setLevel(logging.INFO)
    logHandler.setFormatter(logging.Formatter(\
        '%(levelname)s: %(message)s'))
    logging.getLogger().addHandler(logHandler)

    # Create the actual interpreter
    #stderr = sys.stderr
    #sys.stderr = frame
    stdout = sys.stdout
    sys.stdout = frame
    parole.info('Setting up console Python interpreter...')
    interpreter = ConsoleInterpreter()

    parole.info('Loading console history file...')
    try:
        hf = open(historyFile, 'r')
        history = [l[:len(l) - 1] for l in hf.readlines() if len(l) > 1]
        historyPos = len(history)
        hf.close()
    except:
        parole.warn('Unable to open/load history file "%s".', historyFile)
Example #37
0
def __init():
    """
    Initializes the console module. Automatically called during engine 
    startup - user code shouldn't need to use this function.
    """
    global frame, stdout, stderr, logHandler, interpreter, history, historyPos
    
    parole.conf.notify(__onConfigChange, True)

    # Initialize the console command history
    history = []
    historyPos = 0

    # Create the console frame shader. 
    frame = ConsoleFrame(parole.conf.console.height,
            resource.getFont('fonts/monaco.ttf', 10), parole.conf.console.ps1,
            parole.conf.console.ps2)

    # Write the intro banner to the console
    frame.write(banner)
    frame.flush()

    # Start logging to the console (INFO level)
    parole.info('Begin logging to console...')
    logHandler = logging.StreamHandler(frame)
    logHandler.setLevel(logging.INFO)
    logHandler.setFormatter(logging.Formatter(\
        '%(levelname)s: %(message)s'))
    logging.getLogger().addHandler(logHandler)

    # Create the actual interpreter
    #stderr = sys.stderr
    #sys.stderr = frame
    stdout = sys.stdout
    sys.stdout = frame
    parole.info('Setting up console Python interpreter...')
    interpreter = ConsoleInterpreter()

    parole.info('Loading console history file...')
    try:
        hf = open(historyFile, 'r')
        history = [l[:len(l)-1] for l in hf.readlines() if len(l) > 1]
        historyPos = len(history)
        hf.close()
    except:
        parole.warn('Unable to open/load history file "%s".', historyFile)
Example #38
0
def __onConfigChange(conf):
    global __modeDirty, __clearColor
    for key in __lastModeConfs.keys():
        if conf.display[key] != __lastModeConfs[key]:
            __modeDirty = True
            __lastModeConfs[key] = conf.display[key]
            parole.info('New value for display.%s: %s', key,
                        __lastModeConfs[key])

    pygame.time.set_timer(parole.GeneralUpdateEvent,
                          conf.display.generalUpdateDelay)
    parole.info('General display update delay: %s',
                conf.display.generalUpdateDelay)

    __clearColor = parseColor(conf.display.clearColor)
    parole.info('Display clear color: %s', __clearColor)

    if __modeDirty:
        parole.debug('Config changed; mode dirty')
Example #39
0
def handleWalk(command):
    global lookAnnote, player, zapping
    if not player:
        return
    map = data['mapframe'].getMap()
    frame = data['mapframe']

    displacement = (0,0)
    moveTree = 'tree' in command
    if moveTree and not data['tree']:
        return

    if command in ['north','treenorth']:
        displacement = (0,-1)
    elif command in ['south', 'treesouth']:
        displacement = (0, 1)
    elif command in ['east', 'treeeast']:
        displacement = (1, 0)
    elif command in ['west', 'treewest']:
        displacement = (-1, 0)
    elif command in ['northeast', 'treenortheast']:
        displacement = (1,-1)
    elif command in ['northwest', 'treenorthwest']:
        displacement = (-1, -1)
    elif command in ['southeast', 'treesoutheast']:
        displacement = (1, 1)
    elif command in ['southwest', 'treesouthwest']:
        displacement = (-1,1)
    elif command == 'more ambient':
        map.setAmbientLight(map.ambientRGB, min(1., 
                                                map.ambientIntensity + 0.05))
        map.update()
        return
    elif command == 'less ambient':
        map.setAmbientLight(map.ambientRGB, max(0., 
                                                map.ambientIntensity - 0.05))
        map.update()
        return
    elif command in ('examine', 'zap'):
        if lookAnnote:
            if zapping:
                zapping = False
                zapPos = (lookAnnote.tile.col, lookAnnote.tile.row)
                if map.traceLOS(player.pos, zapPos, remAimOverlay) is \
                        map[zapPos]:
                    message('You zap that space into oblivion!')
                    map[zapPos].clear()
                else:
                    message('You need line-of-sight to zap!')

            frame.removeAnnotation(lookAnnote)
            lookAnnote = None
        else:
            playerTile = map[player.pos]
            if command == 'zap':
                zapping = True
                lookAnnote = frame.annotate(playerTile,
                    'Zap: %s.' % ', '.join([str(x) for x in playerTile]),
                    lineRGB=(64,32,255), reticleRGB=(64,32,255))
            else:
                lookAnnote = frame.annotate(playerTile,
                    'You see: %s.' % ', '.join([str(x) for x in \
                        playerTile]))
        return
    elif command == 'save':
        mbox = util.messageBox('Saving...')
        parole.display.update()
        time = parole.time()
        data['mapframe'].setMap(None)
        f = bz2.BZ2File('mapsave.sav', 'w')
        saveData = (data['outdoors'], data['dungeon'], data['dungeonStairs'],
                data['outdoorsStairs'], data['currentMap'], player,
                data['light'], data['tree'])
        cPickle.dump(saveData, f, protocol=-1)
        f.close()
        data['mapframe'].setMap(map)
        if data['fov']:
            data['mapframe'].bindVisibilityToFOV(player, 16,
            remember=data['memory'])
        time = (parole.time() - time) or 1
        parole.info('Map save time: %dms', time)
        parole.display.scene.remove(mbox)
        return

    elif command == 'restore':
        mbox = util.messageBox('Restoring...')
        parole.display.update()
        
        if lookAnnote:
            data['mapframe'].removeAnnotation(lookAnnote)
            lookAnnote = None
        data['mapframe'].setMap(None)
        time = parole.time()
        f = bz2.BZ2File('mapsave.sav', 'r')
        (data['outdoors'], data['dungeon'], data['dungeonStairs'],
            data['outdoorsStars'], data['currentMap'], player, data['light'],
            data['tree']) = cPickle.load(f)
        f.close()

        time = (parole.time() - time) or 1
        parole.info('Map restore time: %dms', time)
        parole.display.scene.remove(mbox)
        parole.display.update()

        setMap(data['currentMap'], player.pos, False)
        parole.debug('leaving restore')
        return

    elif command == 'toggle fov':
        mbox = util.messageBox('Patience...')
        parole.display.update()
        if data['fov']:
            data['mapframe'].bindVisibilityToFOV(None, None)
        elif player:
            data['mapframe'].bindVisibilityToFOV(player, 16,
                    remember=data['memory'])
        data['fov'] = not data['fov']
        parole.display.scene.remove(mbox)
        return
    elif command == 'down':
        for obj in map[player.pos]:
            if obj.name == 'a stairway leading down':
                message('You climb down.')
                if not data['dungeon']:
                    dungeon, playerPos = mapgen.makeDungeonMap(data)
                    data['dungeon'] = dungeon
                    data['dungeonStairs'] = playerPos
                setMap(data['dungeon'], data['dungeonStairs'])
                return
        message('There are no downward stairs here.')
        return
    elif command == 'up':
        for obj in map[player.pos]:
            if obj.name == 'a stairway leading up':
                message('You climb up.')
                setMap(data['outdoors'], data['outdoorsStairs'])
                return
        message('There are no upward stairs here.')
        return
    elif command == 'toggle memory':
        if data['fov'] and player:
            mbox = util.messageBox('Patience...')
            parole.display.update()
            data['memory'] = not data['memory']
            data['mapframe'].bindVisibilityToFOV(player, 16,
                    remember=data['memory'])
            parole.display.scene.remove(mbox)
            message('Memory %s.' % (data['memory'] and 'on' or 'off',))
        return
        
    if data['msg3Shader'].text:
        message('')
    curPos = moveTree and data['tree'].pos or player.pos
    if not moveTree and lookAnnote:
        curPos = (lookAnnote.tile.col, lookAnnote.tile.row)
    newPos = (curPos[0] + displacement[0], curPos[1] + displacement[1])

    if newPos[0] < 0 or newPos[1] < 0 or newPos[0] >= map.cols or \
            newPos[1] >= map.rows:
        return

    if lookAnnote and not moveTree:
        frame.removeAnnotation(lookAnnote)
        lookTile = map[newPos]
        if zapping:
            map.traceLOS(player.pos, curPos, remAimOverlay)
            if map.traceLOS(player.pos, newPos, addAimOverlay) is \
                    lookTile:
                lookAnnote = frame.annotate(lookTile,
                    'Zap: %s.' % ', '.join([str(x) for x in lookTile]),
                    lineRGB=(64,32,255), reticleRGB=(64,32,255))
            else:
                lookAnnote = frame.annotate(lookTile,
                    'Not in LOS.',
                    lineRGB=(64,32,255), reticleRGB=(64,32,255))
        else:
            if data['mapframe'].inFOV(lookTile):
                lookAnnote = frame.annotate(lookTile,
                    'You see: %s.' % ', '.join([str(x) for x in lookTile]))
            else:
                lookAnnote = frame.annotate(lookTile,
                    'You cannot see here.')

        return

    for obj in map[newPos]:
        if obj.blocker:
            message('Your way is blocked by %s.' % obj)
            return
        if obj.passer:
            message('You pass by %s.' % obj)


    map[curPos].remove(moveTree and data['tree'] or player)
    #data['light'].remove(map)
    #data['light'].rgb = random.choice([colors['Orange'],
    #    colors['Chocolate'], colors['Coral'], colors['Yellow'],
    #    colors['Pink']])
    map[newPos].add(moveTree and data['tree'] or player)
    #data['light'].apply(map, player.pos)

    data['mapframe'].centerAtTile(newPos)

    # This works, but is too slow without some sort of pre-caching and/or
    # optimization: animated water (each application uses random new
    # perlin Z).
    #map.applyGenerator(data['waterGenerator'], 
    #        pygame.Rect((25, 35), (20, 20)))

    map.update()
Example #40
0
                    parole.info('archf = %r', archf)
                except Exception, e:
                    parole.error(
                        'Ignoring bad archive resource package: %s: %s', arch,
                        e)
                    continue
                packages.append((arch, archf, __getResourceFromArch))

    # sort packages - reversed alphabetic, because alphabetically later
    # packages take precedence/override
    packages.sort(lambda x, y: cmp(x[0], y[0]), reverse=True)
    #parole.info('Packages: %r', packages)

    parole.info(
        'Resource packages: %s', ', '.join([
            pkgname +
            ((get == __getResourceFromArch) and ' (arch)' or ' (dir)')
            for (pkgname, f, get) in packages
        ]))
    __inInit = False
    parole.info('Extended image loading available: %s',
                pygame.image.get_extended())


def __unload():
    parole.conf.notify(__onConfigChange, False)


#==============================================================================


def getPackages():
Example #41
0
def clearAll():
    """
    Clears all loaded resources from the cache.
    """
    parole.info('Clearing all resources')
    __resTable.clear()
Example #42
0
                try:
                    archf = zipfile.ZipFile(os.sep.join([__gameDir, arch]), "r")
                    parole.info("archf = %r", archf)
                except Exception, e:
                    parole.error("Ignoring bad archive resource package: %s: %s", arch, e)
                    continue
                packages.append((arch, archf, __getResourceFromArch))

    # sort packages - reversed alphabetic, because alphabetically later
    # packages take precedence/override
    packages.sort(lambda x, y: cmp(x[0], y[0]), reverse=True)
    # parole.info('Packages: %r', packages)

    parole.info(
        "Resource packages: %s",
        ", ".join(
            [pkgname + ((get == __getResourceFromArch) and " (arch)" or " (dir)") for (pkgname, f, get) in packages]
        ),
    )
    __inInit = False
    parole.info("Extended image loading available: %s", pygame.image.get_extended())


def __unload():
    parole.conf.notify(__onConfigChange, False)


# ==============================================================================


def getPackages():
    """
Example #43
0
def clearAll():
    """
    Clears all loaded resources from the cache.
    """
    parole.info("Clearing all resources")
    __resTable.clear()