tmxlib Module Reference

The main module contains the most important classes.

Map

class tmxlib.Map(size, tile_size, orientation='orthogonal', base_path=None)[source]

A tile map. tmxlib’s core class

init arguments, which become attributes:

size

a (height, width) pair specifying the size of the map, in tiles

tile_size

a pair specifying the size of one tile, in pixels

orientation

The orientation of the map ('orthogonal' or 'isometric')

Other attributes:

tilesets

A TilesetList of tilesets this map uses

layers

A LayerList of layers this map uses

properties

A dict of properties, with string (or unicode) keys & values

pixel_size[source]

The size of the map, in pixels. Not settable directly: use size and tile_size for that.

end_gid[source]

The first GID that is not available for tiles. This is the end_gid for the map’s last tileset.

Unpacked size attributes:

Each “size” property has corresponding “width” and “height” properties.

height
width
tile_height[source]
tile_width[source]
pixel_height[source]
pixel_width[source]

Loading and saving (see tmxlib.fileio.ReadWriteBase for detailed information):

classmethod open(filename, shared=False)
classmethod load(string)
save(filename)
dump(string)

Methods:

add_layer(name, before=None, after=None)[source]

Add an empty layer with the given name to the map.

By default, the new layer is added at the end of the layer list. A different position may be specified with either of the before or after arguments, which may be integer indices or names.

all_tiles()[source]

Yield all tiles in the map, including tile objects

all_objects()[source]

Yield all objects in the map

get_tiles(x, y)[source]

For each tile layer, yield the tile at the given position.

check_consistency()[source]

Check that this map is okay.

Most checks are done when reading a map, but if more are required, call this method after reading. This will do a more expensive check than what’s practical from within readers.

Tileset

class tmxlib.Tileset(name, tile_size, source=None)[source]

Base class for a tileset: bank of tiles a map can use.

There are two kinds of tilesets: external and internal. Internal tilesets are specific to a map, and their contents are saved inside the map file. External tilesets are saved to their own file, so they may be shared between several maps. (Of course, any tileset can be shared between maps at the Python level; this distinction only applies to what happens on disk.) External tilesets have the file path in their source attribute; internal ones have source set to None.

tmxlib will try to ensure that each external tileset gets only loaded once, an the resulting Python objects are shared. See ReadWriteBase.open() for more information.

init arguments, which become attributes:

name

Name of the tileset

tile_size:

A (width, height) pair giving the size of a tile in this tileset. In cases where a tileset can have unequally sized tiles, the tile size is not defined. This means that this property should not be used unless working with a specific subclass that defines tile_size better.

source

For external tilesets, the file name for this tileset. None for internal ones.

Other attributes:

properties

A dict with string (or unicode) keys and values. Note that the official TMX format does not support tileset properties (yet), so editors like Tiled will remove these. (tmxlib saves and loads them just fine, however.)

Unpacked versions of tile_size:

tile_width[source]
tile_height[source]

Loading and saving (see tmxlib.fileio.ReadWriteBase for detailed information):

classmethod open(filename, shared=False)
classmethod load(string)
save(filename)
dump(string)

List-like access:

__getitem__(n)[source]

Get tileset tile with the given number.

Supports negative indices by wrapping around, as one would expect.

__len__()[source]

Return the number of tiles in this tileset.

Subclasses need to override this method.

__iter__()[source]

Iterate through tiles in this tileset.

Overridable methods:

tile_image(number)[source]

Return the image used by the given tile.

Usually this will be a region of a larger image.

Subclasses need to override this method.

GID calculation methods:

Note

TilesetList depends on the specific GID calculation algorithm provided by these methods to renumber a map’s tiles when tilesets are moved around. Don’t override these unless your subclass is not used with vanilla TilesetLists.

first_gid(map)[source]

Return the first gid used by this tileset in the given map

end_gid(map)[source]

Return the first gid after this tileset in the given map

ImageTileset

class tmxlib.ImageTileset(name, tile_size, image, margin=0, spacing=0, source=None, base_path=None)[source]

A tileset whose tiles form a rectangular grid on a single image.

This is the default tileset type in Tiled.

init arguments, which become attributes:

name
tile_size
source

see Tileset

image

