gummworld2.toolkit (version $Id: toolkit.py 418 2013-08-19 14:38:28Z stabbingfinger@gmail.com $)
index
c:\cygwin\home\bw\devel\python\svn\gummworld2_devel\gamelib\gummworld2\toolkit.py

toolkit.py - Some helper tools for Gummworld2.

 
Modules
       
gummworld2.data
os
pygame
re
urllib

 
Classes
       
__builtin__.object
Struct
Tilesheet

 
class Struct(__builtin__.object)
    A class with arbitrary members. Construct it like a dict, then access the
keys as instance attributes.
 
s = Struct(x=2, y=4)
print s.x,s.y
 
  Methods defined here:
__init__(self, **kwargs)

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class Tilesheet(__builtin__.object)
     Methods defined here:
__init__(self, file_path, image, margin, tile_size, spacing, rects)
get_image(self, tile_id)
tile_info(self, tile_id)
Return a Struct populated with tilesheet info for tile_id. This info
represents everything needed by the Tile class constructor in
world_editor.py.
 
Struct members:
    name : str; relative path to image file
    image : pygame.surface.Surface; the loaded image
    margin : Vec2d; size of image's edge border
    size : Vec2d; size of a single tile
    spacing : Vec2d; spacing between tiles
    rects : pygame.Rect; list of rects defining tile subsurfaces

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
Functions
       
X_draw_parallax_tiles(layer, tiles, pax_rect, view=None)
## EXPERIMENTAL: not working quite right
draw_grid(grid_cache, layeri=0, color=(0, 0, 255, 255), alpha=33)
Draw a grid over the camera view.
 
The grid_lines argument is a list of length two containing a cached
[vline,hline] pair. This function will initialize the contents if the
starting values evaluate to False (e.g. [0,0]).
 
The layeri argument is the map layer from which to get the grid spacing.
 
The color argument is the desired grid color.
 
The alpha argument is the surface alpha. If alpha is not None, it must be a
valid value for pygame.Surface.set_alpha().
 
color and alpha are only used when when creating the surfaces for the
grid_lines list.
draw_labels(cache_dict, layeri=0, color=(0, 0, 0, 255))
#def draw_labels(cache_dict, layeri=0, color=pygame.Color('black')):
#    global label_font
#    if label_font is None:
#        label_font = pygame.font.Font(data.filepath('font','Vera.ttf'), 7)
#    lfont = label_font
#    #
#    camera = State.camera
#    cam_rect = State.camera.rect
#    blit = camera.surface.blit
#    left,top,width,height = cam_rect
#    layer = State.map.layers[layeri]
#    tw,th = layer.tile_width, layer.tile_height
#    x0 = left // tw
#    y0 = top // th
#    x1 = tw - (left - x0*tw)
#    y1 = th - (top - y0*th)
###    print x0,y0,x1,y1
#    #
#    for x in xrange(x1, width, layer.tile_width):
#        for y in xrange(y1, height, layer.tile_height):
###            print x,y
#            name = (x+tw)//tw+x0, (y+th)//th+y0
###            name = (x+tw)//tw, (y+th)//th
#            label = cache_dict.get(name, None)
#            if not label:
#                label = lfont.render(str(name), True, color)
#                cache_dict[name] = label
#            blit(label, (x+2,y+2))
draw_object_array(object_array)
Draw a layered array of objects.
 
For best performance:
    
def update(self, dt):
    self.visible_objects = toolkit.get_object_array()
def draw(self, dt):
    ...
    toolkit.draw_object_array(self.visible_objects)
draw_parallax_tile_range(layer, tile_range, pax_rect)
## EXPERIMENTAL: not working quite right
draw_parallax_tiles(maps, view)
maps is a list of maps
 
Assumptions:
    1. Maps are in world coords.
    2. Each map has the same number of layers.
    3. Each map's corresponding layer has the same parallax value.
    4. Each map layer has a parallax attribute: tuple of length 2.
    5. Each map layer has a tile_range attribute: range of visible tiles.
draw_parallax_tiles_of_layer(cam, map, layer, parallax=(1.0, 1.0))
## EXPERIMENTAL: not working quite right
draw_sprite(s, blit_flags=0)
Draw a sprite on the camera's surface using world-to-screen conversion.
draw_tiles()
Draw visible tiles.
 
Quick and dirty draw function, handles getting the objects and drawing
them. This is a bit more expensive than getting tiles during the update
cycle and reusing the object array for the draw cycles. However, it is
less hassle, and one might want to use this tactic if panning more than
one tile span per tick.
draw_tiles_of_layer(layeri, pallax_factor_x=1.0, pallax_factor_y=1.0)
Draw visible tiles.
 
This function assumes that the tiles stored in the map are sprites.
export_world(fh, entities)
A sequence-to-text exporter.
 
This function is required by world_editor.py, and possibly other scripts, to
export entities to a text file.
 
Geometry classes used by this plugin are: RectGeometry, CircleGeometry, and
PolyGeometry.
 
The values saved are those needed for each shape-class's constructor, plus a
block of arbitrary user data. The user data is url-encoded.
get_object_array(max_speed=10)
Return a list of the map's objects that would be visible to the camera.
Operates on State.map and State.camera.
 
The max_speed argument adds this many pixels to each edge of the query rect
to accommodate for the space moved during frame interpolation cycles. This
should at least match the scrolling speed to avoid black flickers at the
screen edges.
 
The return value is a list of object lists:
    [   [obj0, obj1, ...],          # layer0
        [obj0, obj1, ...],          # layer1
        ...,                        # layerN
    ]
