cocos.tiles module

Tile map management and rendering.

This module provides an API for loading, saving and rendering a map constructed of image tiles.

exception ResourceError

Bases: exceptions.Exception

exception TilesPropertyWithoutName

Bases: exceptions.Exception

exception TilesPropertyWithoutValue

Bases: exceptions.Exception

class Cell(i, j, width, height, properties, tile)

Bases: object

Base class for cells from rect and hex maps.

Common attributes:
i, j – index of this cell in the map position – the above as a tuple width, height – dimensions properties – arbitrary properties cell – cell from the MapLayer’s cells

Properties are available through the dictionary interface, ie. if the cell has a property ‘cost’ then you may access it as:

cell[‘cost’]

You may also set properties in this way and use the .get() method to supply a default value.

If the named property does not exist on the cell it will be looked up on the cell’s tile.

get(key, default=None)
position
class HexCell(i, j, height, properties, tile)

Bases: cocos.tiles.Cell

A flat-top, regular hexagon cell from a HexMap.

Cell attributes:
i, j – index of this cell in the map width, height – dimensions properties – arbitrary properties cell – cell from the MapLayer’s cells
Read-only attributes:
x, y – bottom-left pixel top – y pixel extent bottom – y pixel extent left – (x, y) of left corner pixel right – (x, y) of right corner pixel center – (x, y) origin – (x, y) of bottom-left corner of bounding rect topleft – (x, y) of top-left corner pixel topright – (x, y) of top-right corner pixel bottomleft – (x, y) of bottom-left corner pixel bottomright – (x, y) of bottom-right corner pixel midtop – (x, y) of middle of top side pixel midbottom – (x, y) of middle of bottom side pixel midtopleft – (x, y) of middle of left side pixel midtopright – (x, y) of middle of right side pixel midbottomleft – (x, y) of middle of left side pixel midbottomright – (x, y) of middle of right side pixel

Note that all pixel attributes are not adjusted for screen, view or layer transformations.

get_bottom()
get_bottomleft()
get_bottomright()
get_center()
get_left()
get_midbottom()
get_midbottomleft()
get_midbottomright()
get_midtop()
get_midtopleft()
get_midtopright()
get_origin()
get_right()
get_top()
get_topleft()
get_topright()
bottom
bottomleft
bottomright
center
left
midbottom
midbottomleft
midbottomright
midtop
midtopleft
midtopright
origin
right
top
topleft
topright
class HexMap(id, th, cells, origin=None, properties=None)

Bases: cocos.tiles.RegularTesselationMap

MapLayer with flat-top, regular hexagonal cells.

Calculated attributes:

edge_length – length of an edge in pixels = int(th / sqrt(3)) tw – with of a “tile” in pixels = edge_length * 2

Hexmaps store their cells in an offset array, column-major with y increasing up, such that a map:

  /d\ /h        /b\_/f\_/
\_/c\_/g        /a\_/e\_/
\_/ \_/

has cells = [[‘a’, ‘b’], [‘c’, ‘d’], [‘e’, ‘f’], [‘g’, ‘h’]]

(and this the cell at (0, 0) is ‘a’ and (1, 1) is ‘d’)

get_at_pixel(x, y)

Get the Cell at pixel (x,y).

Return None if out of bounds.

get_in_region(x1, y1, x2, y2)

Return cells (in [column][row]) that are within the pixel bounds specified by the bottom-left (x1, y1) and top-right (x2, y2) corners.

get_key_at_pixel(x, y)

returns the grid coordinates for the hex that covers the point (x, y)

Reference:
Hexagonal grid math, by Ruslan Shestopalyuk http://blog.ruslans.com/2011/02/hexagonal-grid-math.html
get_neighbor(cell, direction)

Get the neighbor HexCell in the given direction which is one of self.UP, self.DOWN, self.UP_LEFT, self.UP_RIGHT, self.DOWN_LEFT or self.DOWN_RIGHT.

Return None if out of bounds.

get_neighbors(cell)

Get all neighbor cells for the nominated cell.

Return a dict with the directions (self.UP, self.DOWN, etc) as keys and neighbor cells as values.

DOWN = u'down'
DOWN_LEFT = u'down left'
DOWN_RIGHT = u'down right'
UP = u'up'
UP_LEFT = u'up left'
UP_RIGHT = u'up right'
class HexMapLayer(id, th, cells, origin=None, properties=None)