The Image this tileset is based on.

margin

Size of a border around the image that does not contain tiles, in pixels.

spacing

Space between adjacent tiles, in pixels.

Other attributes:

column_count[source]

Number of columns of tiles in the tileset

row_count[source]

Number of rows of tiles in the tileset

See tmxlib.Tileset for tileset methods.

TilesetTile

class tmxlib.TilesetTile(tileset, number)[source]

Reference to a tile within a tileset

init arguents, which become attributes:

tileset

the tileset this tile belongs to

number

the number of the tile

Other attributes:

size[source]

The size of the tile, in pixels

properties[source]

A string-to-string dictionary holding custom properties of the tile

image[source]

Image this tile uses. Most often this will be a region of the tileset’s image.

Methods:

gid(map)[source]

Return the GID of this tile for a given map

The GID is a map-specific identifier unique for any tileset-tile the map uses.

get_pixel(x, y)[source]

Get a pixel at the specified location.

Pixels are returned as RGBA 4-tuples.

Layer

class tmxlib.Layer(map, name, visible=True, opacity=1)[source]

Base class for map layers

init agruments, which become attributes:

map

The map this layer belongs to. Unlike tilesets, layers are tied to a particular map and cannot be shared.

name

Name of the layer

visible

A boolean setting whether the layer is visible at all. (Actual visibility also depends on opacity)

opacity

Floating-point value for the visibility of the layer. (Actual visibility also depends on visible)

Other attributes:

properties

Dict of properties with string (or unicode) keys and values.

type

'tiles' if this is a tile layer, 'objects' if it’s an object layer.

index[source]

Index of this layer in the layer list

Methods:

all_objects()[source]

Yield all objects in this layer

all_tiles()[source]

Yield all tiles in this layer, including empty ones and tile objects

TileLayer

class tmxlib.TileLayer(map, name, visible=True, opacity=1, data=None)[source]

A tile layer

Acts as a 2D array of MapTile’s, indexed by [x, y] coordinates. Assignment is possible either via numeric values, or by assigning a TilesetTile. In the latter case, if the tileset is not on the map yet, it is added.

See Layer documentation for most init arguments.

Other init agruments, which become attributes:

data

Optional list (or array) containing the values of tiles in the layer, as one long list in row-major order. See TileLikeObject.value for what the numbers will mean.

Methods:

all_objects()[source]

Yield all objects in this layer (i.e. return empty iterable)

all_tiles()[source]

Yield all tiles in this layer, including empty ones.

Tile access:

__getitem__(pos)[source]

Get a MapTile representing the tile at the given position.

Supports negative indices by wrapping in the obvious way.

__setitem__(pos, value)[source]

Set the tile at the given position

The set value can be either an raw integer value, or a TilesetTile. In the latter case, any tileset not in the map yet will be added to it.

Supports negative indices by wrapping in the obvious way.

Methods to be overridden in subclasses:

value_at(pos)[source]

Return the value at the given position

See MapTile for an explanation of the value.

set_value_at(pos, new)[source]

Sets the raw value at the given position

See MapTile for an explanation of the value.

ObjectLayer

class tmxlib.ObjectLayer(map, name, visible=True, opacity=1)[source]

A layer of objects.

Acts as a named list of objects. This means semantics similar to layer/tileset lists: indexing by name is possible, where a name references the first object of such name.

See Layer for the init arguments.

Methods:

all_objects()[source]

Yield all objects in this layer (i.e. return self)

all_tiles()[source]

Yield all tile objects in this layer, in order.

MapTile

class tmxlib.MapTile(layer, pos)[source]

References a particular spot on a tile layer

init arguments, which become attributes:

layer

The associated layer.

pos[source]

The associated coordinates, as (x, y), in tile coordinates.

Other attributes:

value

Numeric value of a tile, representing the image and transformations.

See the TMX format for a hopefully more detailed specification. The upper bits of this number are used for flags:

  • 0x80000000: tile is flipped horizontally.
  • 0x40000000: tile is flipped vertically.
  • 0x20000000: tile is flipped diagonally (axes are swapped).
  • 0x10000000: tmxlib reserves this bit for now, just because 0x0FFFFFFF is a nice round number.

