lines-lua/grid.lua
2025-05-20 17:03:47 +03:00

76 lines
1.8 KiB
Lua

require "config"
-- Game grid table, acts as "global level" of some sort
Grid = {}
-- Factory function
function Grid:new( size )
local grid = {
lines = {},
size = size
}
setmetatable( grid, { __index = self } )
return grid
end
-- Add new line to grid
function Grid:push( line )
table.insert( self.lines, line )
end
-- Draw lines and the whole grid
function Grid:draw()
-- Draw lines
for _, line in ipairs( self.lines ) do
line:draw()
end
-- Draw grid
for x = 1, self.size.x do
for y = 1, self.size.y do
local px, py = x * Config.cellSize, y * Config.cellSize
love.graphics.circle( "fill", px - Config.cellSize / 2, py - Config.cellSize / 2, Config.pointRadius)
end
end
end
-- Check all lines and return one, which contains point (if any)
function Grid:matchesLine( point, ignoreEnd )
local line = self.lines[tableFind( self.lines, point,
function( value, innervalue )
return innervalue:has( value )
end
)]
if line ~= nil and not ignoreEnd then
if line.startpoint:equals( point ) then
line:clear()
line:push( line.startpoint )
end
if line.endpoint:equals( point ) then
line:clear()
line:reverse()
return line
end
end
-- Try to check endpoint
if line == nil and not ignoreEnd then
line = self.lines[tableFind( self.lines, point,
function( value, innervalue )
if innervalue.endpoint:equals( value ) then
innervalue:clear()
innervalue:reverse()
return true
end
return false
end
)]
end
return line
end
function Grid:inBounds( point )
return point.x <= self.size.x and point.y <= self.size.y
end