Bases: cocos.tiles.HexMap, cocos.tiles.MapLayer

A renderable, scrollable tile map covered by hexagonal tiles

While visually the tiles look hexagonal, the texture that draws each tile is rectangular and should comply:

  • depicts an hexagon with upper and lower sides paralel to the x-axis
  • area out of the hexagon should be transparent
  • tile size must comply width == int(height / sqrt(3) * 2)

Be warned that some hexagonal tilesets found in the net use other proportions or the pointy orientation ( left and right sides paralel to the y-axis) ; neither will work with HexMapLayer

The Layer has a calculated attribute:

edge_length – length of an edge in pixels = int(th / sqrt(3)) tw – with of a “tile” in pixels = edge_length * 2

Hexmaps store their cells in an offset array, column-major with y increasing up, such that a map:

  /d\ /h            /b\_/f\_/
\_/c\_/g            /a\_/e\_/
\_/ \_/

has cells = [[‘a’, ‘b’], [‘c’, ‘d’], [‘e’, ‘f’], [‘g’, ‘h’]]

class MapLayer(properties)

Bases: cocos.layer.scrolling.ScrollableLayer

Base class for Maps.

Maps are comprised of tiles and can figure out which tiles are required to be rendered on screen.

Both rect and hex maps have the following attributes:

id – identifies the map in XML and Resources (width, height) – size of map in cells (px_width, px_height) – size of map in pixels (tw, th) – size of each cell in pixels (origin_x, origin_y, origin_z) – offset of map top left from origin in pixels cells – array [i][j] of Cell instances debug – display debugging information on cells properties – arbitrary properties

The debug flag turns on textual display of data about each visible cell including its cell index, origin pixel and any properties set on the cell.

find_cells(**requirements)

Find all cells that match the properties specified.

For example:

map.find_cells(player_start=True)

Return a list of Cell instances.

get(key, default=None)
get_visible_cells()

Given the current view in map-space pixels, transform it based on the current screen-space transform and figure the region of map-space pixels currently visible.

Pass to get_in_region to return a list of Cell instances.

is_visible(rect)

Determine whether the indicated rect (with .x, .y, .width and .height attributes) located in this Layer is visible.

set_cell_color(i, j, color)
set_cell_opacity(i, j, opacity)
set_debug(debug)
set_dirty()
set_view(x, y, w, h, viewport_x=0, viewport_y=0)
debug = False
class RectCell(i, j, width, height, properties, tile)

Bases: cocos.rect.Rect, cocos.tiles.Cell

A rectangular cell from a MapLayer.

Cell attributes:
i, j – index of this cell in the map x, y – bottom-left pixel width, height – dimensions properties – arbitrary properties cell – cell from the MapLayer’s cells

The cell may have the standard properties “top”, “left”, “bottom” and “right” which are booleans indicating that those sides are impassable. These are used by RectCellCollider.

Note that all pixel attributes are not adjusted for screen, view or layer transformations.

bottom
bottomleft
bottomright
center
left
midbottom
midleft
midright
midtop
origin
right
top
topleft
topright
class RectMap(id, tw, th, cells, origin=None, properties=None)

Bases: cocos.tiles.RegularTesselationMap

Rectangular map.

Cells are stored in column-major order with y increasing up, allowing [i][j] addressing:

+---+---+---+
| d | e | f |
+---+---+---+
| a | b | c |
+---+---+---+

Thus cells = [[‘a’, ‘d’], [‘b’, ‘e’], [‘c’, ‘f’]]

(and thus the cell at (0, 0) is ‘a’ and (0, 1) is ‘d’)

get_at_pixel(x, y)

Return Cell at pixel px=(x,y) on the map.

The pixel coordinate passed in is in the map’s coordinate space, unmodified by screen, layer or view transformations.

Return None if out of bounds.

get_in_region(x1, y1, x2, y2)
Return cells that intersects the rectangle x1, y1, x2, y2 in an
area greater than zero

(x1, y1) and (x2, y2) are the lower left and upper right corners respectively, in map’s coordinate space, unmodified by screen, layer or view transformations

Return a list of Cell instances.

When the rectangle has area zero results are a bit inconsistent:
A rectangle which is a point intersects no cell A rectangle which is a segment and overlaps the cell boundaries intersects no cells A rectangle which is a segment and don’t overlaps the cell boundaries intersects some cells: the ones that the open segment intersects
get_key_at_pixel(x, y)

