I have a question for chess players in here. How do you script the chess system?

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.

2 Likes

As far as going to the functionality and player to player game play, this video may help you.

1 Like

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
1 Like

If you want you can store the square as a number from 1 to 64, it’s super easy to convert between a number and a Vector2

local function vector2ToNumber(vector2:Vector2):number
	return (vector2.Y - 1) * 8 + vector2.X 
end

local function numberToVector2(number:number):Vector2
	return Vector2.new((number - 1) % 8 + 1, (number - 1) // 8 + 1)
end
1 Like

Oh this is awesome! I see how it works now, thank you! I never thought of making the squares a vector2.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.