get_objects_in_cell_ids(map_, cell_ids_per_layer)
Return a list of objects per layer for the specified cell IDs.
This function is mainly for SuperMap, which needs to specify the map.
 
The argument cell_ids_per_layer is a list of nested lists containing
cell IDs:
    [   [cell_id0, cell_id1, ...],  # layer0
        [cell_id0, cell_id1, ...],  # layer1
        ...,                        # layerN
    ]
 
The return value is a similary constructed list of object lists:
    [   [obj0, obj1, ...],          # layer0
        [obj0, obj1, ...],          # layer1
        ...,                        # layerN
    ]
get_parallax_tile_range(cam, map, layer, parallax, orig='center')
## EXPERIMENTAL: not working quite right
#def get_parallax_tile_range(cam, map, layer, parallax, orig='bottomleft'):
get_tilesheet_info(tilesheet_path)
Get the tilesheet meta data from file if it exists.
get_visible_cell_ids(camera, map_, max_speed=10)
Return a list of the map's cell IDs that would be visible to the camera.
This function is mainly for SuperMap, which needs to specify the map.
 
The camera argument is the camera that defines the view.
 
The map_ argument is the BasicMap or TiledMap to query.
 
The max_speed argument adds this many pixels to each edge of the query rect
to accommodate for the space moved during frame interpolation cycles. This
should at least match the scrolling speed to avoid black flickers at the
screen edge.
 
The return value is a list of cell IDs in the map's spatialhash for each
layer. The per-layer values are necessary because maps can have layers with
different tile sizes, and therefore different grids.
 
The return value is suitable for passing to get_objects_in_cell_ids().
 
Returns:
    [   [cell_id0, cell_id1, ...],  # layer0
        [cell_id0, cell_id1, ...],  # layer1
        ...,                        # layerN
    ]
import_world(fh, rect_cls=<class 'gummworld2.geometry.RectGeometry'>, line_cls=<class 'gummworld2.geometry.LineGeometry'>, poly_cls=<class 'gummworld2.geometry.PolyGeometry'>, circle_cls=<class 'gummworld2.geometry.CircleGeometry'>)
A world entity importer.
 
This function is required by world_editor.py, and possibly other scripts, to
import world entities from a text file. It understands the format of files
created by export_world().
 
Geometry classes used by this function to create shape objects are specified
by the rect_cls, line_cls, poly_cls, and circle_cls arguments. The
constructor parameters must have the same signature as geometry.RectGeometry,
et al.
 
The values imported are those needed for each shape-class's constructor,
plus a block of arbitrary user data which will be placed in the shape
instance's user_data attribute.
 
The user_data is also parsed for tilesheet info. Tilesets are loaded and
returned as a dict of toolkit.Tilesheet, keyed by relative path to the
image file.
interpolated_step(pos, step, interp)
Returns (float,float).
 
This is a utility for drawing routines, after pos has been updated by step.
For example:
    def update():
        move_camera()
        State.camera.update()
        sprite_group.update()  # e.g. steps a sprite position
    def draw():
        interp = State.camera.interpolate()
        camera_pos = State.camera.rect.topleft
        for s in sprite_group:
            sprite_pos = Vec2d(s.rect.topleft)
            pos = sprite_pos - camera_pos
            step = s.step
            interp_pos = toolkit.interpolated_step(pos, step, interp)
            surf.blit(s.image, interp_pos)
load_entities(filepath, cls_dict={})
Load entities via import_world() plugin.
 
The cls_dict argument is a dict of classes to construct when encountering
shape data. The following keys are supported: 'rect_cls', 'line_cls',
'poly_cls', 'circle_cls'. If any of those keys are missing from cls_dict,
the following classes will be used by default: geometry.RectGeometry,
geometry.LineGeometry, geometry.PolyGeometry, geometry.CircleGeometry.
Classes substituted in this manner must have constructors that are
compatible with the default classes.
load_tilesheet(file_path)
Load a tilesheet. A toolkit.Tilesheet containing tilesheet info is
returned.
 
The file_path argument is the path to the image file. If file_path is a
relative path, it must exist relative to data.data_dir (see the
gummworld2.data module). If file_path.tilesheet exists it will be used to
size the tiles; otherwise the defaults (0,0,32,32,0,0) will be used.
make_hud(caption=None, visible=True)
Create a HUD with dynamic items. This creates a default hud to serve
both as an example, and for an early design and debugging convenience.
make_tiles(label=False)
Create tiles to fill the current map. This is a utility for easily making
visible content to aid early game design or debugging.
 
Tiles transition from top-left to bottom-right, red to blue.
make_tiles2()
Create tiles to fill the current map. This is a utility for easily making
visible content to aid early game design or debugging.
 
Tiles transition from top to bottom, light blue to brown.
put_tilesheet_info(tilesheet_path, tilesheet_values)
Put the tilesheet meta data to file.

 
Data
        BLEND_RGBA_ADD = 6
IMAGE_FILE_EXTENSIONS = ('gif', 'png', 'jpg', 'jpeg', 'bmp', 'pcx', 'tga', 'tif', 'lbm', 'pbm', 'pgm', 'xpm')
RLEACCEL = 16384
SRCALPHA = 65536
__author__ = 'Gummbum, (c) 2011-2013'
__version__ = '$Id: toolkit.py 418 2013-08-19 14:38:28Z stabbingfinger@gmail.com $'
hud_font = <pygame.font.Font object>
label_font = None

 
Author
        Gummbum, (c) 2011-2013