diff --git a/lib/tile.lua b/lib/tile.lua new file mode 100644 index 0000000..ad72fb6 --- /dev/null +++ b/lib/tile.lua @@ -0,0 +1,51 @@ +--- @class TileMap +--- @field tileSize integer +--- @field atlas love.Image +local tileMap = {} +tileMap.__index = tileMap + +--- @param path table +local function load(path) + --- @type love.Image + local atlas = path.atlas + --- @type table + local manifest = path.manifest + + --- @type TileMap + local tiles = { + tileSize = manifest.tileSize, + atlas = atlas + } + manifest.tileSize = nil + + local layout = {} + for group, ids in pairs(manifest) do + for _, id in ipairs(ids) do + if layout[id] then + table.insert(layout[id], group) + else + layout[id] = { group } + end + end + end + + local cnt = 0 + for y = 0, atlas:getHeight() - 1, tiles.tileSize do + for x = 0, atlas:getWidth() - 1, tiles.tileSize do + if layout[cnt] then + for _, group in ipairs(layout[cnt]) do + if tiles[group] then + table.insert(tiles[group], love.graphics.newQuad(x, y, tiles.tileSize, tiles.tileSize, atlas)) + else + tiles[group] = { love.graphics.newQuad(x, y, tiles.tileSize, tiles.tileSize, atlas) } + end + end + end + cnt = cnt + 1 + end + end + + return setmetatable(tiles, tileMap) +end + +return { load = load } diff --git a/main.lua b/main.lua index 8d29dc6..992eeb3 100644 --- a/main.lua +++ b/main.lua @@ -14,13 +14,13 @@ local height = 30 function love.load() character.spawn("Hero", "warrior", Tree.assets.files.sprites.character) - Grass = Tree.assets.files.tiles.grass.atlas - Gr1 = love.graphics.newQuad(0, 32, 32, 32, Grass) - Tilemap = {} + Map = {} + TileMap2 = require("lib.tile").load(Tree.assets.files.tiles.grass) for y = 0, height - 1 do - Tilemap[y] = {} + Map[y] = {} for x = 0, width - 1 do - Tilemap[y][x] = love.graphics.newQuad(math.random(0, 7) * 32, math.random(0, 7) * 32, 32, 32, Grass) + local type = TileMap2["flower_grass"] + Map[y][x] = type[math.random(1, #type)] end end @@ -62,7 +62,7 @@ function love.draw() Tree.level.camera:attach() for y = 0, height - 1 do for x = 0, width - 1 do - love.graphics.draw(Grass, Tilemap[x][y], x, y, + love.graphics.draw(TileMap2.atlas, Map[x][y], x, y, nil, 1 / 32, 1 / 32) end end