Home > Back-end >  There's a good method to create a tilemap from an ascii matrix?
There's a good method to create a tilemap from an ascii matrix?

Time:08-13

The idea is simple, but the execution is bothering me. I've created a small random dungeon generator that create a grid like this:

000001
000111
000111
001101
011101
011111

This is a sample 6x6 dungeon where 0 is a wall and 1 is an open path.

The conversion from this to some sort of tile id map is simple, and trivial, but creating the image itself is the hard part.

I want to know if there's a lib, or method to achieve that. If not, then what would you do?

This is not part of a game, and only a dungeon generator for DND. Any language is OK, but the generator was made in Go.

CodePudding user response:

I kind of managed to get a solution, but it will be a Python only. Using PIL I can make a mosaic with tile images and create the map. It's not a solid solution made from scratch but it can do the Job.

I'm still open for another approach.

CodePudding user response:

You can use OpenCV for this task. Probably PIL can do the same, don't have exp with it.

import cv2
import numpy as np

data_list = [
    [0, 0, 0, 0, 0, 1],
    [0, 0, 0, 1, 1, 1],
    [0, 0, 0, 1, 1, 1],
    [0, 0, 1, 1, 0, 1],
    [0, 1, 1, 1, 0, 1],
    [0, 1, 1, 1, 1, 1]
]

arr = np.array(data_list, dtype=np.uint8) * 255
arr = cv2.resize(arr, (0, 0), fx=50, fy=50, interpolation=cv2.INTER_NEAREST)
cv2.imshow("img", arr)
cv2.waitKey()

# or you can save on disk
cv2.imwrite("img.png", arr)

CodePudding user response:

use np.block()

# a bunch of sprites/images, all the same size
# load them however you like
tiles = [...]

data_list = [
    [0, 0, 0, 0, 0, 1],
    [0, 0, 0, 1, 1, 1],
    [0, 0, 0, 1, 1, 1],
    [0, 0, 1, 1, 0, 1],
    [0, 1, 1, 1, 0, 1],
    [0, 1, 1, 1, 1, 1]
]

picture = np.block([
    [tiles[k] for k in row]
    for row in data_list
])

Or, if you use any kind of game engine, or something even more trivial, like SDL/PyGame, simply "blit" each tile.

PIL, as you found out, is perfectly capable of blitting one image (tile) onto another (whole map).

  • Related