The rest of the value is zero if the layer is empty at the corresponding spot (or an object has no associated tile image), or it holds the GID of the tileset-tile.

The GID can be computed as 1 + X + Y where X is the number of tiles in all tilesets preceding the tile’s, and Y is the number of the tile within its tileset.

The individual parts of value are reflected in individual properties:

  • flipped_horizontally (0x80000000)
  • flipped_vertically (0x40000000)
  • flipped_diagonally (0x20000000)
  • gid (0x0FFFFFFF)

The properties themselves have a value attribute, e.g. tmxlib.MapTile.flipped_diagonally.value == 0x20000000.

map

The map associated with this object

Attributes for accessing to the referenced tile:

tileset_tile

Get the referenced tileset tile

size[source]

Size of the referenced tile, taking rotation into account.

Empty tiles have (0, 0) size.

tileset

Get the referenced tileset

number

Get the number of the referenced tileset tile

image

Get the image of the tile. (N.B. see full docstring!)

N.B. No transformations are applied to the image. This can change in future versions. Use self.tileset_tile.image for future-safe behavior.

properties[source]

Properties of the referenced tileset-tile

If that wasn’t clear enough: Changing this will change properties of all tiles using this image. Possibly even across more maps if tilesets are shared.

See TilesetTile.

Unpacked pos and size attributes:

x
y
width
height

Methods:

tile_to_image_coordinates(x, y)

Transform map-tile pixel coordinates to tileset-tile pixel coords.

Handles negative indices in the obvious way.

get_pixel(x, y)

Get the pixel at the given x, y coordinates.

Handles negative indices in the obvious way.

__nonzero__()

This object is “true” iff there’s a tile associated with it.

Empty, “false” tiles have a GID of zero.

Flipping:

vflip()

Flip the tile vertically

hflip()

Flip the tile horizontally

rotate(degrees=90)

Rotate the tile clockwise by the specified number of degrees

Note that tiles can only be rotated in 90-degree increments.

MapObject

class tmxlib.MapObject(layer, pixel_pos, size=None, name=None, type=None, value=0)[source]

A map object: something that’s not placed on the fixed grid

Can be either a “tile object”, which has an associated tile much like a map-tile, or a regular (non-tile) object that has a settable size.

init arguments, which become attributes:

layer

The layer this object is on

pixel_pos

The pixel coordinates

size[source]

Size of this object, as a (width, height) tuple, in pixels. Must be specified for non-tile objects, and must not be specified for tile objects (unless the size matches the tile).

Similar restrictions apply to setting the property (and width & height).

name

Name of the object. A string (or unicode)

type

Type of the object. A string (or unicode). No semantics attached.

value

Value of the tile, if it’s a tile object.

See MapTile

Attributes for accessing to the referenced tile:

tileset_tile

Get the referenced tileset tile

size[source]

Size of the referenced tile, taking rotation into account.

Empty tiles have (0, 0) size.

tileset

Get the referenced tileset

number

Get the number of the referenced tileset tile

image

Get the image of the tile. (N.B. see full docstring!)

N.B. No transformations are applied to the image. This can change in future versions. Use self.tileset_tile.image for future-safe behavior.

properties

Properties of the referenced tileset-tile

If that wasn’t clear enough: Changing this will change properties of all tiles using this image. Possibly even across more maps if tilesets are shared.

See TilesetTile.

Other attributes:

properties

Dict of string (or unicode) keys & values for custom data

pos[source]

Position of the object in tile coordinates, as a (x, y) float tuple

map

The map associated with this object

Unpacked pos, pixel_pos, and size:

x
y
pixel_x[source]
pixel_y[source]
width
height

Methods:

tile_to_image_coordinates(x, y)

Transform map-tile pixel coordinates to tileset-tile pixel coords.

Handles negative indices in the obvious way.

get_pixel(x, y)

Get the pixel at the given x, y coordinates.

Handles negative indices in the obvious way.

__nonzero__()

This object is “true” iff there’s a tile associated with it.

Empty, “false” tiles have a GID of zero.

Flipping:

vflip()

Flip the tile vertically

hflip()

Flip the tile horizontally

rotate(degrees=90)

Rotate the tile clockwise by the specified number of degrees

