How to march tiles together like in Terraria?

by Tyyppi_77   Last Updated April 10, 2015 00:05 AM

I've been trying to get tile marching to work like in Terraria, and I got something to work. I don't think it's actually very good way of doing this, so I'm wondering what would be really the main way of doing this.

Here's a picture of what I want to accomplish:


As you can see, this really does the thing that I want, but it's so horrible looking and it'd be a pain to extend for different types of tiles.

Here is my code for this. I coded this as a test, so my full game would use tile classes etc.

for x, tile in enumerate(row):
    if tile:
            air = row[x + 1]
        except Exception:
            if not air:
                if not LEVEL[y - 1][x]:
                    tile = 3
                    tile = 6
        air = row[x - 1]
        if not air:
            if not LEVEL[y - 1][x]:
                if tile == 3:
                    tile = 5
                    tile = 4
                if tile == 6:
                    tile = 8
                    tile = 7
        LEVEL[y][x] = tile
for y, row in enumerate(LEVEL):
    for x, tile in enumerate(row):
        if LEVEL[y - 1][x] in (6, 3, 14):
            pos = LEVEL[y][x + 1]
        except Exception as e:
            if pos in (2, 3):
                LEVEL[y][x] = 11
    if LEVEL[y - 1][x] in (7, 4, 15):
        pos = LEVEL[y][x - 1]
        if pos in (2, 4):
            LEVEL[y][x] = 12
    if LEVEL[y - 1][x] in (5, 8):
        if LEVEL[y][x] == 1:
            LEVEL[y][x] = 13
    if LEVEL[y][x] == 6:
        if LEVEL[y][x - 1] in (2, 4):
            LEVEL[y][x] = 14
    if LEVEL[y][x] == 7:
            tile = LEVEL[y][x + 1]
        except Exception as e:
        if tile in (2, 3):
            LEVEL[y][x] = 15

The basic idea behind this is just to look for some air and dirt, and set the tiles image from those.

Basically then when I'm drawing this I just take the value at a coord and blit the corresponding image to the screen.

So how would I go about making this as readable and easily extendable as possible? Does anyone know how Terraria handles this?

Answers 1

If I understand right, your map stores whether something is dirt or air, and the simplest thing would be to have dirt and air tiles. However, to make things look better, you have separate images for air above dirt, dirt above air, dirt left of air, and so on. So you're trying to figure out which image to use, given a tile and its neighbors. Is that right?

If so, take a look at one of these articles:

October 13, 2013 17:02 PM

Related Questions

Paint game level algorithm

Updated April 10, 2015 00:05 AM

How to apply wall objects to tiles efficiently

Updated May 04, 2017 02:13 AM

Terrain Rendering/Update Failure Python 3.x

Updated June 18, 2018 17:13 PM