I would like to know how to determine if a move in the game of checkers, also known as draughts, is legal or not.
Whenever I have tried to create this function, only one aspect has worked properly while many others have not.
Below is half of the script, which includes everything that is necessary.
function createCheckerboard(boardSize, squareSize, whiteColor, blackColor)
-- Set default values for the function parameters
boardSize = boardSize or 8
squareSize = squareSize or 1
whiteColor = whiteColor or BrickColor.new("White")
blackColor = blackColor or BrickColor.new("Black")
local squares = {}
local folder = Instance.new("Folder", workspace)
folder.Name = "CheckerBoard"
-- Loop through the rows and columns of the checkerboard
for row = 1, boardSize do
for col = 1, boardSize do
local square = Instance.new("Part", folder)
square.Anchored = true
square.Position = Vector3.new((row - 1) * squareSize - (boardSize / 2) * squareSize, 0.5, (col - 1) * squareSize - (boardSize / 2) * squareSize)
square.Size = Vector3.new(squareSize, 0, squareSize)
square.Material = Enum.Material.Wood
square.Name = row..col
if (row + col) % 2 == 0 then
square.BrickColor = whiteColor
else
square.BrickColor = blackColor
Instance.new("ClickDetector", square)
end
table.insert(squares, square)
end
end
return squares;
end
function placeCheckersPiece(board, row, col, pieceModel)
-- Find the square at the specified row and column
local square = board[(row - 1) * 8 + col]
-- Place the checkers piece on the square
local piece = pieceModel:Clone()
piece.Parent = square
piece:MoveTo(square.Position + Vector3.new(0, 1, 0))
end
function isLegalMove(board, fromRow, fromCol, toRow, toCol, plr)
-- Check if the move is within the bounds of the board
if fromRow < 1 or fromRow > 8 or fromCol < 1 or fromCol > 8 or toRow < 1 or toRow > 8 or toCol < 1 or toCol > 8 then
warn("Over the bounds")
return false
end
return true
end
function moveCheckersPiece(board, fromRow, fromCol, toRow, toCol, plr)
-- Find the square that the piece is currently on
local fromSquare = board[(fromRow - 1) * 8 + fromCol]
-- Find the square that the piece will be moved to
local toSquare = board[(toRow - 1) * 8 + toCol]
-- Get the checkers piece that is on the from square
local piece = fromSquare:FindFirstChildWhichIsA("Model")
-- Make sure there is a piece on the from square
if piece then
-- Check if the move is legal
if isLegalMove(board, fromRow, fromCol, toRow, toCol, plr) then
-- Move the piece to the to square
if piece then
piece:MoveTo(toSquare.Position + Vector3.new(0, 1, 0))
end
else
-- Print an error message
print("Illegal move!")
end
else
-- Print an error message
print("There is no piece on the from square!")
end
end