I play chess alot, and i’m making a chess game. I obviously know all the rules and stuff but i’m having trouble trying to script the moves system for the pieces. I made a chessboard and named each square according to the files and ranks. but i’m dumbfounded on how i can actually script it.
If you know anything, or you have a resource that you can share. Please do tell me.
If squares are represented by Vector2s like Vector2(file, rank), then you just need to do some pretty simple math to find the possible squares where each piece could move. For example,
local function getBishopSquares(square:Vector2): {Vector2}
local allSquares = {}
local file, rank = square.X, square.Y
for i = 1,4 do
local rankDirection = if i == 1 or i == 2 then 1 else -1
local fileDirection = if i == 1 or i == 3 then 1 else -1
if rank + rankDirection > 8 or rank + rankDirection < 1 or file + fileDirection > 8 or file + fileDirection < 1 then continue end
local rank, file = rank, file -- Localize rank and file for the repeat loop
repeat
local newSquare = Vector2.new(file + fileDirection, rank + rankDirection)
table.insert(allSquares,newSquare)
file, rank = newSquare.X, newSquare.Y
until file >= 8 or file <= 1 or rank >= 8 or rank <= 1
-- Also check if another piece already occupies this new square
end
return allSquares
end
local function getRookSquares(square:Vector2): {Vector2}
local allSquares = {}
local file, rank = square.X, square.Y
for i = 1,4 do
local rankDirection = if i == 1 then 1 elseif i == 2 then -1 else 0
local fileDirection = if i == 3 then 1 elseif i == 4 then -1 else 0
if rank + rankDirection > 8 or rank + rankDirection < 1 or file + fileDirection > 8 or file + fileDirection < 1 then continue end
local rank, file = rank, file -- Localize rank and file for the repeat loop
repeat
local newSquare = Vector2.new(file + fileDirection, rank + rankDirection)
table.insert(allSquares,newSquare)
file, rank = newSquare.X, newSquare.Y
until file >= 8 or file <= 1 or rank >= 8 or rank <= 1
end
return allSquares
end