returns the grid coordinates for the hex that covers the point (x, y)

get_neighbor(cell, direction)

Get the neighbor Cell in the given direction (dx, dy) which is one of self.UP, self.DOWN, self.LEFT or self.RIGHT.

Returns None if out of bounds.

get_neighbors(cell, diagonals=False)

Get all cells touching the sides of the nominated cell.

If “diagonals” is True then return the cells touching the corners of this cell too.

Return a dict with the directions (self.UP, self.DOWN, etc) as keys and neighbor cells as values.

DOWN = (0, -1)
LEFT = (-1, 0)
RIGHT = (1, 0)
UP = (0, 1)
class RectMapCollider

Bases: object

This class implements collisions between a moving rect object and a tilemap.

collide_bottom(dy)
collide_left(dx)
collide_map(map, last, new, dy, dx)

Collide a rect with the given RectMap map.

Apart from “map” the arguments are as per do_collision.

Mutates the new rect to conform with the map.

Returns the (possibly modified) (dx, dy)

collide_right(dx)
collide_top(dy)
do_collision(cell, last, new, dy, dx)

Collide a Rect moving from “last” to “new” with the given map RectCell “cell”. The “dx” and “dy” values may indicate the velocity of the moving rect.

The RectCell must have the boolean properties “top”, “left”, “bottom” and “right” for those sides which the rect should collide.

If there is no collision then nothing is done.

If there is a collision:

  1. The “new” rect’s position will be modified to its closest position to the side of the cell that the collision is on, and
  2. If the “dx” and “dy” values are passed in the methods collide_<side> will be called to indicate that the rect has collided with the cell on the rect’s side indicated. The value passed to the collide method will be a modified distance based on the position of the rect after collision (according to step #1).

Mutates the new rect to conform with the map.

Returns the (possibly modified) (dx, dy)

resting = False
class RectMapLayer(id, tw, th, cells, origin=None, properties=None)

Bases: cocos.tiles.RectMap, cocos.tiles.MapLayer

A renderable, scrollable rect map.

class RegularTesselationMap

Bases: object

A regularly tesselated map that allows access to its cells by index (i, j).

get_cell(i, j)

Return Cell at cell pos=(i, j).

Return None if out of bounds.

class Resource(filename)

Bases: object

Load some tile mapping resources from an XML file.

add_resource(id, resource)
find(cls)

Find all elements of the given class in this resource.

find_file(filename)
findall(cls, ns=u'')

Find all elements of the given class in this resource and all <requires>’ed resources.

get_resource(ref)
handle(tag)
classmethod register_factory(name)
requires_factory(tag)
resource_factory(tag)
save_xml(filename)

Save this resource’s XML to the indicated file.

cache = {}
factories = {u'tileset': <function tileset_factory at 0x059BC7B0>, u'resource': <function resource_factory at 0x059BC3F0>, u'imageatlas': <function imageatlas_factory at 0x059BC770>, u'image': <function image_factory at 0x059BC730>, u'rectmap': <function rectmap_factory at 0x059BC970>, u'hexmap': <function hexmap_factory at 0x059BC9B0>, u'requires': <function requires_factory at 0x059BC430>}
class Tile(id, properties, image, offset=None)

Bases: object

Tiles hold an image and some optional properties.

class TileSet(id, properties)

Bases: dict

Contains a set of Tile objects referenced by some id.

add(properties, image, id=None)

Add a new Tile to this TileSet, generating a unique id if necessary.

Returns the Tile instance.

classmethod from_atlas(name, firstgid, file, tile_width, tile_height)
classmethod generate_id()
tile_id = 0
color4_to_text(v)
decode_base64(s)

returns a bytes object

decompress_gzip(in_bytes)

decompress the input array of bytes to an array of bytes using gzip

decompress_zlib(in_bytes)

decompress the input array of bytes to an array of bytes using zlib

hex_width(height)

Determine a regular hexagon’s width given its height.

hexmap_factory(resource, tag)
image_factory(resource, tag)
imageatlas_factory(resource, tag)
load(filename)

Load resource(s) defined in the indicated XML file.

load_tiles(filename)

Load some tile mapping resources from an XML file.

load_tmx(filename)

Load some tile mapping resources from a TMX file.

rectmap_factory(resource, tag)
text_to_4tuple_int(s)
tileset_factory(resource, tag)

Previous topic

cocos.text module

Next topic

cocos.utils module

This Page