From c252c31d3b57436b8261d1a03f4d555fd7385587 Mon Sep 17 00:00:00 2001 From: Josh Date: Sun, 10 Aug 2025 15:44:53 -0400 Subject: [PATCH 1/6] Remove comment --- makefile | 2 -- 1 file changed, 2 deletions(-) diff --git a/makefile b/makefile index d3562c7..c2c9531 100644 --- a/makefile +++ b/makefile @@ -1,5 +1,3 @@ -# Makefile at project root - CC := gcc CFLAGS := -O3 -fPIC -Wall -Wextra LDFLAGS := -shared -- 2.34.1 From d8e42552ee2ccd8d59af2e6f474075f03c2f845b Mon Sep 17 00:00:00 2001 From: Josh Date: Sun, 10 Aug 2025 15:45:25 -0400 Subject: [PATCH 2/6] Remove os check --- makefile | 7 ------- 1 file changed, 7 deletions(-) diff --git a/makefile b/makefile index c2c9531..0e4d9f7 100644 --- a/makefile +++ b/makefile @@ -7,13 +7,6 @@ INCDIR := engine/include BUILDDIR := build LIBNAME := libchess -UNAME_S := $(shell uname -s) -ifeq ($(UNAME_S),Darwin) - SOEXT := dylib -else - SOEXT := so -endif - SRC := $(wildcard $(SRCDIR)/*.c) OBJ := $(patsubst $(SRCDIR)/%.c,$(BUILDDIR)/%.o,$(SRC)) LIB := $(BUILDDIR)/$(LIBNAME).$(SOEXT) -- 2.34.1 From d462f82c8e39fc0da3a684d2cad522d08a0d5f71 Mon Sep 17 00:00:00 2001 From: Josh Date: Fri, 15 Aug 2025 12:59:00 -0400 Subject: [PATCH 3/6] Fix makefile --- makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/makefile b/makefile index 0e4d9f7..862f0ab 100644 --- a/makefile +++ b/makefile @@ -9,7 +9,7 @@ LIBNAME := libchess SRC := $(wildcard $(SRCDIR)/*.c) OBJ := $(patsubst $(SRCDIR)/%.c,$(BUILDDIR)/%.o,$(SRC)) -LIB := $(BUILDDIR)/$(LIBNAME).$(SOEXT) +LIB := $(BUILDDIR)/$(LIBNAME).so .PHONY: all clean clean-pycache test -- 2.34.1 From 4d2cccd3850cae5acb35647c0c1305b8b1e8722d Mon Sep 17 00:00:00 2001 From: Josh Date: Fri, 15 Aug 2025 15:12:07 -0400 Subject: [PATCH 4/6] Remove build always regardless of test pass --- makefile | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/makefile b/makefile index 862f0ab..b8f210a 100644 --- a/makefile +++ b/makefile @@ -11,27 +11,31 @@ SRC := $(wildcard $(SRCDIR)/*.c) OBJ := $(patsubst $(SRCDIR)/%.c,$(BUILDDIR)/%.o,$(SRC)) LIB := $(BUILDDIR)/$(LIBNAME).so -.PHONY: all clean clean-pycache test +.PHONY: all clean test all: $(LIB) $(BUILDDIR): @mkdir -p $(BUILDDIR) -# compile each .c into build/*.o $(BUILDDIR)/%.o: $(SRCDIR)/%.c | $(BUILDDIR) $(CC) $(CFLAGS) -I$(INCDIR) -c $< -o $@ -# link shared library $(LIB): $(OBJ) $(CC) $(LDFLAGS) -o $@ $^ clean: - @echo "Cleaning Python caches..." - @find . -type d -name "__pycache__" -exec rm -rf {} + - @find . -type d -name ".pytest_cache" -exec rm -rf {} + + @echo "Cleaning build and Python caches..." + @rm -rf $(BUILDDIR) + @find . -type d -name "__pycache__" -exec rm -rf {} + + @find . -type d -name ".pytest_cache" -exec rm -rf {} + @find . -type f \( -name "*.pyc" -o -name "*.pyo" \) -delete -# run Python unit tests -test: all - python3 -m unittest -v && $(MAKE) clean +# Always rebuild, and always clean afterward (even if tests fail) +test: + @$(MAKE) clean + @$(MAKE) all + @python3 -m unittest -v; \ + status=$$?; \ + $(MAKE) clean; \ + exit $$status -- 2.34.1 From db115213297e58669aee1cc6e428a112f1ea6f45 Mon Sep 17 00:00:00 2001 From: Josh Date: Fri, 15 Aug 2025 15:32:50 -0400 Subject: [PATCH 5/6] Add fen parser and board loading --- engine/include/bitboard.h | 25 +++++--- engine/src/fen.c | 116 ++++++++++++++++++++++++++++++++++++++ test/test_fen_loader.py | 104 ++++++++++++++++++++++++++++++++++ 3 files changed, 236 insertions(+), 9 deletions(-) create mode 100644 engine/src/fen.c create mode 100644 test/test_fen_loader.py diff --git a/engine/include/bitboard.h b/engine/include/bitboard.h index 381a371..7e1f246 100644 --- a/engine/include/bitboard.h +++ b/engine/include/bitboard.h @@ -20,8 +20,16 @@ #define RANK_7 0x00FF000000000000ULL #define RANK_8 0xFF00000000000000ULL -enum Color { WHITE = 0, BLACK = 1 }; -enum Piece { PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING, PIECE_N = 6 }; +#define SET_BIT(bb, sq) ((bb) |= (1ULL << (sq))) +#define CLEAR_BIT(bb, sq) ((bb) &= ~(1ULL << (sq))) +#define GET_BIT(bb, sq) ((bb) & (1ULL << (sq))) +#define TOGGLE_BIT(bb, sq) ((bb) ^= (1ULL << (sq))) + +enum Color { WHITE = 0, BLACK = 1, BOTH = 2 }; +enum Piece { + P, N, B, R, Q, K, // 0..5 white + p, n, b, r, q, k // 6..11 black +}; enum Castling { CASTLE_WK = 1 << 0, @@ -31,18 +39,17 @@ enum Castling { }; struct Board { - uint64_t bb[2][PIECE_N]; // Each set of pieces get a bitboard for each player. - uint64_t occ[2]; // Color occupancy bitboards. - uint64_t occ_both; // occ[WHITE] | occ[BLACK] + uint64_t pieces[12]; // Each set of pieces get a bitboard for each player. + uint64_t occ[3]; // Color occupancy bitboards. uint64_t king_square[2]; - uint8_t castling; - uint64_t ep_square; + uint8_t castling_rights; + int ep_square; enum Color side_to_move; - uint16_t halfmove_clock; - uint16_t fullmove_number; + int halfmove_clock; + int fullmove_number; }; void create_knight_attack_cache(void); diff --git a/engine/src/fen.c b/engine/src/fen.c new file mode 100644 index 0000000..bef7b6a --- /dev/null +++ b/engine/src/fen.c @@ -0,0 +1,116 @@ +#include +#include +#include +#include +#include +#include "bitboard.h" + + +int square_index(int file, int rank) { + return rank*8 + file; +} + +int char_to_piece_index(char c) { + switch (c) { + case 'P': return P; case 'N': return N; case 'B': return B; + case 'R': return R; case 'Q': return Q; case 'K': return K; + case 'p': return p; case 'n': return n; case 'b': return b; + case 'r': return r; case 'q': return q; case 'k': return k; + default: return -1; + } +} + +int load_fen(struct Board *board, const char *fen) { + int rank = 7, file = 0; + const char *ptr = fen; + + // Place pieces into the board. + while (*ptr && *ptr != ' ') { + if (isdigit(*ptr)) { + file += *ptr - '0'; + ptr++; + } else if (isalpha(*ptr)) { + if (file >= 8) return -1; + + int piece = char_to_piece_index(*ptr); + + if (piece == -1) return -1; + + SET_BIT(board->pieces[piece], rank * 8 + file); + file++; + ptr++; + } else if (*ptr == '/') { + // Each rank must have exactly 8 files + if (file != 8) return -1; + rank--; + file = 0; + ptr++; + } else { + // Unexpected character + return -1; + } + } + + if (rank != 0 || file != 8) return -1; + ptr++; + + // Side to move. + if (*ptr != 'w' && *ptr != 'b') return -1; + + board->side_to_move = (*ptr == 'w') ? WHITE : BLACK; + ptr += 2; + + // Castling rights. + board->castling_rights = 0; + while (*ptr && *ptr != ' ') { + switch (*ptr) { + case 'K': board->castling_rights |= CASTLE_WK; break; + case 'Q': board->castling_rights |= CASTLE_WQ; break; + case 'k': board->castling_rights |= CASTLE_BK; break; + case 'q': board->castling_rights |= CASTLE_BQ; break; + case '-': break; + default: return -1; + } + ptr++; + } + + if (*ptr != ' ') return -1; + ptr++; + + // En Passant square. + if (*ptr == '-') { + board->ep_square = -1; + ptr += 2; + } else { + if (ptr[0] < 'a' || ptr[0] > 'h' || ptr[1] < '1' || ptr[1] > '8') return -1; + + // Strict FEN: Rank must be 3 or 6. + char rank_char = ptr[1]; + if (rank_char != '3' && rank_char != '6') return -1; + + int file = ptr[0] - 'a'; + int rank = ptr[1] - '1'; + + + + board->ep_square = square_index(file, rank); + ptr += 3; + } + + // Parse halfmove clock for the game. + board->halfmove_clock = atoi(ptr); + while (*ptr && *ptr != ' ') ptr++; + if (*ptr == ' ') ptr++; + + // Parse the fullmove number. + board->fullmove_number = atoi(ptr); + + int num_pieces = 6; + for (int i = 0; i < num_pieces; i++) { + board->occ[WHITE] |= board->pieces[i]; // white + board->occ[BLACK] |= board->pieces[i + 6]; // black + } + board->occ[BOTH] = board->occ[WHITE] | board->occ[BLACK]; + + return 0; +} \ No newline at end of file diff --git a/test/test_fen_loader.py b/test/test_fen_loader.py new file mode 100644 index 0000000..088b0ff --- /dev/null +++ b/test/test_fen_loader.py @@ -0,0 +1,104 @@ +import ctypes +from test.base import ChessLibTestBase +from test.base import BLACK +from test.base import WHITE +from test.base import sq +from test.base import popcount + + +class Board(ctypes.Structure): + _fields_ = [ + ("pieces", ctypes.c_uint64 * 12), + ("occ", ctypes.c_uint64 * 3), + ("king_square", ctypes.c_uint64 * 2), + ("castling_rights", ctypes.c_uint8), + ("ep_square", ctypes.c_int), + ("side_to_move", ctypes.c_int), + ("halfmove_clock", ctypes.c_int), + ("fullmove_number", ctypes.c_int), + ] +class FenTests(ChessLibTestBase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.lib.load_fen.argtypes = [ctypes.POINTER(Board), ctypes.c_char_p] + cls.lib.load_fen.restype = ctypes.c_int + + + def rank_mask(self, r): + return sum(1 << (r*8 + f) for f in range(8)) + + + def test_startpos_fields_and_occupancies(self): + fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" + b = Board() + + self.lib.load_fen(ctypes.byref(b), fen.encode("ascii")) + + self.assertEqual(b.side_to_move, WHITE) + self.assertEqual(b.castling_rights, 0b1111) # KQkq + self.assertEqual(b.ep_square, -1) + self.assertEqual(b.halfmove_clock, 0) + self.assertEqual(b.fullmove_number, 1) + + white_expected = self.rank_mask(0) | self.rank_mask(1) # ranks 1 & 2 + black_expected = self.rank_mask(6) | self.rank_mask(7) # ranks 7 & 8 + self.assertEqual(int(b.occ[WHITE]), white_expected) + self.assertEqual(int(b.occ[BLACK]), black_expected) + self.assertEqual(int(b.occ[2]), white_expected | black_expected) + + self.assertEqual(popcount(int(b.occ[WHITE])), 16) + self.assertEqual(popcount(int(b.occ[BLACK])), 16) + + + def test_castling_flags_parsing(self): + fen = "r3k2r/8/8/8/8/8/8/R3K2R b KQkq - 5 42" + b = Board() + self.lib.load_fen(ctypes.byref(b), fen.encode("ascii")) + self.assertEqual(b.side_to_move, BLACK) + self.assertEqual(b.castling_rights, 0b1111) + self.assertEqual(b.halfmove_clock, 5) + self.assertEqual(b.fullmove_number, 42) + + + def test_en_passant_targets(self): + # EP at e6, black to move + fen1 = "8/8/8/3pP3/8/8/8/8 b KQkq e6 0 1" + + b1 = Board() + self.lib.load_fen(ctypes.byref(b1), fen1.encode("ascii")) + self.assertEqual(b1.side_to_move, BLACK) + self.assertEqual(b1.ep_square, sq("e6")) + + # EP at d3, white to move + fen2 = "8/8/8/8/3Pp3/8/8/8 w KQkq d3 12 7" + b2 = Board() + self.lib.load_fen(ctypes.byref(b2), fen2.encode("ascii")) + self.assertEqual(b2.side_to_move, WHITE) + self.assertEqual(b2.ep_square, sq("d3")) + + + def test_malformed_piece_field(self): + # rank sums wrong (9 on a rank), bad char, missing separators + bad = [ + "9/8/8/8/8/8/8/8 w - - 0 1", + "8/8/8/8/8/8/8/7x w - - 0 1", + "8/8/8/8/8/8/8/8w - - 0 1", + ] + for fen in bad: + b = Board() + r = self.lib.load_fen(ctypes.byref(b), fen.encode("ascii")) + self.assertEqual(r, -1) + + + def test_malformed_side_castling_ep(self): + bad = [ + "8/8/8/8/8/8/8/8 x - - 0 1", # bad side + "8/8/8/8/8/8/8/8 w KX - 0 1", # bad castling char + "8/8/8/8/8/8/8/8 w - j9 0 1", # bad EP square + "8/8/8/8/8/8/8/8 w - e4 0 1", # EP not rank 3/6 (your code allows any 1..8; consider tightening) + ] + for fen in bad: + b = Board() + r = self.lib.load_fen(ctypes.byref(b), fen.encode("ascii")) + self.assertEqual(r, -1) \ No newline at end of file -- 2.34.1 From c80826710d3cc408be25f74ea7a90e7f80b80c0a Mon Sep 17 00:00:00 2001 From: Josh Date: Sat, 16 Aug 2025 12:44:04 -0400 Subject: [PATCH 6/6] Add fen loader and a test script for c --- engine/include/bitboard.h | 7 ++++--- engine/include/fen.h | 1 + engine/src/bitboard.c | 42 +++++++++++++++++++++++++++++++++++++++ engine/src/fen.c | 4 ++++ engine/src/test.c | 33 ++++++++++++++++++++++++++++++ makefile | 22 +++++++++++++++++--- 6 files changed, 103 insertions(+), 6 deletions(-) create mode 100644 engine/include/fen.h create mode 100644 engine/src/test.c diff --git a/engine/include/bitboard.h b/engine/include/bitboard.h index 7e1f246..c2ac730 100644 --- a/engine/include/bitboard.h +++ b/engine/include/bitboard.h @@ -52,6 +52,7 @@ struct Board { int fullmove_number; }; -void create_knight_attack_cache(void); -void create_pawn_attack_cache(void); -void create_king_attack_cache(void); \ No newline at end of file +void create_knight_attack_cache(); +void create_pawn_attack_cache(); +void create_king_attack_cache(); +void print_board(); \ No newline at end of file diff --git a/engine/include/fen.h b/engine/include/fen.h new file mode 100644 index 0000000..1decd7c --- /dev/null +++ b/engine/include/fen.h @@ -0,0 +1 @@ +int load_fen(); diff --git a/engine/src/bitboard.c b/engine/src/bitboard.c index 8d97cb0..f34239c 100644 --- a/engine/src/bitboard.c +++ b/engine/src/bitboard.c @@ -1,4 +1,5 @@ #include "bitboard.h" +#include uint64_t PAWN_ATTACKS[2][64]; uint64_t KNIGHT_ATTACKS[64]; @@ -58,4 +59,45 @@ void create_king_attack_cache(void) { KING_ATTACKS[sq] = mask; } +} + +static int first_set_index(uint64_t bb) { + for (int i = 0; i < 64; ++i) { + if ((bb >> i) & 1ULL) return i; + } + return -1; +} + +static int pop_lsb_index(uint64_t *bb) { + if (*bb == 0) return -1; + int idx = first_set_index(*bb); + // Clears bit. + *bb &= ~(1ULL << idx); + return idx; +} + +void print_board(const struct Board *b) { + static const char PIECE_CH[12] = { + 'P','N','B','R','Q','K', + 'p','n','b','r','q','k' + }; + + char grid[64]; + for (int i = 0; i < 64; ++i) grid[i] = '.'; + + for (int p = 0; p < 12; ++p) { + uint64_t bb = b->pieces[p]; + while (bb) { + int sq = pop_lsb_index(&bb); + grid[sq] = PIECE_CH[p]; + } + } + + for (int r = 7; r >= 0; --r) { + for (int f = 0; f < 8; ++f) { + putchar(grid[r * 8 + f]); + if (f < 7) putchar(' '); + } + putchar('\n'); + } } \ No newline at end of file diff --git a/engine/src/fen.c b/engine/src/fen.c index bef7b6a..2485ca9 100644 --- a/engine/src/fen.c +++ b/engine/src/fen.c @@ -21,6 +21,10 @@ int char_to_piece_index(char c) { } int load_fen(struct Board *board, const char *fen) { + // Reset the board first. Weird behavior when not zeroed. + memset(board, 0, sizeof *board); + board->ep_square = -1; + int rank = 7, file = 0; const char *ptr = fen; diff --git a/engine/src/test.c b/engine/src/test.c new file mode 100644 index 0000000..47e5514 --- /dev/null +++ b/engine/src/test.c @@ -0,0 +1,33 @@ +/** + A quick test script to debug and visually inspect functions + and operations. +*/ + + +#include +#include +#include "bitboard.h" +#include "fen.h" + + +static int popcount64(uint64_t x){ int c=0; while(x){ x&=x-1; ++c; } return c; } +static const char NAME[12] = {'P','N','B','R','Q','K','p','n','b','r','q','k'}; + + +int main(void) { + const char *fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; + + struct Board b; + + int rc = load_fen(&b, fen); + + for (int i=0;i<12;i++) printf("%c: %d\n", NAME[i], popcount64(b.pieces[i])); + + if (rc != 0) { + fprintf(stderr, "load_fen failed (rc=%d) for FEN:\n%s\n", rc, fen); + return 1; + } + + print_board(&b); + return 0; +} \ No newline at end of file diff --git a/makefile b/makefile index b8f210a..6169d94 100644 --- a/makefile +++ b/makefile @@ -7,11 +7,17 @@ INCDIR := engine/include BUILDDIR := build LIBNAME := libchess -SRC := $(wildcard $(SRCDIR)/*.c) +# Exclude test.c from the shared lib build +SRC := $(filter-out $(SRCDIR)/test.c,$(wildcard $(SRCDIR)/*.c)) OBJ := $(patsubst $(SRCDIR)/%.c,$(BUILDDIR)/%.o,$(SRC)) LIB := $(BUILDDIR)/$(LIBNAME).so -.PHONY: all clean test +# ---- test executable (engine/src/test.c) ---- +TESTSRC := $(SRCDIR)/test.c +TESTOBJ := $(BUILDDIR)/test.o +TESTBIN := $(BUILDDIR)/print_board + +.PHONY: all clean test test-exe run all: $(LIB) @@ -24,6 +30,17 @@ $(BUILDDIR)/%.o: $(SRCDIR)/%.c | $(BUILDDIR) $(LIB): $(OBJ) $(CC) $(LDFLAGS) -o $@ $^ +c-test-exe: $(TESTBIN) + +$(TESTOBJ): $(TESTSRC) | $(BUILDDIR) + $(CC) -std=c11 -Wall -Wextra -O2 -I$(INCDIR) -c $< -o $@ + +$(TESTBIN): $(TESTOBJ) $(LIB) + $(CC) -O2 -o $@ $(TESTOBJ) -L$(BUILDDIR) -lchess -Wl,-rpath,'$$ORIGIN' + +run-c-test: test-exe + LD_LIBRARY_PATH=$(BUILDDIR) $(TESTBIN) $(FEN) + clean: @echo "Cleaning build and Python caches..." @rm -rf $(BUILDDIR) @@ -31,7 +48,6 @@ clean: @find . -type d -name ".pytest_cache" -exec rm -rf {} + @find . -type f \( -name "*.pyc" -o -name "*.pyo" \) -delete -# Always rebuild, and always clean afterward (even if tests fail) test: @$(MAKE) clean @$(MAKE) all -- 2.34.1