If you’re making a game that uses levels or maps of some sort, why bother reinventing the wheel? Making your own map editor and custom file format might take a while and be troublesome at the end.

Tiled is this great map editor that takes an image (tileset), a scheme you draw (tilemap) and saves it a specific compressed format (.tmx). The editor has a nice interface, making anyone capable of creating maps and customizing them. Look up more features on the site.

This post will help you parse Tiled maps on your C++ application with tmx-parser.

Requirements

tmx-parser requires two libs – tinyxml and zlib.

You can install them yourself (and ask your users to do the same) on Debian-based distros like this:

$ sudo apt-get install libtinyxml-dev libzlib-dev

As an alternative, you can include their source codes on your application. This way, it’ll be more portable. To do that, download them at the links above and place them, say, inside a lib folder on your project.

Then, follow the same instructions as below with tmx-parser.

Installation

To use tmx-parser you’ll have to download it and use it along with your project.

Place it on a lib folder and adjust your Makefile to make sure they’re all compiled together – perhaps like this:

CFILES   = $(shell find lib/ -type f -name '*.c')
CXXFILES = $(shell find lib/ -type f -name '*.cpp')
 
OBJECTS = $(CFILES:.c=.o) $(CXXFILES:.cpp=.o)
 
# Keep your normal Makefile with $(OBJECTS) as the target

Usage

First, start the Tiled editor. You can get any tileset image around there and draw a map. After saving it as test.tmx, let’s do the programming.

#include "lib/Tmx.h"
 
int main()
{
    Tmx::Map map;
 
    map.ParseFile("test.tmx");
    if (map.HasError())
    {
        printf("Error loading map: %s", map.GetErrorText());
        return 1;
    }
 
    // How many layers the map has
    int layers = map.GetNumLayers();
 
    // Will get first layer anyway
    const Tmx::Layer* current_layer = map.GetLayer(0);
 
    int width = current_layer->GetWidth();
    int height = current_layer->GetHeight();
 
    // Now we'll get the actual map
    int map[width][height];
 
    // Retrieving each tile index
    for (int i = 0; i < width; i++)
        for (int j = 0; j < height; j++)
            map[i][j] = current_layer->GetTileId(i, j);
 
    // Do whatever you want with the map
 
    return 0;
}

As you can see, the actual map is a matrix of int . They contain the index of the tile. That index is the number of the image on your tileset.

Of course, this is just a test. You really should abstract that into a class. Since I’ve already done it, you might as well take a quick look.

Hope you enjoyed, any comments and critics are welcome!

Leave a reply

required

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">