Note that tiles can only be rotated in 90-degree increments.

Lists with named elements

NamedElementList

class tmxlib.NamedElementList(lst=None)[source]

A list that supports indexing by element name, as a convenience, etc

lst[some_name] means the first element where element.name == some_name. The dict-like get method is provided.

Additionally, NamedElementList subclasses can use several hooks to control how their elements are stored or what is allowed as elements.

get(index_or_name, default=None)[source]

Same as __getitem__, but a returns default if not found

insert(index_or_name, value)[source]

Same as list.insert, except indices may be names instead of ints.

insert_after(index_or_name, value)[source]

Insert the new value after the position specified by index_or_name

For numerical indexes, the same as insert(index + 1, value). Useful when indexing by strings.

move(index_or_name, amount)[source]

Move an item by the specified number of indexes

amount can be negative. For example, “move layer down” translates to layers.move(idx, -1)

The method will clamp out-of range amounts, so, for eample, lst.move(0, -1) will do nothing.

Hooks for subclasses:

modification_context(*args, **kwds)[source]

Context in which all modifications take place.

The default implementation nullifies the modifications if an exception is raised.

Note that the manager may nest, in which case the outermost one should be treated as an atomic operation.

retrieved_value(item)[source]

Called when an item is being retrieved from the list.

Return the object that will actually be retrieved.

This method must undo any modifications that stored_value does.

stored_value(item)[source]

Called when an item is being inserted into the list.

Return the object that will actually be stored.

To prevent incompatible items, subclasses may raise an exception here.

This method must undo any modifications that retrieved_value does.

LayerList

class tmxlib.LayerList(map, lst=None)[source]

A list of layers.

Allows indexing by name, and can only contain layers of a single map.

See NamedElementList for LayerList’s methods.

TilesetList

class tmxlib.TilesetList(map, lst=None)[source]

A list of tilesets.

Allows indexing by name.

Whenever the list is changed, GIDs of tiles in the associated map are renumbered to match the new set of tilesets.

See NamedElementList for TilesetList’s methods.

modification_context(*args, **kwds)[source]

Context manager that “wraps” modifications to the tileset list

While this manager is active, the map’s tiles are invalid and should not be touched. After all modification_contexts exit, tiles are renumbered to match the new tileset list. This means that multiple operations on the tileset list can be wrapped in a modification_context for efficiency.

If a used tileset is removed, an exception will be raised whenever the outermost modification_context exits.

Images

Image

class tmxlib.Image(data=None, trans=None, size=None, source=None)[source]

An image. Conceptually, an 2D array of pixels.

init arguments that become attributes:

data[source]

Data of this image, as read from disk.

size[source]

Size of the image, in pixels.

If given in constructor, the image doesn’t have to be decoded to get this information, somewhat speeding up operations that don’t require pixel access.

If it’s given in constructor and it does not equal the actual image size, an exception will be raised as soon as the image is decoded.

source

The file name of this image, if it is to be saved separately from maps/tilesets that use it.

trans

A color key used for transparency (currently not implemented)

Images support indexing (img[x, y]) as a shortcut for the get_pixel and set_pixel methods.

get_pixel(x, y)[source]

Get the color of the pixel at position (x, y) as a RGBA 4-tuple.

Supports negative indices by wrapping around in the obvious way.

set_pixel(x, y, value)[source]

Set the color of the pixel at position (x, y) to a RGBA 4-tuple

Supports negative indices by wrapping around in the obvious way.

Methods interesting for subclassers:

load_image()[source]

Load the image from self.data, and set self._size

If self._size is already set, assert that it equals

Note

It’s currently not possible to save modified images.

ImageRegion

class tmxlib.ImageRegion(image, top_left, size)[source]

A rectangular region of a larger image

init arguments that become attributes:

image

The “parent” image

top_left

The coordinates of the top-left corner of the region. Will also available as x and y attributes.

size

The size of the region. Will also available as width and height attributes.

Except for the constructor and attributes, ImageRegion supports the same external API as Image:

get_pixel(x, y)[source]
set_pixel(x, y, value)[source]

Exceptions

class tmxlib.TilesetNotInMapError[source]

Raised when trying to remove a tileset from a map that is uses its tiles