pythonpygametilespytmx

How to import an tmx map in pygame?


I have made a *tmx map in the Tiled Editor program. Then I tried to import it into my game. When I change the variable layers to 0 it works, but there is only 1 tile on the screen. I want to print the entire map on my screen. But I get the following error.

Traceback (most recent call last):
  File "C:\Users\LL\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pytmx\pytmx.py", line 512, in get_tile_image
    layer = self.layers[layer]
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\LL\Desktop\Erik\RPG_project\RPG project\data\main.py", line 143, in <module>
    game_initialize()
  File "C:\Users\LL\Desktop\Erik\RPG_project\RPG project\data\main.py", line 117, in game_initialize
    map_setup()
  File "C:\Users\LL\Desktop\Erik\RPG_project\RPG project\data\main.py", line 140, in map_setup
    image = tmxdata.get_tile_image(0, 0, 2)
  File "C:\Users\LL\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pytmx\pytmx.py", line 514, in get_tile_image
    raise ValueError
ValueError

I think it has to do with my layers. I have only 1 layer for my map. Still my script doesnt work. I also use Base64 (compressed) for my map. And 32 pixels large tiles.

from pytmx import load_pygame

def map_setup():
    global image

    # Getting / Importing the map
    tmxdata = load_pygame("Tile_files\\mymap2.tmx")

    image = tmxdata.get_tile_image(0, 0, 1) # x, y, layer

Solution

  • Because tile seems only (0,0) position. You have to gave loops the layers. I wrote this code maybe help you.

    from pytmx import load_pygame, TiledTileLayer
    
    def map_setup():
        global image
    
        # Getting / Importing the map
        tmxdata = load_pygame("Tile_files\\mymap2.tmx")
        width = tmxdata.width * tmxdata.tilewidth
        height = tmxdata.height * tmxdata.tileheight
    
        ti = tmxdata.get_tile_image_by_gid
        for layer in tmxdata.visible_layers:
            if isinstance(layer, TiledTileLayer):
                for x, y, gid, in layer:
                    tile = ti(gid)
                    if tile:
                        image = tmxdata.get_tile_image(x, y, layer)
    

    By the way, excuse me for my language. Hopefully works.

    Edit: You can look this video detailed for import tmx map in pygame. Video link: https://www.youtube.com/watch?v=QIXyj3WeyZM