tilerotate-demo/mechanism.lua
2025-10-30 00:09:34 +03:00

75 lines
2 KiB
Lua

require 'tablefuncs'
require 'gridpoint'
require 'port'
---@param xcorner GridPoint
---@param size GridPoint
---@return GridPoint
local function nextxcorner( xcorner, size )
-- We're looking for old size
local cornerLookup1 = {
GridPoint:new( 0, 0 ),
GridPoint:new( size.y - 1, 0 ),
GridPoint:new( size.y - 1, size.x - 1 ),
GridPoint:new( 0, size.x - 1 )
}
local cornerLookup2 = {
GridPoint:new( 0, 0 ),
GridPoint:new( size.x - 1, 0 ),
GridPoint:new( size.x - 1, size.y - 1 ),
GridPoint:new( 0, size.y - 1 )
}
local index = TableFind(cornerLookup1, xcorner, function(xc, value) return value:equals(xc) end)
if index < #cornerLookup1 then
index = index + 1
else
index = 0
end
return cornerLookup2[index]
end
---@class Mechanism
---@field position GridPoint
---@field size GridPoint
---@field xcorner GridPoint
---@field ports Port[]
---@field color table
Mechanism = {
position = GridPoint:new( 0, 0 ),
size = GridPoint:new( 1, 1 ),
xcorner = GridPoint:new( 0, 0 ),
ports = {},
color = { 0.5, 0.5, 0.5, 1 }
}
function Mechanism:new( position, size, ports, color )
local mechanism = {
position = position or self.position,
size = size or self.size,
ports = ports or {},
color = color or self.color
}
setmetatable( mechanism, { __index = self } )
return mechanism
end
function Mechanism:rotateClockwise()
self.size = GridPoint:new(self.size.y, self.size.x)
self.xcorner = nextxcorner(self.xcorner, self.size)
for _, port in ipairs(self.ports) do
port:rotateClockwise()
end
end
function Mechanism:draw()
love.graphics.setColor(self.color)
local x, y = self.position:globalCoords()
local w, h = self.size:globalCoords()
love.graphics.rectangle("fill", x, y, w, h)
for _, port in ipairs(self.ports) do
local offset = GridPoint:new( self.position.x + self.xcorner.x, self.position.y + self.xcorner.y )
port:draw( offset )
end
end