Hi. I’m making a chess game in roblox using OOP, and I’m very new to it, but basically, whenever I create a new chess piece object and the module edits the properties of the object inside the new piece function, all of the chess piece’s properties get edited. I know this is how inheritance works, but I just can’t find out a way to have each chess piece object have their own set properties on creation. I did try to use an init function inside of the new piece function, but I know I also can’t call the init function inside of the neew piece function, and I would have to instead call init in the main script every time I create a new piece, which I obviously don’t want to do.
Here’s the code so far, (and other suggestions with my oop code would be appreciated)
(ModuleScript)
local gui = script.Parent
local pieces = gui:WaitForChild("Pieces")
local board = gui:WaitForChild("Board"):WaitForChild("Squares")
local Chess = {}
Chess.__index = Chess
local function getLocation(position)
local location = board:FindFirstChild(position)
assert(location, "Invalid position")
return location
end
local function getAvailableSquares(piece)
return {}
end
function Chess.new()
local ChessGame = {}
function ChessGame:NewPiece(pieceType, position)
local piece = {}
piece.__index = piece
function piece:_init(pieceType, position)
local folder = pieces:FindFirstChild(pieceType:sub(1, 5))
assert(folder, "Invalid color name")
local pieceInstance = folder:FindFirstChild(pieceType:sub(6))
assert(pieceInstance, "Invalid piece name")
local location = getLocation(position)
self.Name = pieceType:sub(6)
self.Color = pieceType:sub(1, 5)
self.Position = position
self._instance = pieceInstance:Clone()
self.Data = {AvailableSquares = {}}
self._instance:SetAttribute("Captured", false)
self._instance.AttributeChanged:Connect(function(attribute)
if attribute == "Captured" and self._instance:GetAttribute("Captured") then
self._instance:Destroy()
end
end)
self._instance.Destroying:Connect(function()
setmetatable(self, nil)
end)
self._instance.Visible = true
self._instance.Parent = location
end
function piece:Move(position)
local location = getLocation(position)
local capturedPiece = location:FindFirstChildOfClass("Frame")
if capturedPiece then
capturedPiece:SetAttribute("Captured", true)
end
self._instance.Parent = location
self.Position = position
end
function piece:CheckSquare(position)
if getAvailableSquares(self)[position] then
return true
end
end
piece:_init(pieceType, position)
return setmetatable(self, piece)
end
return setmetatable(ChessGame, Chess)
end
return Chess
(LocalScript)
local gui = script.Parent
local ChessGame = require(gui:WaitForChild("ChessModule")).new()
local king = ChessGame:NewPiece("WhiteKing", "F2")
local blackPawn = ChessGame:NewPiece("BlackPawn", "G2")
task.wait(3)
king:Move("G2")
One last thing to note here, each square on the board is a frame in the gui, represented by the column/file (letter), and rank/row (number).