Skip to content

Instantly share code, notes, and snippets.

@flyte
Created August 23, 2013 19:56
Show Gist options
  • Save flyte/6323333 to your computer and use it in GitHub Desktop.
Save flyte/6323333 to your computer and use it in GitHub Desktop.
Draw TMX tiles in pygame and save them as an image
import pygame, pytmx, argparse
def draw_tmx(tmx, window):
# For each layer
for l in xrange(0, len(tmx.tilelayers)):
# For each y tile coordinate
for y in xrange(0, tmx.height):
# For each x tile coordinate
for x in xrange(0, tmx.width):
# try not strictly necessary, but a hangover from some old bad code
try:
tile = tmx.getTileImage(x, y, l)
except Exception, e:
print e
continue
# If there is no tile to draw, tile will be 0
if tile:
x_pos = x * tmx.tilewidth
# pygame renders tiles from top left and Tiled renders them
# from bottom left. This means that if the tile image is
# taller than the tile height, pygame will draw it downwards
# instead.
y_pos = (y * tmx.tileheight) - tile.get_height() + tmx.tileheight
window.blit(tile, (x_pos, y_pos))
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("tmx_file")
p.add_argument("output_file")
args = p.parse_args()
pygame.init()
# We can't load_pygame yet because we haven't set our display up and we
# can't do that until we've figured out what size it needs to be..
tmx = pytmx.tmxloader.load_tmx(args.tmx_file)
window = pygame.display.set_mode((
tmx.width * tmx.tilewidth, tmx.height * tmx.tileheight))
tmx = pytmx.tmxloader.load_pygame(args.tmx_file, pixelalpha=True)
draw_tmx(tmx, window)
pygame.display.flip()
pygame.image.save(window, args.output_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment