achrisfling     game dev     reviews     feed

Kivy & Tiled

Kivy is an attractive library for developing cross-platform projects for Windows/OS X/Android/iOS with Python. I have been experimenting with some 2D game structures for use with Kivy. One of the first things I always want to use in my projects is Tiled, which is a nice utility for creating tile-based maps. There is a library called PyTMX that loads the .tmx files created by Tiled, and it has a very straightforward interface for interacting with the maps. It also basically requires nothing other than an overload of the loadTileImages() function to be used with Kivy.

I've created a simple child class of the TiledMap here which implements this function, so when it's created it will capture the regions of the tileset images that are used as tiles.

To actually get this drawing on the screen, I created a simple example widget that loads my "Ground" tile layer:

class TileGrid(GridLayout):
    """Creates a Kivy grid and puts the tiles in a KivyTiledMap in it."""
    map_filepath = StringProperty('map.tmx')

    def __init__(self, **kwargs):
        self.map = KivyTiledMap(self.map_filepath)

        super(TileGrid, self).__init__(
            rows=self.map.height, cols=self.map.width,
            row_force_default=True,
            row_default_height=self.map.tileheight,
            col_force_default=True,
            col_default_width=self.map.tilewidth,
            **kwargs
        )

        tilelayer_index = 0
        for tile in self.map.getTileLayerByName('Ground'):
            texture = self.map.getTileImage(tile[0], tile[1], 0)
            self.add_widget(Image(texture=texture, size=texture.size))
            tilelayer_index += 1

This widget isn't quite the most robust widget right now (I just got it drawing), but the point is it's not too bad getting Tiled stuff displaying in a Kivy application.