How do I load a chess position with a fen string?

Hello World!

So I was currently following a tutorial on how to make a chess game. [ Tutorial is not in Roblox, and also not in lua ]

And I’m still stuck with this part after a few days.

I can’t seem to wrap my head around it. I do not know much about strings as I rarely use them. Does anyone know how I could implement this?

Thanks in advance!

Assuming you just want to know how to implement this without an explanation, here’s the implementation of that same fenString in Luau:

local startFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR"
local squares = {}

local function loadPositionFromFen(fen: string)
    local pieceTypeFromSymbol = {
        -- this is supposed to be a table with objects instead of strings, but for
        -- this example i'm just using strings for simplicity
        k = "King",
        q = "Queen",
        b = "Bishop",
        r = "Rook",
        n = "Knight",
        p = "Pawn",
    }

    local fenStringLength = string.len(fen)
    local file, rank = 0, 7
    local symbol

    for i = 1, fenStringLength do
        symbol = string.sub(fen, i, i)
        if symbol == "/" then
            file = 0
            rank -= 1
        else
            if tonumber(symbol) then
                file += tonumber(symbol)
            else
                local pieceColor = string.match(symbol, "%u") and "White" or "Black"
                local pieceType = pieceTypeFromSymbol[string.lower(symbol)]
                -- the below concats the color and the piece type, example:
                -- "WhiteRook"
                squares[rank*8 + file] = pieceColor .. pieceType
                file += 1
            end
        end
    end
end

loadPositionFromFen(startFEN)
print(squares) -- this should print a numerically-keyed table with the pieces as strings

Thank you, but I forgot that I already developed a script about it. I will still give you the solution button though. Thanks again!

2 Likes

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