dosember-jam-2025/game/tilemap.lua

75 lines
2.2 KiB
Lua

TileMap = {}
TileMap.__index = TileMap
function TileMap:new(size, tiles, map, blendMode, canvasWidth, canvasHeight)
local this = {}
this.size = size
this.tiles = tiles or {}
this.map = map or {}
this.blendMode = blendMode
this.canvasWidth = canvasWidth or 320
this.canvasHeight = canvasHeight or canvasWidth or 200
this.offsetX = 0
this.offsetY = 0
this.tilesCanvasW = math.floor(this.canvasWidth / this.size)
this.tilesCanvasH = math.floor(this.canvasHeight / this.size)
this.canvas = love.graphics.newCanvas(this.canvasWidth, this.canvasHeight)
return setmetatable(this, TileMap)
end
function TileMap:random(x, y)
local map = {}
local tilesCount = #self.tiles
-- Заполнение массива
for i = 1, y do
map[i] = {}
for j = 1, x do
map[i][j] = math.random(1, tilesCount)
end
end
self.map = map
end
function TileMap:update()
if self.map[1] == nil then
return
end
local mapHeight = #self.map
local mapWidth = #self.map[1]
local x = self.offsetX
local y = self.offsetY
local jOffset = math.max(math.floor(x / self.size) + 1, 1)
local iOffset = math.max(math.floor(y / self.size) + 1, 1)
-- print(x, iOffset)
if jOffset > mapWidth or iOffset > mapHeight or -x >= self.canvasWidth or -y >= self.canvasHeight then
return
end
local jUpper = math.min(jOffset + self.tilesCanvasW, mapWidth)
local iUpper = math.min(iOffset + self.tilesCanvasH, mapHeight)
local prevCanvas = love.graphics.getCanvas()
love.graphics.setCanvas(self.canvas)
local prevBlendMode = love.graphics.getBlendMode()
love.graphics.setBlendMode(self.blendMode)
love.graphics.clear(0, 255, 0) -- TODO: debug
for i = iOffset, iUpper do
for j = jOffset, jUpper do
local tileIndex = self.map[i][j]
love.graphics.draw(self.tiles[tileIndex], self.size * (j - 1) - x, self.size * (i - 1) - y)
-- love.graphics.print(tostring(tileIndex), self.size * (j - 1) - x, self.size * (i - 1) - y)
end
end
love.graphics.setBlendMode(prevBlendMode)
love.graphics.setCanvas(prevCanvas)
end
function TileMap:draw(x, y)
love.graphics.draw(self.canvas, x, y)
end