81 Commits

Author SHA1 Message Date
1929d4bb1f bb migration: add util, update fen/fen-test + partial pos + piece 2024-02-07 22:08:24 +01:00
c57e0463cd Set back search.h file 2024-02-05 08:38:12 +01:00
33cd40b37f Duplicate search.h history. 2024-02-05 08:38:12 +01:00
797974f394 Copy search.h into temp-migration-bitboard/search.h 2024-02-05 08:38:12 +01:00
32fac4a0ba Keep search.h 2024-02-05 08:38:12 +01:00
56c9dde6fb Set back search.c file 2024-02-05 08:38:12 +01:00
0b6bdd6eb2 Duplicate search.c history. 2024-02-05 08:38:12 +01:00
10c29ab45d Copy search.c into temp-migration-bitboard/search.c 2024-02-05 08:38:12 +01:00
c44fc214af Keep search.c 2024-02-05 08:38:11 +01:00
13bbf45fc5 Set back position.h file 2024-02-05 08:38:11 +01:00
d2878f70ab Duplicate position.h history. 2024-02-05 08:38:11 +01:00
e2ec09ba65 Copy position.h into temp-migration-bitboard/position.h 2024-02-05 08:38:11 +01:00
beaeadedd2 Keep position.h 2024-02-05 08:38:11 +01:00
3798dbad4b Set back position.c file 2024-02-05 08:38:11 +01:00
c555bc2e72 Duplicate position.c history. 2024-02-05 08:38:11 +01:00
5b536df4b9 Copy position.c into temp-migration-bitboard/position.c 2024-02-05 08:38:11 +01:00
7653ff798f Keep position.c 2024-02-05 08:38:11 +01:00
276589364b Set back piece.h file 2024-02-05 08:38:11 +01:00
06f842a5c3 Duplicate piece.h history. 2024-02-05 08:38:11 +01:00
c9368a3ada Copy piece.h into temp-migration-bitboard/piece.h 2024-02-05 08:38:11 +01:00
b56f5b176b Keep piece.h 2024-02-05 08:38:11 +01:00
e0eccfbafd Set back piece.c file 2024-02-05 08:38:11 +01:00
bbb5840e39 Duplicate piece.c history. 2024-02-05 08:38:11 +01:00
c4eb134e92 Copy piece.c into temp-migration-bitboard/piece.c 2024-02-05 08:38:11 +01:00
624055eb26 Keep piece.c 2024-02-05 08:38:11 +01:00
163f4fedca Set back move.h file 2024-02-05 08:38:11 +01:00
52ec4198c1 Duplicate move.h history. 2024-02-05 08:38:11 +01:00
5841baf619 Copy move.h into temp-migration-bitboard/move.h 2024-02-05 08:38:11 +01:00
aff0e5abf4 Keep move.h 2024-02-05 08:38:10 +01:00
138b76d055 Set back move.c file 2024-02-05 08:38:10 +01:00
1b3ac52f52 Duplicate move.c history. 2024-02-05 08:38:10 +01:00
603aba8043 Copy move.c into temp-migration-bitboard/move.c 2024-02-05 08:38:10 +01:00
02c2667858 Keep move.c 2024-02-05 08:38:10 +01:00
589755331f Set back fen.h file 2024-02-05 08:38:10 +01:00
fbca2fb839 Duplicate fen.h history. 2024-02-05 08:38:10 +01:00
7f972c82a7 Copy fen.h into temp-migration-bitboard/fen.h 2024-02-05 08:38:10 +01:00
0ebecaad41 Keep fen.h 2024-02-05 08:38:10 +01:00
a8565e46cd Set back fen.c file 2024-02-05 08:38:10 +01:00
f7fe395a97 Duplicate fen.c history. 2024-02-05 08:38:10 +01:00
c7a2d9b330 Copy fen.c into temp-migration-bitboard/fen.c 2024-02-05 08:38:10 +01:00
c1aa9a0a0a Keep fen.c 2024-02-05 08:38:10 +01:00
398f40ecdf Set back eval-simple.h file 2024-02-05 08:38:10 +01:00
e709a2c3c6 Duplicate eval-simple.h history. 2024-02-05 08:38:10 +01:00
cefbfcbc25 Copy eval-simple.h into temp-migration-bitboard/eval-simple.h 2024-02-05 08:38:10 +01:00
da1aff03b3 Keep eval-simple.h 2024-02-05 08:38:10 +01:00
3e4855ef4d Set back eval-simple.c file 2024-02-05 08:38:10 +01:00
bbde461b4b Duplicate eval-simple.c history. 2024-02-05 08:38:10 +01:00
53b612358a Copy eval-simple.c into temp-migration-bitboard/eval-simple.c 2024-02-05 08:38:10 +01:00
04ad280beb Keep eval-simple.c 2024-02-05 08:38:10 +01:00
160851af18 Set back eval.h file 2024-02-05 08:38:10 +01:00
4c26aa09d9 Duplicate eval.h history. 2024-02-05 08:38:10 +01:00
b1027330aa Copy eval.h into temp-migration-bitboard/eval.h 2024-02-05 08:38:09 +01:00
4240646969 Keep eval.h 2024-02-05 08:38:09 +01:00
49f834573e Set back eval.c file 2024-02-05 08:38:09 +01:00
733c619594 Duplicate eval.c history. 2024-02-05 08:38:09 +01:00
aebb798b31 Copy eval.c into temp-migration-bitboard/eval.c 2024-02-05 08:38:09 +01:00
17bbe6379d Keep eval.c 2024-02-05 08:38:09 +01:00
bdd88e8511 Set back chessdefs.h file 2024-02-05 08:38:09 +01:00
18c294a1f1 Duplicate chessdefs.h history. 2024-02-05 08:38:09 +01:00
051dbc3348 Copy chessdefs.h into temp-migration-bitboard/chessdefs.h 2024-02-05 08:38:09 +01:00
3b01841877 Keep chessdefs.h 2024-02-05 08:38:09 +01:00
5b1d99650d Set back brchess.h file 2024-02-05 08:38:09 +01:00
ee7701d8ef Duplicate brchess.h history. 2024-02-05 08:38:09 +01:00
eb362f32bb Copy brchess.h into temp-migration-bitboard/brchess.h 2024-02-05 08:38:09 +01:00
8140881359 Keep brchess.h 2024-02-05 08:38:09 +01:00
be5c4e5c2a Set back brchess.c file 2024-02-05 08:38:09 +01:00
917d1852b7 Duplicate brchess.c history. 2024-02-05 08:38:09 +01:00
f52c50c817 Copy brchess.c into temp-migration-bitboard/brchess.c 2024-02-05 08:38:09 +01:00
860aa6fc72 Keep brchess.c 2024-02-05 08:38:09 +01:00
7b18c11cd4 Set back board.h file 2024-02-05 08:38:09 +01:00
83c9444c59 Duplicate board.h history. 2024-02-05 08:38:09 +01:00
15b004651f Copy board.h into temp-migration-bitboard/board.h 2024-02-05 08:38:09 +01:00
1e4760687b Keep board.h 2024-02-05 08:38:09 +01:00
636f1f555a Set back bitboard.h file 2024-02-05 08:38:09 +01:00
8dbae2ceef Duplicate bitboard.h history. 2024-02-05 08:38:08 +01:00
56543095ac Copy bitboard.h into temp-migration-bitboard/bitboard.h 2024-02-05 08:38:08 +01:00
0fc415d900 Keep bitboard.h 2024-02-05 08:38:08 +01:00
26c3b04d17 Set back bitboard.c file 2024-02-05 08:38:08 +01:00
7e870ee269 Duplicate bitboard.c history. 2024-02-05 08:38:08 +01:00
15ad675838 Copy bitboard.c into temp-migration-bitboard/bitboard.c 2024-02-05 08:38:08 +01:00
6acacb0314 Keep bitboard.c 2024-02-05 08:38:08 +01:00
38 changed files with 4139 additions and 602 deletions

View File

@@ -48,6 +48,8 @@ LIBS := -l$(LIB) -lreadline -lncurses
##################################### pre-processor flags ##################################### pre-processor flags
CPPFLAGS := -I$(BRINCDIR) CPPFLAGS := -I$(BRINCDIR)
CPPFLAGS += -DBUG_ON
CPPFLAGS += -DWARN_ON
#CPPFLAGS += -DDEBUG # global #CPPFLAGS += -DDEBUG # global
CPPFLAGS += -DDEBUG_DEBUG # enable log() functions CPPFLAGS += -DDEBUG_DEBUG # enable log() functions
#CPPFLAGS += -DDEBUG_DEBUG_C # enable verbose log() settings #CPPFLAGS += -DDEBUG_DEBUG_C # enable verbose log() settings
@@ -252,6 +254,16 @@ VALGRINDFLAGS += --suppressions=etc/libreadline.supp
memcheck: targets memcheck: targets
@$(VALGRIND) $(VALGRINDFLAGS) $(BINDIR)/brchess @$(VALGRIND) $(VALGRINDFLAGS) $(BINDIR)/brchess
##################################### test binaries
TEST = bin/fen-test
FENTESTOBJS = obj/fen.o obj/position.o obj/piece.o obj/util.o
testing: $(TEST)
bin/fen-test: test/fen-test.c $(FENTESTOBJS)
$(CC) $(LDFLAGS) $(CPPFLAGS) $(CFLAGS) $< $(LIBS) $(FENTESTOBJS) -o $@
##################################### Makefile debug ##################################### Makefile debug
.PHONY: showflags wft .PHONY: showflags wft
@@ -271,3 +283,6 @@ wtf:
@#echo LIBOBJ=$(LIBOBJ) @#echo LIBOBJ=$(LIBOBJ)
@#echo DEP=$(DEP) @#echo DEP=$(DEP)
@#echo LIBSRC=$(LIBSRC) @#echo LIBSRC=$(LIBSRC)
zob:
$(CC) $(LDFLAGS) $(CPPFLAGS) $(CFLAGS) $< $(LIBS) src/util.c -o util

2
brlib

Submodule brlib updated: 635e4c8d9e...8cb08dacb3

View File

@@ -11,18 +11,15 @@
* *
*/ */
#ifndef BITBOARD_H #ifndef _BITBOARD_H
#define BITBOARD_H #define _BITBOARD_H
#include "br.h" #include "brlib.h"
#include "chessdefs.h" #include "chessdefs.h"
#include "piece.h" #include "piece.h"
#include "bitops.h" #include "bitops.h"
#define mask(s) ( 1ULL << (s) ) typedef enum {
#define C64(const_u64) const_u64##ULL
typedef enum square {
A1, B1, C1, D1, E1, F1, G1, H1, A1, B1, C1, D1, E1, F1, G1, H1,
A2, B2, C2, D2, E2, F2, G2, H2, A2, B2, C2, D2, E2, F2, G2, H2,
A3, B3, C3, D3, E3, F3, G3, H3, A3, B3, C3, D3, E3, F3, G3, H3,
@@ -31,23 +28,21 @@ typedef enum square {
A6, B6, C6, D6, E6, F6, G6, H6, A6, B6, C6, D6, E6, F6, G6, H6,
A7, B7, C7, D7, E7, F7, G7, H7, A7, B7, C7, D7, E7, F7, G7, H7,
A8, B8, C8, D8, E8, F8, G8, H8, A8, B8, C8, D8, E8, F8, G8, H8,
SQ_N, SQUARE_MAX = 64,
SQ_0 = 0 SQUARE_NONE = 64
} square; } square;
typedef enum file { typedef enum {
FILE_A, FILE_B, FILE_C, FILE_D, FILE_E, FILE_F, FILE_G, FILE_H, FILE_A, FILE_B, FILE_C, FILE_D, FILE_E, FILE_F, FILE_G, FILE_H,
FILE_N, FILE_MAX,
FILE_0 = 0
} file; } file;
typedef enum rank { typedef enum {
RANK_1, RANK_2, RANK_3, RANK_4, RANK_5, RANK_6, RANK_7, RANK_8, RANK_1, RANK_2, RANK_3, RANK_4, RANK_5, RANK_6, RANK_7, RANK_8,
RANK_N, RANK_MAX,
RANK_0 = 0
} rank; } rank;
typedef enum sq_bb { typedef enum {
//A1 = 0x01ULL, B1 = 0x02ULL, C1 = 1UL << 2, D1 = 1UL << 3, //A1 = 0x01ULL, B1 = 0x02ULL, C1 = 1UL << 2, D1 = 1UL << 3,
//E1 = 1UL << 4, F1 = 1UL << 5, G1 = 1UL << 6, H1 = 1UL << //E1 = 1UL << 4, F1 = 1UL << 5, G1 = 1UL << 6, H1 = 1UL <<
A1bb = mask(A1), A2bb = mask(A2), A3bb = mask(A3), A4bb = mask(A4), A1bb = mask(A1), A2bb = mask(A2), A3bb = mask(A3), A4bb = mask(A4),
@@ -68,7 +63,7 @@ typedef enum sq_bb {
H5bb = mask(H5), H6bb = mask(H6), H7bb = mask(H7), H8bb = mask(H8), H5bb = mask(H5), H6bb = mask(H6), H7bb = mask(H7), H8bb = mask(H8),
} sq_bb; } sq_bb;
typedef enum file_bb { typedef enum {
FILE_Abb = 0x0101010101010101ULL, FILE_Abb = 0x0101010101010101ULL,
FILE_Bbb = 0x0202020202020202ULL, FILE_Bbb = 0x0202020202020202ULL,
FILE_Cbb = 0x0404040404040404ULL, FILE_Cbb = 0x0404040404040404ULL,
@@ -79,7 +74,7 @@ typedef enum file_bb {
FILE_Hbb = 0x8080808080808080ULL, FILE_Hbb = 0x8080808080808080ULL,
} file_bb; } file_bb;
typedef enum rank_bb { typedef enum {
RANK_1bb = 0x00000000000000ffULL, RANK_1bb = 0x00000000000000ffULL,
RANK_2bb = 0x000000000000ff00ULL, RANK_2bb = 0x000000000000ff00ULL,
RANK_3bb = 0x0000000000ff0000ULL, RANK_3bb = 0x0000000000ff0000ULL,
@@ -90,16 +85,31 @@ typedef enum rank_bb {
RANK_8bb = 0xff00000000000000ULL RANK_8bb = 0xff00000000000000ULL
} rank_bb; } rank_bb;
#define NORTH 8 typedef enum {
#define EAST 1 NORTH = 8,
#define SOUTH -NORTH EAST = 1,
#define WEST -EAST SOUTH = -NORTH,
WEST = -EAST,
#define NORTH_EAST (NORTH + EAST) NORTH_EAST = (NORTH + EAST),
#define SOUTH_EAST (SOUTH + EAST) SOUTH_EAST = (SOUTH + EAST),
#define SOUTH_WEST (SOUTH + WEST) SOUTH_WEST = (SOUTH + WEST),
#define NORTH_WEST (NORTH + WEST) NORTH_WEST = (NORTH + WEST),
} direction;
static inline square BB(file file, rank rank)
{
return (rank << 3) + file;
}
static inline file BBfile(square square)
{
return square & 7;
}
static inline rank BBrank(square square)
{
return square >> 3;
}
void bitboard_init(void); void bitboard_init(void);
#endif /* BITBOARD_H */ #endif /* _BITBOARD_H */

View File

@@ -14,67 +14,44 @@
#ifndef BOARD_H #ifndef BOARD_H
#define BOARD_H #define BOARD_H
#include <stdint.h> #include "brlib.h"
#include "chessdefs.h"
#include "piece.h"
typedef struct board_s { #include "chessdefs.h"
piece_t piece; //#include "piece.h"
piece_list_t *s_piece;
//struct list_head *s_piece;
} board_t; /* 0x88 board */
#define BOARDSIZE (8*8*2)
/* definitions for 0x88 representation /* definitions for 0x88 representation
*/ */
#define SQ88(f, r) (((r) << 4) | (f)) /* from rank,file to sq88 */ //#define SQ88(f, r) (((r) << 4) | (f)) /* from rank,file to sq88 */
#define F88(s) ((s) & 0x0f) /* from sq88 to file */ //#define F88(s) ((s) & 0x0f) /* from sq88 to file */
#define R88(s) ((s) >> 4) /* from sq88 to rank */ //#define R88(s) ((s) >> 4) /* from sq88 to rank */
#define SETF88(s, r) ((s) &= 0xf0, (s) |= (r)) //#define SETF88(s, r) ((s) &= 0xf0, (s) |= (r))
#define SETR88(s, f) ((s) &= 0x0f, (s) |= (f)<<4) //#define SETR88(s, f) ((s) &= 0x0f, (s) |= (f)<<4)
#define SQ88_NOK(s) ((s) & 0x88) /* invalid square */ //#define SQ88_NOK(s) ((s) & 0x88) /* invalid square */
#define SQ88_OK(s) (!SQ88_NOK(s)) //#define SQ88_OK(s) (!SQ88_NOK(s))
/* definitions for bitboard representation /* definitions for bitboard representation
*/ */
#define BB(f, r) (1ULL << (8 * (r) + (f))) /* from rank,file to bitboard */ //#define BB(f, r) (1ULL << (8 * (r) + (f))) /* from rank,file to bitboard */
#define SQ88_2_BB(s) (BB(F88(s), R88(s))) /* from sq88 to bitboard */
#define FILEBB(b) ((b) % 8) /* from sq88 to file */
#define RANKBB(b) ((b) / 8) /* from sq88 to rank */
#define SQ88_NOK(s) ((s) & 0x88) /* invalid square */
#define SQ88_OK(s) (!SQ88_NOK(s))
/* piece human notation //#define SQ88_2_BB(s) (BB(F88(s), R88(s))) /* from sq88 to bitboard */
*/ //#define FILEBB(b) ((b) % 8) /* from sq88 to file */
#define CHAR_EMPTY ' ' //#define RANKBB(b) ((b) / 8) /* from sq88 to rank */
#define CHAR_PAWN 'P'
#define CHAR_KNIGHT 'N' //#define SQ88_NOK(s) ((s) & 0x88) /* invalid square */
#define CHAR_BISHOP 'B' //#define SQ88_OK(s) (!SQ88_NOK(s))
#define CHAR_ROOK 'R'
#define CHAR_QUEEN 'Q'
#define CHAR_KING 'K'
/* from human to machine /* from human to machine
*/ */
#define C2FILE(c) (tolower(c) - 'a') /*
#define C2RANK(c) (tolower(c) - '1') * #define C2FILE(c) (tolower(c) - 'a')
/* from machine to human * #define C2RANK(c) (tolower(c) - '1')
* /\* from machine to human
* *\/
* #define FILE2C(f) ((f) + 'a')
* #define RANK2C(r) ((r) + '1')
*/ */
#define FILE2C(f) ((f) + 'a')
#define RANK2C(r) ((r) + '1')
enum x88_square {
x88_A1=0x00, x88_B1, x88_C1, x88_D1, x88_E1, x88_F1, x88_G1, x88_H1,
x88_A2=0x10, x88_B2, x88_C2, x88_D2, x88_E2, x88_F2, x88_G2, x88_H2,
x88_A3=0x20, x88_B3, x88_C3, x88_D3, x88_E3, x88_F3, x88_G3, x88_H3,
x88_A4=0x30, x88_B4, x88_C4, x88_D4, x88_E4, x88_F4, x88_G4, x88_H4,
x88_A5=0x40, x88_B5, x88_C5, x88_D5, x88_E5, x88_F5, x88_G5, x88_H5,
x88_A6=0x50, x88_B6, x88_C6, x88_D6, x88_E6, x88_F6, x88_G6, x88_H6,
x88_A7=0x60, x88_B7, x88_C7, x88_D7, x88_E7, x88_F7, x88_G7, x88_H7,
x88_A8=0x70, x88_B8, x88_C8, x88_D8, x88_E8, x88_F8, x88_G8, x88_H8,
};
#endif /* BOARD_H */ #endif /* BOARD_H */

View File

@@ -11,67 +11,47 @@
* *
*/ */
#ifndef CHESSDEFS_H #ifndef _CHESSDEFS_H
#define CHESSDEFS_H #define _CHESSDEFS_H
#include "br.h" #include "brlib.h" /* brlib types */
#define mask(i) ( 1ULL << (i) )
#define C64(const_u64) const_u64##ULL
#define U64(const_s64) const_s64##LL
/* piece_t bits structure /* piece_t bits structure
* MSB 8 7 6 5 4 3 2 1 LSB * piece is on bits 1-3, color on bit 4:
* 1: color (0 for white) * .... CPPP
* 2-7: bit set for pawn (2), knight, bishop, rook, queen, king (7) * C: 0 for white, 1: black
* PPP: pawn (1), knight, bishop, rook, queen, king (6)
*/ */
typedef u8 piece_t; typedef enum {
WHITE, BLACK,
NCOLOR_MAX
} color;
enum { typedef enum {
E_EMPTY = 0, ALL_PIECES = 0, /* 'all pieces' bitboard */
E_COLOR, /* LSB */ PAWN = 1, KNIGHT, BISHOP, ROOK, QUEEN, KING,
E_PAWN, PIECE_TYPE_MAX = 7 /* bit 4 */
E_KNIGHT, } piece_type;
E_BISHOP,
E_ROOK,
E_QUEEN,
E_KING,
};
/* pos_t bitboards tables typedef enum {
*/ EMPTY,
enum { W_PAWN = PAWN, W_KNIGHT, W_BISHOP, W_ROOK, W_QUEEN, W_KING,
BB_ALL = 0, /* OR of all bitboards */ B_PAWN = PAWN | 8, B_KNIGHT, B_BISHOP, B_ROOK, B_QUEEN, B_KING,
BB_UNUSED, /* future use ? */ PIECE_MAX
BB_PAWN = E_PAWN, } piece;
BB_KNIGHT,
BB_BISHOP,
BB_ROOK,
BB_QUEEN,
BB_KING,
BB_END
};
/* piece bitmask in piece_t
*/
enum {
EMPTY = 0,
PAWN = 1 << (E_PAWN - 1), /* 1<<(2-1) = 0x02 00000010 */
KNIGHT = 1 << (E_KNIGHT - 1), /* 0x04 00000100 */
BISHOP = 1 << (E_BISHOP - 1), /* 0x08 00001000 */
ROOK = 1 << (E_ROOK - 1), /* 0x10 00010000 */
QUEEN = 1 << (E_QUEEN - 1), /* 0x20 00100000 */
KING = 1 << (E_KING - 1), /* 0x40 01000000 */
};
#define PIECETOBB(p) (ffs64(PIECE(p))) /* from piece_t to bb piece array */
#define WHITE 0 /* 0x00 00000000 */
#define BLACK 1 /* 0x01 00000001 */
#define OPPONENT(p) !(p) #define OPPONENT(p) !(p)
#define MASK_COLOR 0x01 /* 00000001 */ #define MASK_PIECE 0x07 /* 00000111 */
#define MASK_PIECE 0x7E /* 01111110 */ #define MASK_COLOR 0x08 /* 00001000 */
#define COLOR(p) ((p) & MASK_COLOR) /* bitmask */ #define COLOR(p) ((p) >> 3) /* bitmask */
#define PIECE(p) ((p) & MASK_PIECE) #define PIECE(p) ((p) & MASK_PIECE)
#define E_PIECE(p) (ffs64(PIECE(p))) /* convert mask to E_XX */ #define MAKE_PIECE(p, c) ((p) | (c) << 3)
#define IS_WHITE(p) (!COLOR(p)) #define IS_WHITE(p) (!COLOR(p))
#define IS_BLACK(p) (COLOR(p)) #define IS_BLACK(p) (COLOR(p))
@@ -86,20 +66,25 @@ enum {
*/ */
#define FLIP_V(sq) ((sq) ^ 56) #define FLIP_V(sq) ((sq) ^ 56)
#define FLIP_H(sq) ((sq) ^ 7) #define FLIP_H(sq) ((sq) ^ 7)
/* square_t bits structure : rrrrffff
* ffff: file typedef u64 bitboard;
* rrrr: rank typedef ushort board;
*/ #define BOARDSIZE (8*8)
typedef uchar square_t; /* from human to machine */
#define C2FILE(c) (tolower(c) - 'a')
#define C2RANK(c) (tolower(c) - '1')
/* from machine to human */
#define FILE2C(f) ((f) + 'a')
#define RANK2C(r) ((r) + '1')
/* castle_t bits structure /* castle_t bits structure
*/ */
typedef unsigned char castle_t; typedef enum {
CASTLE_WK = (1 << 0), /* 0x01 00000001 */
#define CASTLE_WK (1 << 0) /* 0x01 00000001 */ CASTLE_WQ = (1 << 1), /* 0x02 00000010 */
#define CASTLE_WQ (1 << 1) /* 0x02 00000010 */ CASTLE_BK = (1 << 2), /* 0x04 00000100 */
#define CASTLE_BK (1 << 2) /* 0x04 00000100 */ CASTLE_BQ = (1 << 3), /* 0x08 00001000 */
#define CASTLE_BQ (1 << 3) /* 0x08 00001000 */ } castle;
#define CASTLE_W (CASTLE_WK | CASTLE_WQ) /* 00000011 W castle mask */ #define CASTLE_W (CASTLE_WK | CASTLE_WQ) /* 00000011 W castle mask */
#define CASTLE_B (CASTLE_BK | CASTLE_BQ) /* 00001100 B castle mask */ #define CASTLE_B (CASTLE_BK | CASTLE_BQ) /* 00001100 B castle mask */
@@ -112,18 +97,17 @@ typedef unsigned char castle_t;
/* bitboard /* bitboard
*/ */
typedef u64 bitboard_t; //typedef u64 bitboard_t;
/* eval type /* eval type
*/ */
typedef s32 eval_t; //typedef s32 eval_t;
/* forward typedefs /* forward typedefs
*/ */
typedef struct piece_list_s piece_list_t; //typedef struct piece_list_s piece_list_t;
typedef struct board_s board_t; //typedef struct board_s board_t;
typedef struct pos_s pos_t; //typedef struct pos_s pos_t;
typedef struct move_s move_t; //typedef struct move_s move_t;
#endif #endif /* _CHESSDEFS_H */

336
src/fen.c
View File

@@ -1,6 +1,6 @@
/* fen.c - fen notation. /* fen.c - fen notation.
* *
* Copyright (C) 2021 Bruno Raoult ("br") * Copyright (C) 2021-2024 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later. * Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING. * Some rights reserved. See COPYING.
* *
@@ -18,158 +18,264 @@
#include <ctype.h> #include <ctype.h>
#include <debug.h> #include <debug.h>
#include <bug.h>
#include "chessdefs.h" #include "chessdefs.h"
#include "position.h" #include "position.h"
#include "board.h"
#include "fen.h" #include "fen.h"
#include "piece.h" #include "piece.h"
#include "util.h"
/* Starting Position : /* FEN description:
* rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 * 1 : pieces on board (no space allowed):
* After 1.e4 : * - rank 8 first, '/' between ranks
* rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1 * - piece is usual piece notation(PNBRQK), black lowercase.
* After 1... c5 : * - empty: number of consecutive empty squares (digit)
* rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq c6 0 2
* After 2. Nf3:
* rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2
*
* 1 : White uppercase
* 2 : next move (w or b) * 2 : next move (w or b)
* 3 : Castling capabilities: "-" if none, KQ/kq if white/black can castle * 3 : Castling capabilities: "-" if none, KQ/kq if white/black can castle
* on K or Q side * on K or Q side
* 4 : en-passant: if pawn just moved 2 squares, indicate target square (e.g. * 4 : en-passant: "-" if none. If pawn just moved 2 squares, indicate target
* for e2-e4 this field is e3) * en-passant square (e.g. for e2-e4 this field is e3)
* 5 : half moves since last capture or pawn advance (for 50 moves rule) * 5 : half moves since last capture or pawn advance (for 50 moves rule)
* 6 : full moves, starts at 1, increments after black move * 6 : full moves, starts at 1, increments after black move
* *
* Examples:
*
* starting position:
* rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
* after 1.e4 e6 2.e5 d5
* rnbqkbnr/ppp2ppp/4p3/3pP3/8/8/PPPP1PPP/RNBQKBNR w KQkq d6 0 3
* 3.Nc3 Nc6 4.Rb1 Rb8 5.Nf3 h5 6.Be2
* 1rbqkbnr/ppp2pp1/2n1p3/3pP2p/8/2N2N2/PPPPBPPP/1RBQK2R b Kk - 1 6
* 6...Be7
* 1rbqk1nr/ppp1bpp1/2n1p3/3pP2p/8/2N2N2/PPPPBPPP/1RBQK2R w Kk - 2 7
* 7.Nxd5 h4 8.g4
* 1rbqk1nr/ppp1bpp1/2n1p3/3NP3/6Pp/5N2/PPPPBP1P/1RBQK2R b Kk g3 0 8
*/ */
// warning, we expect a valid fen input /* chess startup position FEN */
pos_t *fen2pos(pos_t *pos, char *fen) const char *startfen="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
{
char *p = fen; /* next must follow 'piece_type' enum values (pawn is 1, king is 6) */
short rank, file, skip, color, bbpiece; static const char *pieces_str = " PNBRQK";
piece_t piece; /* And this one must follow 'castle' enum order (also same as usual FEN) */
board_t *board = pos->board; static const char *castle_str = "KQkq";
# define SKIP_BLANK(p) for(;*(p) == ' '; (p)++)
#define SKIP_BLANK(p) for(;isspace(*(p)); (p)++)
/**
* startpos - create a game start position
* @pos: a position pointer or NULL
*
* See @fen2pos function.
*
* @return: the pos position.
*/
position *startpos(position *pos)
{
return fen2pos(pos, startfen);
}
/**
* fen2pos - make a position from a fen string
* @pos: a position pointer or NULL
* @fen: a valid fen string
*
* If @pos is NULL, a position will be allocated with malloc(1),
* that should be freed by caller.
*
* @return: the pos position, or NULL if error.
*/
position *fen2pos(position *pos, const char *fen)
{
const char *cur = fen;
char *p;
short rank, file, color, tmp;
int consumed, err_line = 0, err_pos, err_char;
position tmppos;
pos_clear(&tmppos);
pos_clear(pos);
/* 1) get piece placement information /* 1) get piece placement information
*/ */
for (rank = 7, file = 0; *p && *p != ' '; ++p) { for (rank = 7, file = 0; *cur && !isspace(*cur); ++cur) {
color = isupper(*p)? WHITE: BLACK; if (*cur == '/') { /* next rank */
char cp = toupper(*p);
switch (cp) {
case CHAR_PAWN:
bbpiece = BB_PAWN;
piece = PAWN;
goto set_square;
case CHAR_KNIGHT:
bbpiece = BB_KNIGHT;
piece = KNIGHT;
goto set_square;
case CHAR_BISHOP:
bbpiece = BB_BISHOP;
piece = BISHOP;
goto set_square;
case CHAR_ROOK:
bbpiece = BB_ROOK;
piece = ROOK;
goto set_square;
case CHAR_QUEEN:
bbpiece = BB_QUEEN;
piece = QUEEN;
goto set_square;
case CHAR_KING:
bbpiece = BB_KING;
piece = KING;
//pos->bb[color][BB_KING] = BB(file, rank);
//goto set_square;
set_square:
# ifdef DEBUG_FEN
log_i(5, "f=%d r=%d *p=%c piece=%c color=%d\n",
file, rank, *p, cp, color);
# endif
pos->bb[color][bbpiece] |= BB(file, rank);
pos->occupied[color] |= BB(file, rank);
SET_COLOR(piece, color);
board[SQ88(file, rank)].piece = piece;
board[SQ88(file, rank)].s_piece =
piece_add(pos, piece, SQ88(file, rank));
file++;
break;
case '/':
rank--; rank--;
file = 0; file = 0;
break; continue;
default:
skip = cp - '0';
while (skip--) {
board[SQ88(file++, rank)].piece = EMPTY;
}
} }
if (isdigit(*cur)) { /* empty square(s) */
file += *cur - '0';
continue;
} }
color = isupper(*cur)? WHITE: BLACK;
if ((p = strchr(pieces_str, toupper(*cur)))) { /* valid piece letter */
# ifdef DEBUG_FEN # ifdef DEBUG_FEN
for (rank = 7; rank >= 0; --rank) { log_i(5, "f=%d r=%d *p=%c piece=%c color=%d ppos=%ld\n",
for (file = 0; file < 8; ++file) { file, rank, *cur, *p, color, p - pieces_str);
log(5, "%02x ", board[SQ88(file, rank)].piece);
}
log(5, "\n");
}
# endif # endif
pos_set_sq(&tmppos, p - pieces_str, color, file, rank);
file++;
} else { /* error */
err_line = __LINE__, err_char = *cur, err_pos = cur - fen;
goto end;
}
}
SKIP_BLANK(cur);
/* 2) next move color /* 2) next turn color
*/ */
SKIP_BLANK(p); tmppos.turn = *cur++ == 'w' ? WHITE : BLACK;
SET_COLOR(pos->turn, *p == 'w' ? WHITE : BLACK); SKIP_BLANK(cur);
p++;
/* 3) castle status /* 3) castle rights
*/ */
SKIP_BLANK(p); if (*cur == '-') {
pos->castle = 0; cur++;
if (*p != '-') { } else {
for (; *p && *p != ' '; ++p) { for (; *cur && !isspace(*cur); ++cur) {
switch (*p) { if ((p = strchr(castle_str, *cur))) { /* valid castle letter */
case 'K': tmppos.castle |= 1 << (p - castle_str);
pos->castle |= CASTLE_WK; } else {
break; err_line = __LINE__, err_char = *cur, err_pos = cur - fen;
case 'k': goto end;
pos->castle |= CASTLE_BK;
break;
case 'Q':
pos->castle |= CASTLE_WQ;
break;
case 'q':
pos->castle |= CASTLE_BQ;
break;
} }
} }
} }
p++; SKIP_BLANK(cur);
/* 4) en passant /* 4) en passant
*/ */
SKIP_BLANK(p); tmppos.en_passant = 0;
pos->en_passant = 0; if (*cur == '-') {
if (*p != '-') { cur++;
//SET_F(pos->en_passant, C2FILE(*p++));
//SET_R(pos->en_passant, C2RANK(*p++));
pos->en_passant = SQ88(C2FILE(*p), C2RANK(*(p+1)));
pos += 2;
} else { } else {
p++; tmppos.en_passant = BB(C2FILE(*cur), C2RANK(*(cur+1)));
cur += 2;
} }
SKIP_BLANK(cur);
/* 5) half moves since last capture or pawn move and /* 5) half moves since last capture or pawn move (50 moves rule)
* 6) current move number
*/ */
SKIP_BLANK(p); sscanf(cur, "%hd%n", &tmppos.clock_50, &consumed);
//log_i(5, "pos=%d\n", (int)(p-fen)); cur += consumed;
sscanf(p, "%hd %hd", &pos->clock_50, &pos->curmove); SKIP_BLANK(cur);
/* 6) current full move number, starting with 1
*/
printf ("remain=[%s]\n", cur);
sscanf(cur, "%hd", &tmp);
printf ("tmp=[%d]\n", tmp);
if (tmp <= 0) /* fix faulty numbers*/
tmp = 1;
printf ("tmp2=[%d]\n", tmp);
tmp = 2 * (tmp - 1) + (tmppos.turn == BLACK); /* plies, +1 if black turn */
printf ("tmp3=[%d]\n", tmp);
tmppos.plycount = tmp;
# ifdef DEBUG_FEN # ifdef DEBUG_FEN
log_i(5, "50 rule=%d current move=%d\n", pos->clock_50, pos->curmove); for (rank = 7; rank >= 0; --rank) {
for (file = 0; file < 8; ++file) {
log(5, "%02x ", tmppos.board[BB(file, rank)]);
}
log(5, "\n");
}
log(5, "turn=%d 50_rule=%d curply=%d\n",
tmppos.turn, tmppos.clock_50, tmppos.plycount);
# endif # endif
end:
if (warn(err_line, "FEN error line %d: pos=%d char=%#x(%c)\n",
err_line, err_pos, err_char, err_char)) {
return NULL;
}
if (!pos)
pos = pos_new();
else
pos_clear(pos);
*pos = tmppos;
return pos; return pos;
} }
/**
* pos2fen - make a FEN string from a position.
* @pos: a position pointer
* @fen: destination FEN char*, or NULL
*
* If @fen is NULL, a 100 bytes memory will be allocated with malloc(1),
* that should be freed by caller.
*
* Note: If @fen is given, no check is done on its length, but to
* be on secure side, it should be at least 90 bytes. See:
* https://chess.stackexchange.com/questions/30004/longest-possible-fen
* For convenience, use FENSTRLEN.
*
* @return: the pos position, or NULL if error.
*/
char *pos2fen(const position *pos, char *fen)
{
int cur = 0;
if (!fen)
fen = safe_malloc(92);
/* 1) position
*/
for (int rank = RANK_8; rank >= RANK_1; --rank) {
printf("r=%d 1=%d\n", rank, RANK_1);
for (int file = FILE_A; file <= FILE_H;) {
printf(" f=%d H=%d\n", file, FILE_H);
square sq = BB(file, rank);
printf(" sq=%d\n", sq);
piece piece = PIECE(pos->board[sq]);
color color = COLOR(pos->board[sq]);
if (pos->board[sq] == EMPTY) {
int len = 0;
for (; file <= FILE_H && pos->board[BB(file,rank)] == EMPTY; file++)
len++;
fen[cur++] = '0' + len;
} else {
char c = pieces_str[piece];
fen[cur++] = color == WHITE? c: tolower(c);
file++;
}
fen[cur]=0; puts(fen);
}
fen[cur++] = rank == RANK_1? ' ': '/';
}
/* 2) next turn color
*/
fen[cur++] = pos->turn == WHITE? 'w': 'b';
fen[cur++] = ' ';
/* 3) castle rights
*/
if (pos->castle == 0) {
fen[cur++] = '-';
} else {
//static char *
for (int i = 0; i < 4; ++i)
if (pos->castle & mask(i))
fen[cur++] = castle_str[i];
}
fen[cur++] = ' ';
/* 4) en passant
*/
if (!pos->en_passant) {
fen[cur++] = '-';
} else {
fen[cur++] = FILE2C(BBfile(pos->en_passant));
fen[cur++] = RANK2C(BBrank(pos->en_passant));
}
fen[cur++] = ' ';
/* 5) moves since last capture or pawn move (50 moves rule)
* 6) current full move number, starting with 1
*/
sprintf(fen+cur, "%d %d", pos->clock_50,
1 + (pos->plycount - (pos->turn == BLACK)) / 2);
return fen;
}

View File

@@ -1,6 +1,6 @@
/* fen.h - fen notation. /* fen.h - fen notation.
* *
* Copyright (C) 2021 Bruno Raoult ("br") * Copyright (C) 2021-2024 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later. * Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING. * Some rights reserved. See COPYING.
* *
@@ -16,6 +16,12 @@
#include "position.h" #include "position.h"
pos_t *fen2pos(pos_t *pos, char *fen); #define FENSTRLEN 92 /* secure FEN string size */
extern const char *startfen; /* startup position */
extern position *startpos(position *pos);
extern position *fen2pos(position *pos, const char *fen);
extern char *pos2fen(const position *pos, char *fen);
#endif /* FEN_H */ #endif /* FEN_H */

View File

@@ -1,6 +1,6 @@
/* piece.c - piece list management. /* piece.c - piece list management.
* *
* Copyright (C) 2021 Bruno Raoult ("br") * Copyright (C) 2021-2024 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later. * Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING. * Some rights reserved. See COPYING.
* *
@@ -13,106 +13,118 @@
#include <malloc.h> #include <malloc.h>
#include <ctype.h> #include <ctype.h>
#include <string.h>
#include <assert.h>
#include <debug.h> //#include <debug.h>
#include <pool.h> //#include <pool.h>
#include <list.h> //#include <list.h>
#include "chessdefs.h" #include "chessdefs.h"
#include "piece.h" #include "piece.h"
#include "board.h" //#include "board.h"
#include "bitboard.h" //#include "bitboard.h"
#include "position.h" //#include "position.h"
static pool_t *pieces_pool; //static pool_t *pieces_pool;
struct piece_details piece_details[] = { const struct piece_details piece_details[] = {
[E_EMPTY] = { ' ', ' ', " ", " ", "", 0 }, /* W B SW SB Name start value */
[E_PAWN] = { 'P', 'p', "", "", "Pawn", PAWN_VALUE }, [EMPTY] = { ' ', ' ', " ", " ", "",
[E_KNIGHT] = { 'N', 'n', "", "", "Knight", KNIGHT_VALUE }, 0, 0, 0 },
[E_BISHOP] = { 'B', 'b', "", "", "Bishop", BISHOP_VALUE }, [PAWN] = { 'P', 'p', "", "", "Pawn",
[E_ROOK] = { 'R', 'r', "", "", "Rook", ROOK_VALUE }, PAWN_VALUE, PAWN_VALUE, PAWN_VALUE },
[E_QUEEN] = { 'Q', 'q', "", "", "Queen", QUEEN_VALUE }, [KNIGHT] = { 'N', 'n', "", "", "Knight",
[E_KING] = { 'K', 'k', "", "", "King", KING_VALUE } KNIGHT_VALUE, KNIGHT_VALUE, KNIGHT_VALUE },
[BISHOP] = { 'B', 'b', "", "", "Bishop",
BISHOP_VALUE, BISHOP_VALUE, BISHOP_VALUE },
[ROOK] = { 'R', 'r', "", "", "Rook",
ROOK_VALUE, ROOK_VALUE, ROOK_VALUE },
[QUEEN] = { 'Q', 'q', "", "", "Queen",
QUEEN_VALUE, QUEEN_VALUE, QUEEN_VALUE },
[KING] = { 'K', 'k', "", "", "King",
KING_VALUE, KING_VALUE, KING_VALUE }
}; };
void piece_list_print(struct list_head *list) /*
{ * void piece_list_print(struct list_head *list)
struct list_head *p_cur, *tmp; * {
piece_list_t *piece; * struct list_head *p_cur, *tmp;
* piece_list_t *piece;
list_for_each_safe(p_cur, tmp, list) { *
piece = list_entry(p_cur, piece_list_t, list); * list_for_each_safe(p_cur, tmp, list) {
* piece = list_entry(p_cur, piece_list_t, list);
printf("%s%c%c ", P_SYM(piece->piece), *
FILE2C(F88(piece->square)), * printf("%s%c%c ", P_SYM(piece->piece),
RANK2C(R88(piece->square))); * FILE2C(F88(piece->square)),
} * RANK2C(R88(piece->square)));
printf("\n"); * }
} * printf("\n");
* }
pool_t *piece_pool_init() *
{ * pool_t *piece_pool_init()
if (!pieces_pool) * {
pieces_pool = pool_create("pieces", 128, sizeof(piece_list_t)); * if (!pieces_pool)
return pieces_pool; * pieces_pool = pool_create("pieces", 128, sizeof(piece_list_t));
} * return pieces_pool;
* }
void piece_pool_stats() *
{ * void piece_pool_stats()
if (pieces_pool) * {
pool_stats(pieces_pool); * if (pieces_pool)
} * pool_stats(pieces_pool);
* }
piece_list_t *piece_add(pos_t *pos, piece_t piece, square_t square) *
{ * piece_list_t *piece_add(pos_t *pos, piece_t piece, square_t square)
piece_list_t *new; * {
short color = COLOR(piece); * piece_list_t *new;
* short color = COLOR(piece);
# ifdef DEBUG_PIECE *
log_f(3, "piece=%02x square=%02x\n", piece, square); * # ifdef DEBUG_PIECE
log_f(5, "Adding %s %s on %c%c\n", color? "Black": "White", * log_f(3, "piece=%02x square=%02x\n", piece, square);
P_NAME(piece), FILE2C(F88(square)), RANK2C(R88(square))); * log_f(5, "Adding %s %s on %c%c\n", color? "Black": "White",
# endif * P_NAME(piece), FILE2C(F88(square)), RANK2C(R88(square)));
if ((new = pool_get(pieces_pool))) { * # endif
/* first piece is always king */ * if ((new = pool_get(pieces_pool))) {
if (PIECE(piece) == KING) * /\* first piece is always king *\/
list_add(&new->list, &pos->pieces[color]); * if (PIECE(piece) == KING)
else * list_add(&new->list, &pos->pieces[color]);
list_add_tail(&new->list, &pos->pieces[color]); * else
new->piece = piece; * list_add_tail(&new->list, &pos->pieces[color]);
new->square = square; * new->piece = piece;
new->castle = 0; * new->square = square;
new-> value = piece_details[PIECE(piece)].value; * new->castle = 0;
} * new-> value = piece_details[PIECE(piece)].value;
* }
return new; *
} * return new;
* }
void piece_del(struct list_head *ptr) *
{ * void piece_del(struct list_head *ptr)
piece_list_t *piece = list_entry(ptr, piece_list_t, list); * {
# ifdef DEBUG_PIECE * piece_list_t *piece = list_entry(ptr, piece_list_t, list);
log_f(3, "piece=%02x square=%02x\n", piece->piece, piece->square); * # ifdef DEBUG_PIECE
# endif * log_f(3, "piece=%02x square=%02x\n", piece->piece, piece->square);
list_del(ptr); * # endif
pool_add(pieces_pool, piece); * list_del(ptr);
return; * pool_add(pieces_pool, piece);
} * return;
* }
int pieces_del(pos_t *pos, short color) *
{ * int pieces_del(pos_t *pos, short color)
struct list_head *p_cur, *tmp, *head; * {
int count = 0; * struct list_head *p_cur, *tmp, *head;
* int count = 0;
head = &pos->pieces[color]; *
* head = &pos->pieces[color];
list_for_each_safe(p_cur, tmp, head) { *
piece_del(p_cur); * list_for_each_safe(p_cur, tmp, head) {
count++; * piece_del(p_cur);
} * count++;
# ifdef DEBUG_PIECE * }
log_f(3, "color=%d removed=%d\n", color, count); * # ifdef DEBUG_PIECE
# endif * log_f(3, "color=%d removed=%d\n", color, count);
return count; * # endif
} * return count;
* }
*/

View File

@@ -1,6 +1,6 @@
/* piece.h - piece definitions. /* piece.h - piece definitions.
* *
* Copyright (C) 2021 Bruno Raoult ("br") * Copyright (C) 2021-2024 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later. * Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING. * Some rights reserved. See COPYING.
* *
@@ -20,9 +20,9 @@
#include "list.h" #include "list.h"
#include "pool.h" #include "pool.h"
#define PIECE_DEFAULT_VALUE 0
/* initial default values */ /* initial default values */
#define EMPTY_VALUE 0
#define PAWN_VALUE 100 #define PAWN_VALUE 100
#define KNIGHT_VALUE 300 #define KNIGHT_VALUE 300
#define BISHOP_VALUE 300 #define BISHOP_VALUE 300
@@ -30,6 +30,7 @@
#define QUEEN_VALUE 900 #define QUEEN_VALUE 900
#define KING_VALUE 20000 #define KING_VALUE 20000
/*
typedef struct piece_list_s { typedef struct piece_list_s {
piece_t piece; piece_t piece;
square_t square; square_t square;
@@ -37,35 +38,39 @@ typedef struct piece_list_s {
s64 value; s64 value;
struct list_head list; struct list_head list;
} piece_list_t; } piece_list_t;
*/
/* some default values for pieces /* some default values for pieces
*/ */
extern struct piece_details { extern const struct piece_details {
char abbrev_w; /* used for game notation */ char abbrev_w; /* used for game notation */
char abbrev_b; char abbrev_b;
char *symbol_w; char *symbol_w;
char *symbol_b; /* used for game notation */ char *symbol_b; /* used for game notation */
char *name; char *name;
s64 value; s64 opn_value;
s64 mid_value;
s64 end_value;
} piece_details[]; } piece_details[];
#define P_NAME(p) piece_details[E_PIECE(p)].name #define P_NAME(p) piece_details[PIECE(p)].name
#define P_LETTER(p) piece_details[E_PIECE(p)].abbrev_w #define P_LETTER(p) piece_details[PIECE(p)].abbrev_w
#define P_SYM(p) piece_details[E_PIECE(p)].symbol_b #define P_SYM(p) piece_details[PIECE(p)].symbol_b
#define P_CSHORT(p) (IS_WHITE(p)? piece_details[E_PIECE(p)].abbrev_w: \ #define P_CSHORT(p) (IS_WHITE(p)? piece_details[PIECE(p)].abbrev_w: \
piece_details[E_PIECE(p)].abbrev_b) piece_details[PIECE(p)].abbrev_b)
#define P_CSYM(p) (IS_WHITE(p)? piece_details[E_PIECE(p)].symbol_w: \ #define P_CSYM(p) (IS_WHITE(p)? piece_details[PIECE(p)].symbol_w: \
piece_details[E_PIECE(p)].symbol_b) piece_details[PIECE(p)].symbol_b)
#define P_VALUE(p) (piece_details[E_PIECE(p)].value) #define P_VALUE(p) (piece_details[PIECE(p)].value)
/* use short name or symbol - no effect /* use short name or symbol - no effect
*/ */
#define P_USE_UTF 1 #define P_USE_UTF 1
void piece_list_print(struct list_head *list); //void piece_list_print(struct list_head *list);
pool_t *piece_pool_init(); //pool_t *piece_pool_init();
void piece_pool_stats(); //void piece_pool_stats();
piece_list_t *piece_add(pos_t *pos, piece_t piece, square_t square); //piece_list_t *piece_add(pos_t *pos, piece_t piece, square_t square);
void piece_del(struct list_head *ptr); //void piece_del(struct list_head *ptr);
int pieces_del(pos_t *pos, short color); //int pieces_del(pos_t *pos, short color);
#endif #endif

View File

@@ -1,6 +1,6 @@
/* position.c - position management. /* position.c - position management.
* *
* Copyright (C) 2021 Bruno Raoult ("br") * Copyright (C) 2021-2024 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later. * Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING. * Some rights reserved. See COPYING.
* *
@@ -16,16 +16,23 @@
#include <stdbool.h> #include <stdbool.h>
#include <string.h> #include <string.h>
#include <ctype.h> #include <ctype.h>
#include <assert.h>
#include "bitops.h"
#include "chessdefs.h" #include "chessdefs.h"
#include "position.h" #include "position.h"
#include "move.h" //#include "move.h"
#include "fen.h" #include "fen.h"
#include "piece.h" #include "piece.h"
#include "eval.h" #include "util.h"
//#include "eval.h"
static pool_t *pos_pool; static pool_t *pos_pool;
const char *rankstr = "12345678";
const char *filestr = "ABCDEFGH";
#define BYTE_PRINT "%c%c%c%c%c%c%c%c" #define BYTE_PRINT "%c%c%c%c%c%c%c%c"
#define BYTE2BIN(b) ((b) & 0x01 ? '1' : '0'), \ #define BYTE2BIN(b) ((b) & 0x01 ? '1' : '0'), \
((b) & 0x02 ? '1' : '0'), \ ((b) & 0x02 ? '1' : '0'), \
@@ -36,88 +43,115 @@ static pool_t *pos_pool;
((b) & 0x40 ? '1' : '0'), \ ((b) & 0x40 ? '1' : '0'), \
((b) & 0x80 ? '1' : '0') ((b) & 0x80 ? '1' : '0')
inline void bitboard_print(bitboard_t bb) /*
inline void bitboard_print_raw(bitboard_t bb, char *title)
{ {
int i; int i;
printf("%#018lx\n", bb); printf("%s%s %#018lx\n", title? title: "", title? " - ": "", bb);
for (i=56; i>=0; i-=8) for (i=56; i>=0; i-=8)
printf("\t"BYTE_PRINT"\n", printf("\t"BYTE_PRINT"\n",
BYTE2BIN(bb>>i)); BYTE2BIN(bb>>i));
} }
*/
inline void bitboard_print2(bitboard_t bb1, bitboard_t bb2) /*
inline void bitboard_print2_raw(bitboard_t bb1, bitboard_t bb2, char *title)
{ {
int i; int i;
printf("%s%s", title? title: "", title? ":\n": "");
printf("\tW: %#018lx\tB: %#018lx\n", bb1, bb2); printf("\tW: %#018lx\tB: %#018lx\n", bb1, bb2);
for (i=56; i>=0; i-=8) for (i=56; i>=0; i-=8)
printf("\t"BYTE_PRINT"\t\t"BYTE_PRINT"\n", printf("\t"BYTE_PRINT"\t\t"BYTE_PRINT"\n",
BYTE2BIN(bb1>>i), BYTE2BIN(bb1>>i),
BYTE2BIN(bb2>>i)); BYTE2BIN(bb2>>i));
} }
*/
/** /**
* pos_pieces_print() - Print position pieces * pos_pieces_print() - Print position pieces
* @pos: &position * @pos: &position
*/ */
void pos_pieces_print(pos_t *pos) void pos_pieces_print(position *pos)
{ {
printf("White pieces (%d): \t", popcount64(pos->occupied[WHITE])); int bit, count, cur;
piece_list_print(&pos->pieces[WHITE]); char pname;
printf("Black pieces (%d): \t", popcount64(pos->occupied[BLACK])); u64 tmp;
piece_list_print(&pos->pieces[BLACK]); bitboard p;
for (int color = WHITE; color <= BLACK; ++color) {
for (int piece = KING; piece >= PAWN; --piece) {
p = pos->bb[color][piece];
count = popcount64(p);
cur = 0;
pname = P_LETTER(piece);
printf("%c(0)%s", pname, count? ":": "");
if (count) {
bit_for_each64(bit, tmp, p) {
char cf = BBfile(bit), cr = BBrank(bit);
printf("%s%c%c", cur? ",": "", FILE2C(cf), RANK2C(cr));
cur++;
}
}
printf(" ");
}
printf("\n");
//printf("White pieces (%d): \t", popcount64(pos->occupied[WHITE]));
//piece_list_print(&pos->pieces[WHITE]);
//printf("Black pieces (%d): \t", popcount64(pos->occupied[BLACK]));
//piece_list_print(&pos->pieces[BLACK]);
}
} }
/** /**
* pos_bitboards_print() - Print position bitboards * pos_bitboards_print() - Print position bitboards
* @pos: &position * @pos: &position
*/ */
void pos_bitboards_print(pos_t *pos) //void pos_bitboards_print(pos_t *pos)
{ //{
printf("Bitboards occupied :\n"); // printf("Bitboards occupied :\n");
bitboard_print2(pos->occupied[WHITE], pos->occupied[BLACK]); // bitboard_print2(pos->occupied[WHITE], pos->occupied[BLACK]);
printf("Bitboards controlled :\n"); // printf("Bitboards controlled :\n");
bitboard_print2(pos->controlled[WHITE], pos->controlled[BLACK]); // bitboard_print2(pos->controlled[WHITE], pos->controlled[BLACK]);
//
} //}
/** /**
* pos_print() - Print position on stdout. * pos_print() - Print position on stdout.
* @pos: &position * @pos: &position
*/ */
void pos_print(pos_t *pos) void pos_print(position *pos)
{ {
int rank, file; int rank, file;
piece_t piece; piece pc, *board = pos->board;
board_t *board = pos->board;
piece_list_t *wk = list_first_entry(&pos->pieces[WHITE], piece_list_t, list), //piece_list_t *wk = list_first_entry(&pos->pieces[WHITE], piece_list_t, list),
*bk = list_first_entry(&pos->pieces[BLACK], piece_list_t, list); // *bk = list_first_entry(&pos->pieces[BLACK], piece_list_t, list);
printf(" +---+---+---+---+---+---+---+---+\n"); printf(" +---+---+---+---+---+---+---+---+\n");
for (rank = 7; rank >= 0; --rank) { for (rank = 7; rank >= 0; --rank) {
printf("%c |", rank + '1'); printf("%c |", rank + '1');
for (file = 0; file < 8; ++file) { for (file = 0; file < 8; ++file) {
piece = board[SQ88(file, rank)].piece; pc = board[BB(file, rank)];
printf(" %s |", P_CSYM(piece)); printf(" %s |", P_CSYM(pc));
} }
printf("\n +---+---+---+---+---+---+---+---+\n"); printf("\n +---+---+---+---+---+---+---+---+\n");
} }
printf(" A B C D E F G H\n\n"); printf(" A B C D E F G H\n\n");
printf("Turn: %s.\n", IS_WHITE(pos->turn) ? "white" : "black"); printf("Turn: %s.\n", IS_WHITE(pos->turn) ? "white" : "black");
printf("Kings: W:%c%c B:%c%c\n", /*
FILE2C(F88(wk->square)), * printf("Kings: W:%c%c B:%c%c\n",
RANK2C(R88(wk->square)), * FILE2C(F88(wk->square)),
FILE2C(F88(bk->square)), * RANK2C(R88(wk->square)),
RANK2C(R88(bk->square))); * FILE2C(F88(bk->square)),
* RANK2C(R88(bk->square)));
*/
printf("Possible en-passant: [%#x] ", pos->en_passant); printf("Possible en-passant: [%#x] ", pos->en_passant);
if (pos->en_passant == 0) if (pos->en_passant == 0)
printf("None.\n"); printf("None.\n");
else else
printf("%d %d = %c%c\n", printf("%c%c.\n",
F88(pos->en_passant), FILE2C(BBfile(pos->en_passant)),
R88(pos->en_passant), RANK2C(BBrank(pos->en_passant)));
FILE2C(F88(pos->en_passant)),
RANK2C(R88(pos->en_passant)));
printf("castle [%#x] : ", pos->castle); printf("castle [%#x] : ", pos->castle);
@@ -130,97 +164,94 @@ void pos_print(pos_t *pos)
if (pos->castle & CASTLE_BQ) if (pos->castle & CASTLE_BQ)
printf("q"); printf("q");
printf("\n50 half-moves-rule = %d\n", pos->clock_50); printf("\nplies=%d clock50=%d\n", pos->plycount, pos->clock_50);
printf("Current move = %d\n", pos->curmove); //printf("Current move = %d\n", pos->curmove);
printf("Squares controlled: W:%d B:%d\n", popcount64(pos->controlled[WHITE]), //printf("Squares controlled: W:%d B:%d\n", popcount64(pos->controlled[WHITE]),
popcount64(pos->controlled[BLACK])); // popcount64(pos->controlled[BLACK]));
printf("Mobility: W:%u B:%u\n", pos->mobility[WHITE], //printf("Mobility: W:%u B:%u\n", pos->mobility[WHITE],
pos->mobility[BLACK]); // pos->mobility[BLACK]);
} }
/** /**
* pos_check() - extensive position consistenci check. * pos_check() - extensive position consistenci check.
* @pos: &position * @pos: &position
*/ */
void pos_check(pos_t *pos) /*
{ * void pos_check(position *pos)
int rank, file; * {
piece_t piece; * int rank, file;
board_t *board = pos->board; * piece_t piece;
* board_t *board = pos->board;
/* check that board and bitboard reflect same information */ *
for (rank = 7; rank >= 0; --rank) { * /\* check that board and bitboard reflect same information *\/
for (file = 0; file < 8; ++file) { * for (rank = 7; rank >= 0; --rank) {
piece_list_t *ppiece; * for (file = 0; file < 8; ++file) {
printf("checking %c%c ", file+'a', rank+'1'); * piece_list_t *ppiece;
* printf("checking %c%c ", file+'a', rank+'1');
piece = board[SQ88(file, rank)].piece; *
ppiece= board[SQ88(file, rank)].s_piece; * piece = board[SQ88(file, rank)].piece;
printf("piece=%s ", P_CSYM(piece)); * ppiece= board[SQ88(file, rank)].s_piece;
if (ppiece) * printf("piece=%s ", P_CSYM(piece));
printf("ppiece=%s/sq=%#x ", P_CSYM(ppiece->piece), ppiece->square); * if (ppiece)
switch(PIECE(piece)) { * printf("ppiece=%s/sq=%#x ", P_CSYM(ppiece->piece), ppiece->square);
case PAWN: * switch(PIECE(piece)) {
printf("pawn" ); * case PAWN:
break; * printf("pawn" );
case KNIGHT: * break;
printf("knight "); * case KNIGHT:
break; * printf("knight ");
case BISHOP: * break;
printf("bishop "); * case BISHOP:
break; * printf("bishop ");
case ROOK: * break;
printf("rook "); * case ROOK:
break; * printf("rook ");
case QUEEN: * break;
printf("queen "); * case QUEEN:
break; * printf("queen ");
case KING: * break;
printf("king "); * case KING:
break; * printf("king ");
} * break;
printf("\n"); * }
} * printf("\n");
} * }
} * }
* }
pos_t *pos_clear(pos_t *pos)
{
int file, rank;
board_t *board = pos->board;
for (file = 0; file < 8; ++file) {
for (rank = 0; rank < 8; ++rank) {
/*printf("file = %d rank = %d SQ88 = %#2x = %d addr=%p\n", file, rank,
SQ88(file, rank), SQ88(file, rank),
&board[SQ88(file, rank)].piece);
*/ */
board[SQ88(file, rank)].piece = EMPTY;
} position *pos_clear(position *pos)
} {
printf("size(pos_board=%lu elt=%lu\n", sizeof(pos->board), sizeof(int));
//for (square square = A1; square <= H8; ++square)
// pos->board[square] = EMPTY;
SET_WHITE(pos->turn); SET_WHITE(pos->turn);
pos->node_count = 0; pos->node_count = 0;
pos->castle = 0; pos->turn = 0;
pos->clock_50 = 0; pos->clock_50 = 0;
pos->curmove = 0; pos->plycount = 0;
pos->eval = 0;
pos->en_passant = 0; pos->en_passant = 0;
pos->occupied[WHITE] = 0; pos->castle = 0;
pos->occupied[BLACK] = 0; memset(pos->board, 0, sizeof(pos->board));
for (int color=0; color<2; ++color) //pos->curmove = 0;
for (int piece = BB_ALL; piece < BB_END; ++piece) //pos->eval = 0;
//pos->occupied[WHITE] = 0;
//pos->occupied[BLACK] = 0;
for (color color = WHITE; color <= BLACK; ++color) {
for (piece_type piece = 0; piece <= KING; ++piece)
pos->bb[color][piece] = 0; pos->bb[color][piece] = 0;
pos->controlled[WHITE] = 0; pos->controlled[WHITE] = 0;
pos->controlled[BLACK] = 0; pos->controlled[BLACK] = 0;
pos->mobility[WHITE] = 0; }
pos->mobility[BLACK] = 0; //pos->mobility[WHITE] = 0;
pos->moves_generated = false; //pos->mobility[BLACK] = 0;
pos->moves_counted = false; //pos->moves_generated = false;
//pos->moves_counted = false;
/* remove pieces / moves */ /* remove pieces / moves */
pieces_del(pos, WHITE); //pieces_del(pos, WHITE);
pieces_del(pos, BLACK); //pieces_del(pos, BLACK);
moves_del(pos); //moves_del(pos);
return pos; return pos;
} }
@@ -229,35 +260,22 @@ pos_t *pos_clear(pos_t *pos)
* pos_del() - delete a position. * pos_del() - delete a position.
* @pos: &position. * @pos: &position.
*/ */
void pos_del(pos_t *pos) /*
* void pos_del(pos_t *pos)
* {
* pieces_del(pos, WHITE);
* pieces_del(pos, BLACK);
* moves_del(pos);
* pool_add(pos_pool, pos);
* }
*/
position *pos_new(void)
{ {
pieces_del(pos, WHITE); position *pos = safe_malloc(sizeof(position));
pieces_del(pos, BLACK); //assert(pos);
moves_del(pos); return pos_clear(pos);
pool_add(pos_pool, pos);
}
pos_t *pos_startpos(pos_t *pos)
{
static char *startfen="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
return fen2pos(pos, startfen);
}
pos_t *pos_get()
{
pos_t *pos = pool_get(pos_pool);
if (pos) {
INIT_LIST_HEAD(&pos->pieces[WHITE]);
INIT_LIST_HEAD(&pos->pieces[BLACK]);
INIT_LIST_HEAD(&pos->moves[WHITE]);
INIT_LIST_HEAD(&pos->moves[BLACK]);
pos_clear(pos);
} else {
fprintf(stderr, "zobaaa\n");
}
return pos;
} }
/** /**
@@ -275,44 +293,29 @@ pos_t *pos_get()
* *
* @return: The new position. * @return: The new position.
* *
* TODO: merge with pos_get - NULL for init, non null for duplicate * TODO: merge with pos_new - NULL for init, non null for duplicate
*/ */
pos_t *pos_dup(pos_t *pos) position *pos_dup(position *pos)
{ {
struct list_head *p_cur, *piece_list; position *newpos= pool_get(pos_pool);
piece_list_t *oldpiece;
board_t *board;
pos_t *new = pool_get(pos_pool);
if (new) { if (newpos) {
board = new->board; //board = new->board;
*new = *pos; *newpos = *pos;
for (int color = 0; color < 2; ++color) { //new->bestmove = NULL;
INIT_LIST_HEAD(&new->pieces[color]); newpos->node_count = 0;
INIT_LIST_HEAD(&new->moves[color]); //new->eval = EVAL_INVALID;
/* duplicate piece list */ //new->moves_generated = false;
piece_list = &pos->pieces[color]; /* white/black piece list */ //new->moves_counted = false;
//new->check[WHITE] = new->check[BLACK] = 0;
list_for_each(p_cur, piece_list) {
oldpiece = list_entry(p_cur, piece_list_t, list);
board[oldpiece->square].s_piece =
piece_add(new, oldpiece->piece, oldpiece->square);
} }
} return newpos;
new->bestmove = NULL;
new->node_count = 0;
new->eval = EVAL_INVALID;
new->moves_generated = false;
new->moves_counted = false;
new->check[WHITE] = new->check[BLACK] = 0;
}
return new;
} }
pool_t *pos_pool_init() pool_t *pos_pool_init()
{ {
if (!pos_pool) if (!pos_pool)
pos_pool = pool_create("positions", 128, sizeof(pos_t)); pos_pool = pool_create("positions", 128, sizeof(position));
return pos_pool; return pos_pool;
} }

View File

@@ -1,6 +1,6 @@
/* position.h - position management definitions. /* position.h - position management definitions.
* *
* Copyright (C) 2021 Bruno Raoult ("br") * Copyright (C) 2021-2024 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later. * Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING. * Some rights reserved. See COPYING.
* *
@@ -16,51 +16,85 @@
#include <stdint.h> #include <stdint.h>
#include "pool.h" #include "brlib.h"
#include "list.h" //#include "pool.h"
//#include "list.h"
#include "bitops.h" #include "bitops.h"
#include "bitboard.h"
#include "board.h" #include "board.h"
#include "chessdefs.h" #include "chessdefs.h"
typedef struct pos_s { typedef struct {
u64 node_count; /* evaluated nodes */ u64 node_count; /* evaluated nodes */
piece_t turn; /* we use only color bit */ int turn; /* WHITE or BLACK */
castle_t castle;
u16 clock_50; u16 clock_50;
u16 curmove; u16 plycount; /* plies so far, start is 0 */
eval_t eval; square en_passant;
int check[2]; castle castle;
int eval_simple_phase;
eval_t eval_simple;
move_t *bestmove;
bool moves_generated;
bool moves_counted;
board_t board[BOARDSIZE];
square_t en_passant; //eval_t eval;
//int check[2];
//int eval_simple_phase;
//eval_t eval_simple;
//move_t *bestmove;
//bool moves_generated;
//bool moves_counted;
bitboard_t bb[2][BB_END]; /* use: pieces[BLACK][BB_PAWN] */ bitboard bb[2][PIECE_TYPE_MAX]; /* bb[0][PAWN], bb[1][ALL_PIECES] */
bitboard_t occupied[2]; /* OR of bb[COLOR][x] */ bitboard controlled[2];
bitboard_t controlled[2]; //u16 mobility[2];
u16 mobility[2]; //struct list_head pieces[2]; /* pieces list, King is first */
struct list_head pieces[2]; /* pieces list, King is first */ //struct list_head moves[2];
struct list_head moves[2]; piece board[BOARDSIZE];
} pos_t; } position;
void bitboard_print(bitboard_t bb); /**
void bitboard_print2(bitboard_t bb1, bitboard_t bb2); * pos_set_sq - unconditionally set a piece on a square
void pos_pieces_print(pos_t *pos); * @pos: position
void pos_bitboards_print(pos_t *pos); * @p, @c: type and color of piece to add
void pos_print(pos_t *pos); * @f, @r: destination file and rank
pos_t *pos_clear(pos_t *pos); *
void pos_del(pos_t *pos); * Both position bords and bitboards are modified.
pos_t *pos_startpos(pos_t *pos); */
pos_t *pos_create(); static inline void pos_set_sq(position *pos, piece_type p, color c, file f, rank r)
{
piece piece = MAKE_PIECE(p, c);
square square = BB(f, r);
pos->board[square] = piece;
pos->bb[c][ALL_PIECES] |= 1 << square;
pos->bb[c][p] |= 1 << square;
}
/**
* pos_clr_sq - unconditionally remove a piece from square
* @pos: position
* @f, @r: destination file and rank
*
* Both position bords and bitboards are modified.
*/
static inline void pos_clr_sq(position *pos, file f, rank r)
{
square square = BB(f, r);
piece_type piece = PIECE(pos->board[square]);
color color = COLOR(pos->board[square]);
pos->board[square] = EMPTY;
pos->bb[color][piece] &= ~(1 << square);
pos->bb[color][ALL_PIECES] &= ~(1 << square);
}
//void bitboard_print(bitboard_t bb, char *title);
//void bitboard_print2(bitboard_t bb1, bitboard_t bb2, char *title);
void pos_pieces_print(position *pos);
//void pos_bitboards_print(pos_t *pos);
void pos_print(position *pos);
position *pos_clear(position *pos);
//void pos_del(position *pos);
position *pos_startpos(position *pos);
position *pos_new();
pool_t *pos_pool_init(); pool_t *pos_pool_init();
void pos_pool_stats(); void pos_pool_stats();
pos_t *pos_get(); position *pos_dup(position *pos);
pos_t *pos_dup(pos_t *pos); //void pos_check(position *pos);
void pos_check(pos_t *pos);
#endif /* POSITION_H */ #endif /* POSITION_H */

View File

@@ -0,0 +1,42 @@
/* bitboard.c - bitboard functions.
*
* Copyright (C) 2024 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#include "br.h"
#include "bitboard.h"
/* maps are clockwise from N */
static char knight_vector[8] = {
NORTH*2 + EAST, NORTH + EAST*2, SOUTH + EAST*2, SOUTH*2 + EAST,
SOUTH*2 + WEST, SOUTH + WEST*2, NORTH + WEST*2, NORTH*2 + WEST
};
static char king_vector[8] = {
NORTH, NORTH_EAST, EAST, SOUTH_EAST,
SOUTH, SOUTH_WEST, WEST, NORTH_WEST
};
static u64 knight_attacks[64], king_attacks[64];
static int zob=0;
void bitboard_init(void)
{
for (int sq = SQ_0; sq < SQ_N; ++sq) {
/* knight/king */
for (int j = 0; j < 8; ++j) {
zob += *knight_attacks + *king_attacks + *knight_vector +
*king_vector;
//int dest_knight = sq + knight_vector[j];
//if ()
}
}
}

View File

@@ -0,0 +1,105 @@
/* bitboard.h - bitboard definitions.
*
* Copyright (C) 2021-2024 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#ifndef BITBOARD_H
#define BITBOARD_H
#include "br.h"
#include "chessdefs.h"
#include "piece.h"
#include "bitops.h"
#define mask(s) ( 1ULL << (s) )
#define C64(const_u64) const_u64##ULL
typedef enum square {
A1, B1, C1, D1, E1, F1, G1, H1,
A2, B2, C2, D2, E2, F2, G2, H2,
A3, B3, C3, D3, E3, F3, G3, H3,
A4, B4, C4, D4, E4, F4, G4, H4,
A5, B5, C5, D5, E5, F5, G5, H5,
A6, B6, C6, D6, E6, F6, G6, H6,
A7, B7, C7, D7, E7, F7, G7, H7,
A8, B8, C8, D8, E8, F8, G8, H8,
SQ_N,
SQ_0 = 0
} square;
typedef enum file {
FILE_A, FILE_B, FILE_C, FILE_D, FILE_E, FILE_F, FILE_G, FILE_H,
FILE_N,
FILE_0 = 0
} file;
typedef enum rank {
RANK_1, RANK_2, RANK_3, RANK_4, RANK_5, RANK_6, RANK_7, RANK_8,
RANK_N,
RANK_0 = 0
} rank;
typedef enum sq_bb {
//A1 = 0x01ULL, B1 = 0x02ULL, C1 = 1UL << 2, D1 = 1UL << 3,
//E1 = 1UL << 4, F1 = 1UL << 5, G1 = 1UL << 6, H1 = 1UL <<
A1bb = mask(A1), A2bb = mask(A2), A3bb = mask(A3), A4bb = mask(A4),
A5bb = mask(A5), A6bb = mask(A6), A7bb = mask(A7), A8bb = mask(A8),
B1bb = mask(B1), B2bb = mask(B2), B3bb = mask(B3), B4bb = mask(B4),
B5bb = mask(B5), B6bb = mask(B6), B7bb = mask(B7), B8bb = mask(B8),
C1bb = mask(C1), C2bb = mask(C2), C3bb = mask(C3), C4bb = mask(C4),
C5bb = mask(C5), C6bb = mask(C6), C7bb = mask(C7), C8bb = mask(C8),
D1bb = mask(D1), D2bb = mask(D2), D3bb = mask(D3), D4bb = mask(D4),
D5bb = mask(D5), D6bb = mask(D6), D7bb = mask(D7), D8bb = mask(D8),
E1bb = mask(E1), E2bb = mask(E2), E3bb = mask(E3), E4bb = mask(E4),
E5bb = mask(E5), E6bb = mask(E6), E7bb = mask(E7), E8bb = mask(E8),
F1bb = mask(F1), F2bb = mask(F2), F3bb = mask(F3), F4bb = mask(F4),
F5bb = mask(F5), F6bb = mask(F6), F7bb = mask(F7), F8bb = mask(F8),
G1bb = mask(G1), G2bb = mask(G2), G3bb = mask(G3), G4bb = mask(G4),
G5bb = mask(G5), G6bb = mask(G6), G7bb = mask(G7), G8bb = mask(G8),
H1bb = mask(H1), H2bb = mask(H2), H3bb = mask(H3), H4bb = mask(H4),
H5bb = mask(H5), H6bb = mask(H6), H7bb = mask(H7), H8bb = mask(H8),
} sq_bb;
typedef enum file_bb {
FILE_Abb = 0x0101010101010101ULL,
FILE_Bbb = 0x0202020202020202ULL,
FILE_Cbb = 0x0404040404040404ULL,
FILE_Dbb = 0x0808080808080808ULL,
FILE_Ebb = 0x1010101010101010ULL,
FILE_Fbb = 0x2020202020202020ULL,
FILE_Gbb = 0x4040404040404040ULL,
FILE_Hbb = 0x8080808080808080ULL,
} file_bb;
typedef enum rank_bb {
RANK_1bb = 0x00000000000000ffULL,
RANK_2bb = 0x000000000000ff00ULL,
RANK_3bb = 0x0000000000ff0000ULL,
RANK_4bb = 0x00000000ff000000ULL,
RANK_5bb = 0x000000ff00000000ULL,
RANK_6bb = 0x0000ff0000000000ULL,
RANK_7bb = 0x00ff000000000000ULL,
RANK_8bb = 0xff00000000000000ULL
} rank_bb;
#define NORTH 8
#define EAST 1
#define SOUTH -NORTH
#define WEST -EAST
#define NORTH_EAST (NORTH + EAST)
#define SOUTH_EAST (SOUTH + EAST)
#define SOUTH_WEST (SOUTH + WEST)
#define NORTH_WEST (NORTH + WEST)
void bitboard_init(void);
#endif /* BITBOARD_H */

View File

@@ -0,0 +1,80 @@
/* board.h - board definitions.
*
* Copyright (C) 2021 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#ifndef BOARD_H
#define BOARD_H
#include <stdint.h>
#include "chessdefs.h"
#include "piece.h"
typedef struct board_s {
piece_t piece;
piece_list_t *s_piece;
//struct list_head *s_piece;
} board_t; /* 0x88 board */
#define BOARDSIZE (8*8*2)
/* definitions for 0x88 representation
*/
#define SQ88(f, r) (((r) << 4) | (f)) /* from rank,file to sq88 */
#define F88(s) ((s) & 0x0f) /* from sq88 to file */
#define R88(s) ((s) >> 4) /* from sq88 to rank */
#define SETF88(s, r) ((s) &= 0xf0, (s) |= (r))
#define SETR88(s, f) ((s) &= 0x0f, (s) |= (f)<<4)
#define SQ88_NOK(s) ((s) & 0x88) /* invalid square */
#define SQ88_OK(s) (!SQ88_NOK(s))
/* definitions for bitboard representation
*/
#define BB(f, r) (1ULL << (8 * (r) + (f))) /* from rank,file to bitboard */
#define SQ88_2_BB(s) (BB(F88(s), R88(s))) /* from sq88 to bitboard */
#define FILEBB(b) ((b) % 8) /* from sq88 to file */
#define RANKBB(b) ((b) / 8) /* from sq88 to rank */
#define SQ88_NOK(s) ((s) & 0x88) /* invalid square */
#define SQ88_OK(s) (!SQ88_NOK(s))
/* piece human notation
*/
#define CHAR_EMPTY ' '
#define CHAR_PAWN 'P'
#define CHAR_KNIGHT 'N'
#define CHAR_BISHOP 'B'
#define CHAR_ROOK 'R'
#define CHAR_QUEEN 'Q'
#define CHAR_KING 'K'
/* from human to machine
*/
#define C2FILE(c) (tolower(c) - 'a')
#define C2RANK(c) (tolower(c) - '1')
/* from machine to human
*/
#define FILE2C(f) ((f) + 'a')
#define RANK2C(r) ((r) + '1')
enum x88_square {
x88_A1=0x00, x88_B1, x88_C1, x88_D1, x88_E1, x88_F1, x88_G1, x88_H1,
x88_A2=0x10, x88_B2, x88_C2, x88_D2, x88_E2, x88_F2, x88_G2, x88_H2,
x88_A3=0x20, x88_B3, x88_C3, x88_D3, x88_E3, x88_F3, x88_G3, x88_H3,
x88_A4=0x30, x88_B4, x88_C4, x88_D4, x88_E4, x88_F4, x88_G4, x88_H4,
x88_A5=0x40, x88_B5, x88_C5, x88_D5, x88_E5, x88_F5, x88_G5, x88_H5,
x88_A6=0x50, x88_B6, x88_C6, x88_D6, x88_E6, x88_F6, x88_G6, x88_H6,
x88_A7=0x60, x88_B7, x88_C7, x88_D7, x88_E7, x88_F7, x88_G7, x88_H7,
x88_A8=0x70, x88_B8, x88_C8, x88_D8, x88_E8, x88_F8, x88_G8, x88_H8,
};
#endif /* BOARD_H */

View File

@@ -0,0 +1,522 @@
/* brchess.c - main loop.
*
* Copyright (C) 2021-2023 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#include <err.h>
#include <stdlib.h>
#include <string.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <br.h>
#include <list.h>
#include <debug.h>
#include "brchess.h"
#include "chessdefs.h"
#include "board.h"
#include "piece.h"
#include "move.h"
#include "fen.h"
#include "eval.h"
#include "eval-simple.h"
#include "search.h"
struct command {
char *name; /* User printable name */
int (*func)(pos_t *, char *); /* function doing the job */
char *doc; /* function doc */
};
/* readline example inspired by :
* - https://thoughtbot.com/blog/tab-completion-in-gnu-readline
* - http://web.mit.edu/gnu/doc/html/rlman_2.html
*/
char **commands_completion(const char *, int, int);
char *commands_generator(const char *, int);
char *escape(const char *);
int quote_detector(char *, int);
int execute_line (pos_t *, char *line);
struct command *find_command (char *);
char *stripwhite (char *string);
/* The names of functions that actually do the manipulation. */
int do_help(pos_t *, char*);
int do_fen(pos_t *, char*);
int do_init(pos_t *, char*);
int do_pos(pos_t *, char*);
int do_genmoves(pos_t *, char*);
int do_prmoves(pos_t *, char*);
//int do_prmovepos(pos_t *pos, char *arg);
int do_prpieces(pos_t *pos, char *arg);
int do_memstats(pos_t *, char*);
int do_eval(pos_t *, char*);
int do_simple_eval(pos_t *, char*);
int do_move(pos_t *, char*);
int do_quit(pos_t *, char*);
int do_debug(pos_t *, char*);
int do_depth(pos_t *, char*);
int do_search(pos_t *, char*);
int do_pvs(pos_t *, char*);
struct command commands[] = {
{ "help", do_help, "Display this text" },
{ "?", do_help, "Synonym for 'help'" },
{ "fen", do_fen, "Set position to FEN" },
{ "init", do_init, "Set position to normal start position" },
{ "pos", do_pos, "Print current position" },
{ "quit", do_quit, "Quit" },
{ "genmove", do_genmoves, "Generate move list for " },
{ "prmoves", do_prmoves, "Print position move list" },
// { "prmovepos", do_prmovepos, "Print Nth move resulting position" },
{ "prpieces", do_prpieces, "Print Pieces (from pieces lists)" },
{ "memstats", do_memstats, "Generate next move list" },
{ "eval", do_eval, "Eval current position" },
{ "simple-eval", do_simple_eval, "Simple eval current position" },
{ "do_move", do_move, "execute nth move on current position" },
{ "debug", do_debug, "Set log level to LEVEL" },
{ "depth", do_depth, "Set search depth to N" },
{ "search", do_search, "Search best move (negamax)" },
{ "pvs", do_pvs, "Search best move (Principal Variation Search)" },
{ NULL, (int(*)()) NULL, NULL }
};
static int done=0;
static int depth=1;
int brchess(pos_t *pos)
{
char *buffer, *s;
rl_attempted_completion_function = commands_completion;
rl_completer_quote_characters = "'\"";
rl_completer_word_break_characters = " ";
rl_char_is_quoted_p = &quote_detector;
while (!done) {
buffer = readline("chess> ");
if (!buffer)
break;
/* Remove leading and trailing whitespace from the line.
* Then, if there is anything left, add it to the history list
* and execute it.
*/
s = stripwhite(buffer);
if (*s) {
add_history(s);
execute_line(pos, s);
}
free(buffer);
}
return 0;
}
//char **commands_completion(const char *text, int start, int end)
char **commands_completion(const char *text, __unused int start, __unused int end)
{
rl_attempted_completion_over = 1;
return rl_completion_matches(text, commands_generator);
}
char *commands_generator(const char *text, int state)
{
static int list_index, len;
char *name;
if (!state) {
list_index = 0;
len = strlen(text);
}
while ((name = commands[list_index++].name)) {
if (rl_completion_quote_character) {
name = strdup(name);
} else {
name = escape(name);
}
if (strncmp(name, text, len) == 0) {
return name;
} else {
free(name);
}
}
return NULL;
}
char *escape(const char *original)
{
size_t original_len;
size_t i, j;
char *escaped, *resized_escaped;
original_len = strlen(original);
if (original_len > SIZE_MAX / 2) {
errx(1, "string too long to escape");
}
if ((escaped = malloc(2 * original_len + 1)) == NULL) {
err(1, NULL);
}
for (i = 0, j = 0; i < original_len; ++i, ++j) {
if (original[i] == ' ') {
escaped[j++] = '\\';
}
escaped[j] = original[i];
}
escaped[j] = '\0';
if ((resized_escaped = realloc(escaped, j)) == NULL) {
free(escaped);
resized_escaped = NULL;
err(1, NULL);
}
return resized_escaped;
}
int quote_detector(char *line, int index)
{
return index > 0
&& line[index - 1] == '\\'
&&!quote_detector(line, index - 1);
}
/* Execute a command line. */
int execute_line(pos_t *pos, char *line)
{
register int i;
struct command *command;
char *word;
/* Isolate the command word. */
i = 0;
while (line[i] && whitespace(line[i]))
i++;
word = line + i;
while (line[i] && !whitespace(line[i]))
i++;
if (line[i])
line[i++] = '\0';
command = find_command(word);
if (!command) {
fprintf(stderr, "%s: Unknown command.\n", word);
return -1;
}
/* Get argument to command, if any. */
while (whitespace(line[i]))
i++;
word = line + i;
/* return command number */
return (*command->func)(pos, word);
}
/* Look up NAME as the name of a command, and return a pointer to that
command. Return a NULL pointer if NAME isn't a command name. */
struct command *find_command(char *name)
{
register int i;
for (i = 0; commands[i].name; i++)
if (strcmp(name, commands[i].name) == 0)
return &commands[i];
return (struct command *)NULL;
}
/* Strip whitespace from the start and end of STRING. Return a pointer
into STRING. */
char *stripwhite(char *string)
{
register char *s, *t;
for (s = string; whitespace(*s); s++)
;
if (*s == 0)
return s;
t = s + strlen(s) - 1;
while (t > s && whitespace(*t))
t--;
*++t = '\0';
return s;
}
int do_eval(__unused pos_t *pos, __unused char *arg)
{
eval_t material[2], control[2], mobility[2];
for (int color = WHITE; color <= BLACK; ++color) {
material[color] = eval_material(pos, color);
control[color] = eval_square_control(pos, color);
mobility[color] = eval_mobility(pos, color);
printf("%s: material=%d mobility=%d controlled=%d\n",
color? "Black": "White", material[color],
mobility[color], control[color]);
}
eval_t res = eval(pos);
printf("eval = %d centipawns\n", res);
return 1;
}
int do_simple_eval(__unused pos_t *pos, __unused char *arg)
{
eval_t eval = eval_simple(pos);
printf("eval = %d centipawns\n", eval);
return 1;
}
int do_fen(pos_t *pos, char *arg)
{
fen2pos(pos, arg);
return 1;
}
int do_init(pos_t *pos, __unused char *arg)
{
pos_startpos(pos);
return 1;
}
int do_pos(pos_t *pos, __unused char *arg)
{
pos_print(pos);
return 1;
}
int do_genmoves(pos_t *pos, __unused char *arg)
{
moves_gen_all(pos);
return 1;
}
int do_prmoves(pos_t *pos, __unused char *arg)
{
uint debug_level = debug_level_get();
debug_level_set(1);
moves_print(pos, M_PR_SEPARATE | M_PR_NUM | M_PR_LONG);
debug_level_set(debug_level);
return 1;
}
/*
* int do_prmovepos(pos_t *pos, char *arg)
* {
* struct list_head *p_cur, *tmp;
* int movenum = atoi(arg), cur = 0; /\* starts with 0 *\/
* move_t *move;
*
* log_f(1, "%s\n", arg);
* list_for_each_safe(p_cur, tmp, &pos->moves[pos->turn]) {
* move = list_entry(p_cur, move_t, list);
* if (cur++ == movenum) {
* pos_print(move->newpos);
* break;
* }
* }
*
* return 1;
* }
*/
int do_prpieces(pos_t *pos, __unused char *arg)
{
log_f(1, "%s\n", arg);
pos_pieces_print(pos);
return 1;
}
int do_memstats(__unused pos_t *pos,__unused char *arg)
{
moves_pool_stats();
piece_pool_stats();
pos_pool_stats();
return 1;
}
int do_move(__unused pos_t *pos, __unused char *arg)
{
int i = 1, nmove = atoi(arg);
move_t *move;
pos_t *newpos;
if (list_empty(&pos->moves[pos->turn])) {
log_f(1, "No moves list.\n");
return 0;
}
list_for_each_entry(move, &pos->moves[pos->turn], list) {
if (i == nmove)
goto doit;
i++;
}
log_f(1, "Invalid <%d> move, should be <1-%d>.\n", nmove, i);
return 0;
doit:
newpos = move_do(pos, move);
pos_print(newpos);
return 1;
}
int do_quit(__unused pos_t *pos, __unused char *arg)
{
return done = 1;
}
int do_debug(__unused pos_t *pos, __unused char *arg)
{
debug_level_set(atoi(arg));
return 1;
}
/* Print out help for ARG, or for all of the commands if ARG is
not present. */
int do_help(__unused pos_t *pos, __unused char *arg)
{
int i;
int printed = 0;
for (i = 0; commands[i].name; i++) {
if (!*arg || (strcmp(arg, commands[i].name) == 0)) {
printf("%-11.11s%s.\n", commands[i].name, commands[i].doc);
printed++;
}
}
if (!printed) {
printf("No commands match `%s'. Possibilties are:\n", arg);
for (i = 0; commands[i].name; i++) {
/* Print in six columns. */
if (printed == 6) {
printed = 0;
printf("\n");
}
printf("%s\t", commands[i].name);
printed++;
}
if (printed)
printf("\n");
}
return 0;
}
int do_depth(__unused pos_t *pos, char *arg)
{
depth = atoi(arg);
printf("depth = %d\n", depth);
return 1;
}
int do_search(pos_t *pos, __unused char *arg)
{
int debug_level = debug_level_get();
float timer1, timer2, nodes_sec;
timer1 = debug_timer_elapsed();
negamax(pos, depth, pos->turn == WHITE ? 1 : -1);
timer2 = debug_timer_elapsed();
nodes_sec = (float) pos->node_count / ((float) (timer2 - timer1) / (float)NANOSEC);
log(1, "best=");
debug_level_set(1);
move_print(0, pos->bestmove, 0);
debug_level_set(debug_level);
log(1, " negamax=%d\n", pos->bestmove->negamax);
printf("Depth:%d Nodes:%luK time:%.02fs (%.0f kn/s)\n", depth,
pos->node_count / 1000, (timer2 - timer1)/NANOSEC, nodes_sec/1000);
return 1;
}
int do_pvs(pos_t *pos, __unused char *arg)
{
int debug_level = debug_level_get();
float timer1, timer2, nodes_sec;
eval_t _pvs;
timer1 = debug_timer_elapsed();
moves_gen_eval_sort(pos);
_pvs = pvs(pos, depth, EVAL_MIN, EVAL_MAX, pos->turn == WHITE ? 1 : -1);
timer2 = debug_timer_elapsed();
nodes_sec = (float) pos->node_count / ((float) (timer2 - timer1) / (float)NANOSEC);
log(1, "best=");
if (pos->bestmove) {
debug_level_set(1);
move_print(0, pos->bestmove, 0);
debug_level_set(debug_level);
log(1, " pvs=%d stored=%d\n", _pvs, pos->bestmove->negamax);
} else {
log(1, "<no-best-move>");
}
printf("Depth:%d Nodes:%luK time:%.02fs (%.0f kn/s)\n", depth,
pos->node_count / 1000, (timer2 - timer1)/NANOSEC, nodes_sec/1000);
return 1;
}
/** main()
* options:
int brchess(pos_t *pos)
*
*/
static int usage(char *prg)
{
fprintf(stderr, "Usage: %s [-ilw] [file...]\n", prg);
return 1;
}
#include <unistd.h>
int main(int ac, char **av)
{
pos_t *pos;
int opt;
piece_pool_init();
moves_pool_init();
pos_pool_init();
pos = pos_get();
debug_init(1, stderr, true);
eval_simple_init();
while ((opt = getopt(ac, av, "d:f:")) != -1) {
switch (opt) {
case 'd':
debug_level_set(atoi(optarg));
break;
case 'f':
fen2pos(pos, optarg);
break;
default:
return usage(*av);
}
}
if (optind < ac)
return usage(*av);
return brchess(pos);
}

View File

@@ -0,0 +1,21 @@
/* brchess.h - main loop.
*
* Copyright (C) 2021-2024 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#ifndef BRCHESS_H
#define BRCHESS_H
#include "position.h"
int brchess(pos_t *pos);
#endif /* BRCHESS_H */

View File

@@ -0,0 +1,129 @@
/* chessdefs.h - generic chess definitions.
*
* Copyright (C) 2021 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#ifndef CHESSDEFS_H
#define CHESSDEFS_H
#include "br.h"
/* piece_t bits structure
* MSB 8 7 6 5 4 3 2 1 LSB
* 1: color (0 for white)
* 2-7: bit set for pawn (2), knight, bishop, rook, queen, king (7)
*/
typedef u8 piece_t;
enum {
E_EMPTY = 0,
E_COLOR, /* LSB */
E_PAWN,
E_KNIGHT,
E_BISHOP,
E_ROOK,
E_QUEEN,
E_KING,
};
/* pos_t bitboards tables
*/
enum {
BB_ALL = 0, /* OR of all bitboards */
BB_UNUSED, /* future use ? */
BB_PAWN = E_PAWN,
BB_KNIGHT,
BB_BISHOP,
BB_ROOK,
BB_QUEEN,
BB_KING,
BB_END
};
/* piece bitmask in piece_t
*/
enum {
EMPTY = 0,
PAWN = 1 << (E_PAWN - 1), /* 1<<(2-1) = 0x02 00000010 */
KNIGHT = 1 << (E_KNIGHT - 1), /* 0x04 00000100 */
BISHOP = 1 << (E_BISHOP - 1), /* 0x08 00001000 */
ROOK = 1 << (E_ROOK - 1), /* 0x10 00010000 */
QUEEN = 1 << (E_QUEEN - 1), /* 0x20 00100000 */
KING = 1 << (E_KING - 1), /* 0x40 01000000 */
};
#define PIECETOBB(p) (ffs64(PIECE(p))) /* from piece_t to bb piece array */
#define WHITE 0 /* 0x00 00000000 */
#define BLACK 1 /* 0x01 00000001 */
#define OPPONENT(p) !(p)
#define MASK_COLOR 0x01 /* 00000001 */
#define MASK_PIECE 0x7E /* 01111110 */
#define COLOR(p) ((p) & MASK_COLOR) /* bitmask */
#define PIECE(p) ((p) & MASK_PIECE)
#define E_PIECE(p) (ffs64(PIECE(p))) /* convert mask to E_XX */
#define IS_WHITE(p) (!COLOR(p))
#define IS_BLACK(p) (COLOR(p))
#define SET_WHITE(p) ((p) &= ~MASK_COLOR)
#define SET_BLACK(p) ((p) |= MASK_COLOR)
#define SET_COLOR(p, c) (!(c)? SET_WHITE(p): SET_BLACK(p))
/* flip a 0-63 square:
* Vertical: G8 (62) becomes G1 (6)
* Horizontal: G8 (62) becomes B8 (57)
*/
#define FLIP_V(sq) ((sq) ^ 56)
#define FLIP_H(sq) ((sq) ^ 7)
/* square_t bits structure : rrrrffff
* ffff: file
* rrrr: rank
*/
typedef uchar square_t;
/* castle_t bits structure
*/
typedef unsigned char castle_t;
#define CASTLE_WK (1 << 0) /* 0x01 00000001 */
#define CASTLE_WQ (1 << 1) /* 0x02 00000010 */
#define CASTLE_BK (1 << 2) /* 0x04 00000100 */
#define CASTLE_BQ (1 << 3) /* 0x08 00001000 */
#define CASTLE_W (CASTLE_WK | CASTLE_WQ) /* 00000011 W castle mask */
#define CASTLE_B (CASTLE_BK | CASTLE_BQ) /* 00001100 B castle mask */
/* game phases
*/
#define OPENING 0
#define MIDDLEGAME 1
#define ENDGAME 2
/* bitboard
*/
typedef u64 bitboard_t;
/* eval type
*/
typedef s32 eval_t;
/* forward typedefs
*/
typedef struct piece_list_s piece_list_t;
typedef struct board_s board_t;
typedef struct pos_s pos_t;
typedef struct move_s move_t;
#endif

View File

@@ -0,0 +1,199 @@
/* eval-simple.c - simple position evaluation.
*
* Copyright (C) 2023 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#include "br.h"
#include "debug.h"
#include "piece.h"
#include "eval-simple.h"
#include "position.h"
/*
* Tables are from https://www.chessprogramming.org/Simplified_Evaluation_Function
*
* Attention! Tables are black point of view (to be visually easier to read).
*/
static int mg_pawn[] = {
0, 0, 0, 0, 0, 0, 0, 0,
50, 50, 50, 50, 50, 50, 50, 50,
10, 10, 20, 30, 30, 20, 10, 10,
5, 5, 10, 25, 25, 10, 5, 5,
0, 0, 0, 20, 20, 0, 0, 0,
5, -5, -10, 0, 0, -10, -5, 5,
5, 10, 10, -20, -20, 10, 10, 5,
0, 0, 0, 0, 0, 0, 0, 0
};
static int mg_knight[] = {
-50, -40, -30, -30, -30, -30, -40, -50,
-40, -20, 0, 0, 0, 0, -20, -40,
-30, 0, 10, 15, 15, 10, 0, -30,
-30, 5, 15, 20, 20, 15, 5, -30,
-30, 0, 15, 20, 20, 15, 0, -30,
-30, 5, 10, 15, 15, 10, 5, -30,
-40, -20, 0, 5, 5, 0, -20, -40,
-50, -40, -30, -30, -30, -30, -40, -50
};
static int mg_bishop[] = {
-20, -10, -10, -10, -10, -10, -10, -20,
-10, 0, 0, 0, 0, 0, 0, -10,
-10, 0, 5, 10, 10, 5, 0, -10,
-10, 5, 5, 10, 10, 5, 5, -10,
-10, 0, 10, 10, 10, 10, 0, -10,
-10, 10, 10, 10, 10, 10, 10, -10,
-10, 5, 0, 0, 0, 0, 5, -10,
-20, -10, -10, -10, -10, -10, -10, -20
};
static int mg_rook[] = {
0, 0, 0, 0, 0, 0, 0, 0,
5, 10, 10, 10, 10, 10, 10, 5,
-5, 0, 0, 0, 0, 0, 0, -5,
-5, 0, 0, 0, 0, 0, 0, -5,
-5, 0, 0, 0, 0, 0, 0, -5,
-5, 0, 0, 0, 0, 0, 0, -5,
-5, 0, 0, 0, 0, 0, 0, -5,
0, 0, 0, 5, 5, 0, 0, 0
};
static int mg_queen[] = {
-20, -10, -10, -5, -5, -10, -10, -20,
-10, 0, 0, 0, 0, 0, 0, -10,
-10, 0, 5, 5, 5, 5, 0, -10,
-5, 0, 5, 5, 5, 5, 0, -5,
0, 0, 5, 5, 5, 5, 0, -5,
-10, 5, 5, 5, 5, 5, 0, -10,
-10, 0, 5, 0, 0, 0, 0, -10,
-20, -10, -10, -5, -5, -10, -10, -20
};
static int mg_king[] = {
-30, -40, -40, -50, -50, -40, -40, -30,
-30, -40, -40, -50, -50, -40, -40, -30,
-30, -40, -40, -50, -50, -40, -40, -30,
-30, -40, -40, -50, -50, -40, -40, -30,
-20, -30, -30, -40, -40, -30, -30, -20,
-10, -20, -20, -20, -20, -20, -20, -10,
20, 20, 0, 0, 0, 0, 20, 20,
20, 30, 10, 0, 0, 10, 30, 20
};
static int eg_king[] = {
-50, -40, -30, -20, -20, -30, -40, -50,
-30, -20, -10, 0, 0, -10, -20, -30,
-30, -10, 20, 30, 30, 20, -10, -30,
-30, -10, 30, 40, 40, 30, -10, -30,
-30, -10, 30, 40, 40, 30, -10, -30,
-30, -10, 20, 30, 30, 20, -10, -30,
-30, -30, 0, 0, 0, 0, -30, -30,
-50, -30, -30, -30, -30, -30, -30, -50
};
/* as pieces bitboard tables start at position 2; we make these tables
* bigger.
*/
static int *mg_tables[] = {
NULL,
NULL,
mg_pawn,
mg_knight,
mg_bishop,
mg_rook,
mg_queen,
mg_king
};
static int *eg_tables[] = {
NULL,
NULL,
mg_pawn,
mg_knight,
mg_bishop,
mg_rook,
mg_queen,
eg_king
};
/* to flip vertically a square, we need to XOR it with 56
*/
static int mg_table[2][6 + 2][64];
static int eg_table[2][6 + 2][64];
void eval_simple_init(void)
{
# ifdef DEBUG_EVAL
log_f(1, "initializing piece tables\n");
# endif
for (int piece = BB_PAWN; piece <= BB_KING; ++piece) {
for (int square = 0; square < 64; ++square) {
mg_table[WHITE][piece][square] = mg_tables[piece][FLIP_V(square)];
eg_table[WHITE][piece][square] = eg_tables[piece][FLIP_V(square)];
mg_table[BLACK][piece][square] = mg_tables[piece][square];
eg_table[BLACK][piece][square] = eg_tables[piece][square];
}
}
}
/**
* eval_simple() - simple and fast position evaluation
* @pos: &position to evaluate
*
* This function is normally used only during initialization,
* or when changing phase (middlegame <--> endgame), as the eval
* will be done increntally when doing moves.
*
* @return: the @pos evaluation in centipawns
*/
eval_t eval_simple(pos_t *pos)
{
eval_t eval[2] = { 0, 0 };
int eg = simple_is_endgame(pos);
int (*gg)[6 + 2][64]= eg? eg_table: mg_table;
pos->eval_simple_phase = ENDGAME;
# ifdef DEBUG_EVAL
log_f(5, "phase = %s.\n", eg? "endgame": "midgame");
# endif
for (int color = WHITE; color <= BLACK; ++color) {
for (uint piece = PAWN; piece <= KING; piece <<= 1) {
int bb = PIECETOBB(piece), cur;
u64 _t;
# ifdef DEBUG_EVAL
log_f(5, "p=%u bb=%d %s %s: count=%d val=%ld ", piece, bb, color? "black": "white",
P_SYM(piece), popcount64(pos->bb[color][bb]),
popcount64(pos->bb[color][bb]) * P_VALUE(piece));
# endif
eval[color] += popcount64(pos->bb[color][bb]) * P_LETTER(piece);
bit_for_each64(cur, _t, pos->bb[color][bb]) {
# ifdef DEBUG_EVAL
log(5, "sq=%d:%d ", cur, gg[color][bb][cur]);
# endif
eval[color] += gg[color][bb][cur];
}
# ifdef DEBUG_EVAL
log(5, "\n");
# endif
}
}
# ifdef DEBUG_EVAL
log_f(2, "eval:%d white:%d black:%d\n", eval[WHITE] - eval[BLACK],
eval[WHITE], eval[BLACK]);
# endif
return eval[WHITE] - eval[BLACK];
}

View File

@@ -0,0 +1,47 @@
/* eval-simple.h - simple position evaluation.
*
* Copyright (C) 2021 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#ifndef EVAL_SIMPLE_H
#define EVAL_SIMPLE_H
#include "chessdefs.h"
/* no queen on board */
#define simple_no_queen(p, c) \
( !(p)->bb[c][BB_QUEEN] )
#define simple_one_queen(p, c) \
( popcount64((p)->bb[c][BB_QUEEN]) == 1 )
#define simple_no_rook(p, c) \
(!(p)->bb[c][BB_ROOK])
#define simple_one_minor_piece(p, c) \
(popcount64((p)->bb[c][BB_KNIGHT] | (p)->bb[c][BB_BISHOP]) == 1)
#define simple_is_endgame(p) \
( (simple_no_queen(p, WHITE) || \
(simple_one_queen(p, WHITE) && \
simple_no_rook(p, WHITE) && \
simple_one_minor_piece(p, WHITE))) \
&& \
(simple_no_queen(p, BLACK) || \
(simple_one_queen(p, BLACK) && \
simple_no_rook(p, BLACK) && \
simple_one_minor_piece(p, BLACK))) )
void eval_simple_init(void);
eval_t eval_simple(pos_t *pos);
#endif /* EVAL_SIMPLE_H */

View File

@@ -0,0 +1,95 @@
/* eval.c - static position evaluation.
*
* Copyright (C) 2021-2023 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#include <stdio.h>
#include <list.h>
#include <debug.h>
#include "position.h"
#include "eval.h"
#include "eval-simple.h"
inline eval_t eval_material(pos_t *pos, bool color)
{
eval_t res = 0;
/* I need to do something about the king, if it can be potentially taken
* if pseudo-moves include a pinned piece on King.
*/
for (uint piece = PAWN; piece < KING; piece <<= 1) {
uint bb = PIECETOBB(piece);
# ifdef DEBUG_EVAL
log_f(2, "color=%u piece=%u bb=%u=%c count=%ul val=%ld\n",
color, piece, bb, P_LETTER(piece), popcount64(pos->bb[color][bb]),
P_VALUE(piece));
# endif
/* attention here */
res += popcount64(pos->bb[color][bb]) * P_VALUE(piece);
}
return res;
}
inline eval_t eval_mobility(pos_t *pos, bool color)
{
return pos->mobility[color];
}
inline eval_t eval_square_control(pos_t *pos, bool color)
{
return popcount64(pos->controlled[color]);
}
eval_t eval(pos_t *pos)
{
eval_t simple = 0, control[2] = {0};
if (pos->eval != EVAL_INVALID)
return pos->eval;
/* 1) pieces value */
//material[WHITE] = eval_material(pos, WHITE);
//material[BLACK] = eval_material(pos, BLACK);
simple = eval_simple(pos);
# ifdef DEBUG_EVAL
log_f(2, "eval_simple=%d\n", simple);
# endif
/* 2) square control: 10 square controls diff = 1 pawn */
control[WHITE] = eval_square_control(pos, WHITE);
control[BLACK] = eval_square_control(pos, BLACK);
# ifdef DEBUG_EVAL
log_f(2, "square control: W:%d B:%d diff=%d\n",
control[WHITE], control[BLACK],
(control[WHITE] - control[BLACK]) * 10);
# endif
/* 3) mobility: 10 mobility diff = 1 pawn
*/
# ifdef DEBUG_EVAL
log_f(2, "mobility: W:%u B:%u diff=%d\n",
pos->mobility[WHITE], pos->mobility[BLACK],
(pos->mobility[WHITE] - pos->mobility[BLACK]) * 10);
# endif
eval_t res = simple +
(control[WHITE] - control[BLACK]) * 10 +
(pos->mobility[WHITE] - pos->mobility[BLACK]) * 10;
# ifdef DEBUG_EVAL
log_f(2, "eval: %d\n", res);
# endif
pos->eval = res;
return res;
}

View File

@@ -0,0 +1,37 @@
/* eval.h - static position evaluation.
*
* Copyright (C) 2021 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#ifndef EVAL_H
#define EVAL_H
#include <limits.h>
#include "chessdefs.h"
#include "piece.h"
/* max pieces eval is KING_VALUE + 9*QUEEN_VALUE + 2*ROOK_VALUE + 2*BISHOP_VALUE
* + 2*KNIGHT_VALUE which around 30000.
* We are on secure side with -50000/+50000
*/
#define EVAL_MAX (50000)
#define EVAL_MIN (-EVAL_MAX)
#define EVAL_INVALID INT_MIN
#define EVAL_MATE EVAL_MAX
eval_t eval_material(pos_t *pos, bool color);
eval_t eval_mobility(pos_t *pos, bool color);
eval_t eval_square_control(pos_t *pos, bool color);
eval_t eval(pos_t *pos);
#endif /* EVAL_H */

View File

@@ -0,0 +1,175 @@
/* fen.c - fen notation.
*
* Copyright (C) 2021 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
#include <debug.h>
#include "chessdefs.h"
#include "position.h"
#include "board.h"
#include "fen.h"
#include "piece.h"
/* Starting Position :
* rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
* After 1.e4 :
* rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1
* After 1... c5 :
* rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq c6 0 2
* After 2. Nf3:
* rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2
*
* 1 : White uppercase
* 2 : next move (w or b)
* 3 : Castling capabilities: "-" if none, KQ/kq if white/black can castle
* on K or Q side
* 4 : en-passant: if pawn just moved 2 squares, indicate target square (e.g.
* for e2-e4 this field is e3)
* 5 : half moves since last capture or pawn advance (for 50 moves rule)
* 6 : full moves, starts at 1, increments after black move
*
*/
// warning, we expect a valid fen input
pos_t *fen2pos(pos_t *pos, char *fen)
{
char *p = fen;
short rank, file, skip, color, bbpiece;
piece_t piece;
board_t *board = pos->board;
# define SKIP_BLANK(p) for(;*(p) == ' '; (p)++)
pos_clear(pos);
/* 1) get piece placement information
*/
for (rank = 7, file = 0; *p && *p != ' '; ++p) {
color = isupper(*p)? WHITE: BLACK;
char cp = toupper(*p);
switch (cp) {
case CHAR_PAWN:
bbpiece = BB_PAWN;
piece = PAWN;
goto set_square;
case CHAR_KNIGHT:
bbpiece = BB_KNIGHT;
piece = KNIGHT;
goto set_square;
case CHAR_BISHOP:
bbpiece = BB_BISHOP;
piece = BISHOP;
goto set_square;
case CHAR_ROOK:
bbpiece = BB_ROOK;
piece = ROOK;
goto set_square;
case CHAR_QUEEN:
bbpiece = BB_QUEEN;
piece = QUEEN;
goto set_square;
case CHAR_KING:
bbpiece = BB_KING;
piece = KING;
//pos->bb[color][BB_KING] = BB(file, rank);
//goto set_square;
set_square:
# ifdef DEBUG_FEN
log_i(5, "f=%d r=%d *p=%c piece=%c color=%d\n",
file, rank, *p, cp, color);
# endif
pos->bb[color][bbpiece] |= BB(file, rank);
pos->occupied[color] |= BB(file, rank);
SET_COLOR(piece, color);
board[SQ88(file, rank)].piece = piece;
board[SQ88(file, rank)].s_piece =
piece_add(pos, piece, SQ88(file, rank));
file++;
break;
case '/':
rank--;
file = 0;
break;
default:
skip = cp - '0';
while (skip--) {
board[SQ88(file++, rank)].piece = EMPTY;
}
}
}
# ifdef DEBUG_FEN
for (rank = 7; rank >= 0; --rank) {
for (file = 0; file < 8; ++file) {
log(5, "%02x ", board[SQ88(file, rank)].piece);
}
log(5, "\n");
}
# endif
/* 2) next move color
*/
SKIP_BLANK(p);
SET_COLOR(pos->turn, *p == 'w' ? WHITE : BLACK);
p++;
/* 3) castle status
*/
SKIP_BLANK(p);
pos->castle = 0;
if (*p != '-') {
for (; *p && *p != ' '; ++p) {
switch (*p) {
case 'K':
pos->castle |= CASTLE_WK;
break;
case 'k':
pos->castle |= CASTLE_BK;
break;
case 'Q':
pos->castle |= CASTLE_WQ;
break;
case 'q':
pos->castle |= CASTLE_BQ;
break;
}
}
}
p++;
/* 4) en passant
*/
SKIP_BLANK(p);
pos->en_passant = 0;
if (*p != '-') {
//SET_F(pos->en_passant, C2FILE(*p++));
//SET_R(pos->en_passant, C2RANK(*p++));
pos->en_passant = SQ88(C2FILE(*p), C2RANK(*(p+1)));
pos += 2;
} else {
p++;
}
/* 5) half moves since last capture or pawn move and
* 6) current move number
*/
SKIP_BLANK(p);
//log_i(5, "pos=%d\n", (int)(p-fen));
sscanf(p, "%hd %hd", &pos->clock_50, &pos->curmove);
# ifdef DEBUG_FEN
log_i(5, "50 rule=%d current move=%d\n", pos->clock_50, pos->curmove);
# endif
return pos;
}

View File

@@ -0,0 +1,21 @@
/* fen.h - fen notation.
*
* Copyright (C) 2021 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#ifndef FEN_H
#define FEN_H
#include "position.h"
pos_t *fen2pos(pos_t *pos, char *fen);
#endif /* FEN_H */

View File

@@ -0,0 +1,890 @@
/* move.c - move management.
*
* Copyright (C) 2021 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#include <malloc.h>
#include <ctype.h>
#include <br.h>
#include <list.h>
#include <list_sort.h>
#include <debug.h>
#include "chessdefs.h"
#include "board.h"
#include "bitboard.h"
#include "piece.h"
#include "move.h"
#include "eval.h"
#include "eval-simple.h"
static pool_t *moves_pool;
static struct vector {
unsigned char ndirs;
char slide;
char dir[8];
} vectors[] = {
[KNIGHT] = { 8, 0, { -33, -31, -18, -14, 14, 18, 31, 33 }},
[BISHOP] = { 4, 1, { -15, -17, 15, 17 }},
[ROOK] = { 4, 1, { -1, -16, 1, 16 }},
[QUEEN] = { 8, 1, { -1, -16, 1, 16, -15, -17, 15, 17 }},
[KING] = { 8, 0, { -1, -16, 1, 16, -15, -17, 15, 17 }}
};
/* squares needed to be empty & not controlled by opponent for castle.
* For black castle, same values 7 rows higher (>> 7*8)
*/
static struct can_castle {
bitboard_t controlled[2];
bitboard_t occupied[2];
} castle_squares[2] = {
/* Queen side King side Queen side King side */
{ { C1bb|D1bb|E1bb, E1bb|F1bb|G1bb }, { B1bb|C1bb|D1bb, F1bb|G1bb } },
{ { C8bb|D8bb|E8bb, E8bb|F8bb|G8bb }, { B8bb|C8bb|D8bb, F8bb|G8bb } }
};
pool_t *moves_pool_init()
{
if (!moves_pool)
moves_pool = pool_create("moves", 128, sizeof(move_t));
return moves_pool;
}
void moves_pool_stats()
{
if (moves_pool)
pool_stats(moves_pool);
}
/**
* move_print() - print a move
* @movenum: move number
* @move: &move to display
* @flags: options to display
*
* Possible flags are:
* M_PR_CAPT: print move if capture
* M_PR_NCAPT: print move if non capture
* M_PR_NUM: print also move number
* M_PR_LONG: print long notation
* M_PR_NL: print a newline after move
* M_PR_EVAL: print move eval
*
* @return: 0 if nothing printed, 1 otherwise
*/
int move_print(int movenum, move_t *move, move_flags_t flags)
{
if ((flags & M_PR_CAPT) && !(move->flags & M_CAPTURE)) {
# ifdef DEBUG_MOVE
log_i(9, "skipping capture & %#04x\n", move->flags);
# endif
return 0;
}
if ((flags & M_PR_NCAPT) && (move->flags & M_CAPTURE)) {
# ifdef DEBUG_MOVE
log_i(9, "skipping !capture & %#04x\n", move->flags);
# endif
return 0;
}
if (flags & M_PR_NUM)
log(1, "%d:", movenum);
if (move->flags & M_CASTLE_K) {
log(1, "O-O");
goto end;
} else if (move->flags & M_CASTLE_Q) {
log(1, "O-O-O");
goto end;
} else {
log(1, "%s%c%c", P_SYM(move->piece),
FILE2C(F88(move->from)),
RANK2C(R88(move->from)));
if (move->flags & M_CAPTURE) {
log(1, "x");
if (flags & M_PR_LONG)
log(1, "%s", P_SYM(move->capture));
} else {
log(1, "-");
}
log(1, "%c%c",
FILE2C(F88(move->to)),
RANK2C(R88(move->to)));
if (flags & M_PR_LONG && move->flags & M_EN_PASSANT)
log(1, "e.p.");
if (move->promotion)
log(1, "=%s", P_SYM(move->promotion));
if (flags & M_PR_EVAL)
log(1, "[ev:%d] ", move->eval);
end:
log(1, " ");
}
if (flags & M_PR_NL)
log(1, "\n");
return 1;
}
void moves_print(pos_t *pos, move_flags_t flags)
{
struct list_head *p_cur, *tmp;
move_t *move;
int movenum;
for (int color=WHITE; color <= BLACK; ++color) {
int verif = 0;
log(1, "%s pseudo-moves:\n\t", color == WHITE? "White": "Black");
if (! (flags & M_PR_SEPARATE)) {
movenum = 1;
list_for_each_safe(p_cur, tmp, &pos->moves[color]) {
move = list_entry(p_cur, move_t, list);
verif += move_print(movenum++, move, flags);
}
} else {
log(1, "captures: ");
movenum = 1;
list_for_each_safe(p_cur, tmp, &pos->moves[color]) {
move = list_entry(p_cur, move_t, list);
verif += move_print(movenum++, move, flags | M_PR_CAPT);
}
movenum = 1;
log(1, "\n\tothers : ");
list_for_each_safe(p_cur, tmp, &pos->moves[color]) {
move = list_entry(p_cur, move_t, list);
verif += move_print(movenum++, move, flags | M_PR_NCAPT);
}
}
log(1, "\n\tTotal moves = %d mobility=%u\n", verif, pos->mobility[color]);
}
}
static move_t *move_add(pos_t *pos, piece_t piece, square_t from,
square_t to)
{
board_t *board = pos->board;
move_t *move;
int color = COLOR(pos->board[from].piece);
# ifdef DEBUG_MOVE
log_i(3, "piece_color=%d turn=%d from=%c%c to=%c%c\n",
color, pos->turn,
FILE2C(F88(from)),
RANK2C(R88(from)),
FILE2C(F88(to)),
RANK2C(R88(to)));
# endif
/* invalid position if opponent king is attacked
*/
if (board[to].piece & KING) {
# ifdef DEBUG_MOVE
log_i(2, "invalid position: opponent king [%c%c] is in check.\n",
FILE2C(F88(to)), RANK2C(R88(to)));
# endif
return NULL;
}
if (!(move = pool_get(moves_pool)))
return NULL;
list_add(&move->list, &pos->moves[color]);
move->piece = piece | color;
move->from = from;
move->to = to;
move->capture = board[to].piece;
if (PIECE(move->capture) == KING)
pos->check[color]++;
move->flags = M_NORMAL;
if (move->capture)
move->flags |= M_CAPTURE;
move->pos = NULL;
# ifdef DEBUG_MOVE
log_i(3, "added %s %s move from %c%c to %c%c\n",
COLOR(move->piece)? "black": "white",
P_NAME(PIECE(move->piece)),
FILE2C(F88(move->from)), RANK2C(R88(move->from)),
FILE2C(F88(move->to)), RANK2C(R88(move->to)));
# endif
return move;
}
/**
* move_del() - delete a move from list.
* @ptr: move &list_head
*
* Remove the move whose 'list' element address is @ptr.
*/
void move_del(struct list_head *ptr)
{
move_t *move = list_entry(ptr, move_t, list);
# ifdef DEBUG_MOVE
log_i(3, "delete move from %c%c to %c%c\n",
FILE2C(F88(move->from)), RANK2C(R88(move->from)),
FILE2C(F88(move->to)), RANK2C(R88(move->to)));
# endif
if (move->pos)
pos_del(move->pos);
list_del(ptr);
pool_add(moves_pool, move);
return;
}
/**
* move_del() - delete all position moves.
* @ppos: &position.
*
* Remove all generated moves from @pos structure.
*/
int moves_del(pos_t *pos)
{
struct list_head *p_cur, *tmp, *head;
int count = 0;
for (int color = WHITE; color <= BLACK; ++color) {
head = &pos->moves[color];
list_for_each_safe(p_cur, tmp, head) {
move_del(p_cur);
count++;
}
}
# ifdef DEBUG_PIECE
log_f(3, "%d moves removed\n", count);
# endif
return count;
}
/* TODO: return nmoves */
static move_t *move_pawn_add(pos_t *pos, piece_t piece, square_t from,
square_t to, unsigned char rank7)
{
move_t *move;
piece_t promote;
unsigned char color = COLOR(piece);
if (R88(from) == rank7) { /* promotion */
for (promote = QUEEN; promote > PAWN; promote >>= 1) {
if ((move = move_add(pos, piece, from, to))) {
move->flags |= M_PROMOTION;
move->promotion = promote | color;
}
}
} else {
move = move_add(pos, piece, from, to);
}
return move;
}
/**
* pseudo_moves_pawn() - generate moves for pawn.
* @pos: &position
* @ppiece: &piece_list pawn structure pointer
* @doit: add move to moves list
*
* Calculate all possible moves for @ppiece pawn.
* If @doit is true, add moves to @pos' moves list.
*/
int pseudo_moves_pawn(pos_t *pos, piece_list_t *ppiece, bool doit)
{
piece_t piece = PIECE(ppiece->piece);
unsigned char color = COLOR(ppiece->piece);
square_t square = ppiece->square, new;
board_t *board = pos->board;
unsigned char rank2, rank7, rank5;
move_t *move = NULL;
char dir;
int count = 0;
/* setup direction */
if (IS_WHITE(color)) {
dir = 1;
rank2 = 1;
rank7 = 6;
rank5 = 4;
} else {
dir = -1;
rank2 = 6;
rank7 = 1;
rank5 = 3;
}
# ifdef DEBUG_MOVE
log_f(2, "pos:%p turn:%s piece:%d [%s %s] dir:%d at %#04x[%c%c]\n",
pos,
IS_WHITE(pos->turn)? "white": "black",
piece,
IS_WHITE(color)? "white": "black",
P_NAME(piece),
dir,
square,
FILE2C(F88(square)), RANK2C(R88(square)));
# endif
/* normal push. We do not test for valid destination square here,
* assuming position is valid. Is that correct ?
*/
new = square + dir * 16;
if (!board[new].piece) {
# ifdef DEBUG_MOVE
log_i(4, "pushing pawn %#04x\n", square);
# endif
pos->mobility[color]++;
count++;
if (doit)
move_pawn_add(pos, piece | color, square, new, rank7);
/* push 2 squares */
log(4, "R88(%#x)=%d R2=%d \n", square, R88(square), rank2);
if (R88(square) == rank2) {
new += dir * 16;
if (SQ88_OK(new) && !board[new].piece) {
# ifdef DEBUG_MOVE
log_i(4, "pushing pawn %#04x 2 squares\n", square);
# endif
//log_f(2, "pawn move2 mobility\n");
pos->mobility[color]++;
count++;
if (doit)
move_pawn_add(pos, piece | color, square, new, rank7);
}
}
}
/* en passant - not accounted for mobility. Correct ? */
if (pos->en_passant && R88(square) == rank5) {
unsigned char ep_file = F88(pos->en_passant);
unsigned char sq_file = F88(square);
# ifdef DEBUG_MOVE
log_i(4, "possible en passant on rank %#x (current = %#0x)\n", ep_file,
sq_file);
# endif
if (sq_file == ep_file - 1 || sq_file == ep_file + 1) {
square_t t_square = SQ88(ep_file, rank5); /* taken pawn square */
piece_t captured = board[t_square].piece;
move = move_pawn_add(pos, piece | color , square, pos->en_passant, rank7);
move->flags |= M_EN_PASSANT | M_CAPTURE;
move->capture = captured;
pos->mobility[color]++;
count++;
}
}
/* capture */
int two=0;
for (new = square + dir * 15; two < 2; new = square + dir * 17, two++) {
# ifdef DEBUG_MOVE
log_i(4, "pawn capture %#04x %#04x\n", square, new);
# endif
if (SQ88_NOK(new))
continue;
pos->controlled[color] |= SQ88_2_BB(new);
if (board[new].piece && COLOR(board[new].piece) != color) {
if (PIECE(board[new].piece) == KING)
pos->check[color]++;
//log_f(2, "pawn capture mobility\n");
pos->mobility[color]++;
count++;
if (doit)
move_pawn_add(pos, piece | color, square, new, rank7);
}
}
# ifdef DEBUG_MOVE
log_f(2, "pos:%p turn:%s piece:%d [%s %s] dir:%d at %#04x[%c%c] count=%d\n",
pos,
IS_WHITE(pos->turn)? "white": "black",
piece,
IS_WHITE(color)? "white": "black",
P_NAME(piece),
dir,
square,
FILE2C(F88(square)), RANK2C(R88(square)), count);
# endif
return count;
}
/**
* pseudo_moves_castle() - generate castle moves.
* @pos: &position
* @color: side for which to generate moves
* @doit: add move to moves list
* @do_king: count king moves in mobility
*
* Calculate the possible castle moves for @color side.
* If @doit is true, add moves to @pos' moves list.
* If @do_king is true, account king moves (incl. castle) to mobility.
*
* @return: The number of possible king moves.
*/
int pseudo_moves_castle(pos_t *pos, bool color, bool doit, bool do_king)
{
board_t *board = pos->board;
unsigned char rank1, castle_K, castle_Q;
move_t *move = NULL;
unsigned short count=0;
struct can_castle *can_castle;
bitboard_t controlled;
bitboard_t occupied = pos->occupied[WHITE] | pos->occupied[BLACK];
//pos_t *newpos;
# ifdef DEBUG_MOVE
log_f(2, "pos:%p turn:%s color:%s\n",
pos,
IS_WHITE(pos->turn)? "white": "black",
IS_WHITE(color)? "white": "black");
# endif
if (IS_WHITE(color)) {
rank1 = 0;
castle_K = pos->castle & CASTLE_WK;
castle_Q = pos->castle & CASTLE_WQ;
can_castle = castle_squares+WHITE;
controlled = pos->controlled[BLACK];
} else {
rank1 = 7;
castle_K = pos->castle & CASTLE_BK;
castle_Q = pos->castle & CASTLE_BQ;
can_castle = castle_squares+BLACK;
controlled = pos->controlled[WHITE];
}
if (castle_K) {
if (occupied & can_castle->occupied[1]) {
# ifdef DEBUG_MOVE
log(5, "Cannot castle K side: occupied\n");
# endif
goto next;
}
if (controlled & can_castle->controlled[1]) {
# ifdef DEBUG_MOVE
log(5, "Cannot castle K side: controlled\n");
# endif
goto next;
}
if (do_king) {
pos->mobility[color]++;
count++;
}
if (doit) {
move = move_add(pos, board[SQ88(4, rank1)].piece,
SQ88(4, rank1), SQ88(6, rank1));
if (move)
move->flags |= M_CASTLE_K;
}
}
next:
if (castle_Q) {
if (occupied & can_castle->occupied[0]) {
# ifdef DEBUG_MOVE
log(5, "Cannot castle Q side: occupied\n");
# endif
goto end;
}
if (controlled & can_castle->controlled[0]) {
# ifdef DEBUG_MOVE
log(5, "Cannot castle Q side: controlled\n");
# endif
goto end;
}
if (do_king) {
pos->mobility[color]++;
count++;
}
if (doit) {
move = move_add(pos, board[SQ88(4, rank1)].piece,
SQ88(4, rank1), SQ88(2, rank1));
if (move)
move->flags |= M_CASTLE_Q;
}
}
end:
return count;
}
/**
* pseudo_moves_gen() - general move generation for non pawn pieces
* @pos: &position
* @ppiece: &piece_list structure pointer
* @doit: add move to moves list
* @do_king: count king moves
*
* Calculate all possible moves for @ppiece.
* If @doit is true, add moves to @pos' moves list.
* If @do_king is true, account king moves (incl. castle) to mobility.
*/
int pseudo_moves_gen(pos_t *pos, piece_list_t *ppiece, bool doit, bool do_king)
{
piece_t piece = PIECE(ppiece->piece);
unsigned char color = COLOR(ppiece->piece);
struct vector *vector = vectors+piece;
square_t square = ppiece->square;
unsigned char ndirs = vector->ndirs;
char slide = vector->slide;
board_t *board = pos->board;
//move_t *move;
int count = 0;
u64 bb_new;
# ifdef DEBUG_MOVE
log_f(2, "pos:%p turn:%s piece:%d [%s %s] at %#04x[%c%c]\n",
pos,
IS_WHITE(pos->turn)? "white": "black",
piece,
IS_WHITE(color)? "white": "black",
P_NAME(piece),
square,
FILE2C(F88(square)), RANK2C(R88(square)));
log_i(5, "vector=%ld ndirs=%d slide=%d\n", vector-vectors, ndirs, slide);
# endif
for (int curdir = 0; curdir < ndirs; ++curdir) {
char dir = vector->dir[curdir];
for (square_t new = square + dir; ; new = new + dir) {
/* outside board */
if (SQ88_NOK(new)) {
# ifdef DEBUG_MOVE
log_i(4,"skipping %04x (invalid square)\n", new);
# endif
break;
}
bb_new = SQ88_2_BB(new);
# ifdef DEBUG_MOVE
log_i(2, "trying %#x=%c%c bb=%#lx\n",
new, FILE2C(F88(new)), RANK2C(R88(new)),
bb_new);
//bitboard_print(new_bitboard);
# endif
pos->controlled[color] |= bb_new;;
/* king: do not move to opponent controlled square */
if (piece == KING && pos->controlled[OPPONENT(color)] & bb_new) {
# ifdef DEBUG_MOVE
log_i(2, "%s king cannot move to %c%c\n",
IS_WHITE(color)? "white": "black",
FILE2C(F88(new)), RANK2C(R88(new)));
# endif
break;
}
if (bb_new & pos->occupied[color]) {
//bitboard_print(pos->occupied[color]);
//bitboard_print(pos->occupied[OPPONENT(color)]);
# ifdef DEBUG_MOVE
log_i(2, "BB: skipping %#lx [%c%c] (same color piece)\n",
bb_new, FILE2C(F88(new)), RANK2C(R88(new)));
# endif
break;
}
/* we are sure the move is valid : we create move */
if (piece != KING || do_king) {
pos->mobility[color]++;
count++;
}
if (doit)
move_add(pos, ppiece->piece, square, new);
if (board[new].piece) { /* stopper move */
break;
}
if (!slide)
break;
}
}
# ifdef DEBUG_MOVE
log_f(2, "pos:%p turn:%s piece:%d [%s %s] at %#04x[%c%c] count=%d\n",
pos,
IS_WHITE(pos->turn)? "white": "black",
piece,
IS_WHITE(color)? "white": "black",
P_NAME(piece),
square,
FILE2C(F88(square)), RANK2C(R88(square)), count);
# endif
return count;
}
/**
* moves_gen() - move generation for one color
* @pos: &position
* @color: side
* @doit: add move to moves list
* @do_king: count king moves
*
* Calculate all possible moves for @color.
* If @doit is true, add moves to @pos' moves list.
* If @do_king is true, account king moves (incl. castle) to mobility.
*/
int moves_gen(pos_t *pos, bool color, bool doit, bool do_king)
{
struct list_head *p_cur, *tmp, *piece_list;
piece_list_t *piece;
int count = 0;
# ifdef DEBUG_MOVE
log_f(2, "color:%s doit:%d\n", color? "Black": "White", doit);
# endif
/* do not generate moves if already done for color */
if (!list_empty(&pos->moves[color]))
doit = false;
piece_list = &pos->pieces[color];
pos->mobility[color] = 0;
pos->controlled[color] = 0;
count += pseudo_moves_castle(pos, color, doit, do_king);
list_for_each_safe(p_cur, tmp, piece_list) {
piece = list_entry(p_cur, piece_list_t, list);
if (PIECE(piece->piece) != PAWN)
count += pseudo_moves_gen(pos, piece, doit, do_king);
else
count += pseudo_moves_pawn(pos, piece, doit);
count++;
}
return count;
}
/**
* moves_gen_king_moves() - adjust king mobility
* @pos: &position
* @color: king color
* @doit: add move to moves list
*
* Compute the number of king moves (incl. castle), after opponent controlled
* are known.
* If @doit is true, add moves to @pos' moves list.
*
* @return: The number of possible king moves.
*/
int moves_gen_king_moves(pos_t *pos, bool color, bool doit)
{
int count = 0;
piece_list_t *king = list_first_entry(&pos->pieces[color], piece_list_t, list);
count = pseudo_moves_castle(pos, king, doit, true);
count += pseudo_moves_gen(pos, king, doit, true);
return count;
}
static int moves_cmp_eval(__unused void *data, const struct list_head *h1, const struct list_head *h2)
{
move_t *m1 = list_entry(h1, move_t, list);
move_t *m2 = list_entry(h2, move_t, list);
return m2->eval_simple - m1->eval_simple;
}
/**
* moves_sort() sort - sort moves list, best eval first.
* @pos: &position.
*/
void moves_sort(pos_t *pos)
{
list_sort(NULL, &pos->moves[pos->turn], moves_cmp_eval);
}
/**
* moves_gen_all_eval_sort() - calculate/generate/sort moves for side to play.
* @pos: &position
*
* Generate positions for each move for player to move.
* For each of them generate opponents moves, calculate eval, and sort the moves list.
*/
void moves_gen_eval_sort(pos_t *pos)
{
move_t *move;
pos_t *newpos;
moves_gen_all(pos);
list_for_each_entry(move, &pos->moves[pos->turn], list) {
newpos = move_do(pos, move);
move->pos = newpos;
//move_print(0, move, 0);
move->eval_simple = eval_simple(newpos);
newpos->eval_simple = move->eval_simple;
}
moves_sort(pos);
//moves_print(pos, 0);
}
/**
* moves_gen_all() - calculate all moves, and generate moves for side to play.
* @pos: &position
*
* Compute pseudo moves for both sides, and generate moves for player to move.
*/
void moves_gen_all(pos_t *pos)
{
//log_f(1, "turn=%d opponent=%d\n", pos->turn, OPPONENT(pos->turn));
if (!pos->moves_generated) {
if (!pos->moves_counted) {}
moves_gen(pos, OPPONENT(pos->turn), false, false);
moves_gen(pos, pos->turn, true, true);
if (!pos->moves_counted)
moves_gen_king_moves(pos, OPPONENT(pos->turn), false);
pos->moves_counted = true;
pos->moves_generated = true;
}
}
/**
* moves_gen_all_nomoves() - calculate number of moves for each player.
* @pos: &position
*/
void moves_gen_all_nomoves(pos_t *pos)
{
//log_f(1, "turn=%d opponent=%d\n", pos->turn, OPPONENT(pos->turn));
if (!pos->moves_counted) {
moves_gen(pos, OPPONENT(pos->turn), false, false);
moves_gen(pos, pos->turn, false, true);
moves_gen_king_moves(pos, OPPONENT(pos->turn), false);
pos->moves_counted = true;
}
}
/**
* move_do() - execute move in a duplicated position.
* @pos: &pos_t struct on which move will be applied
* @move: &move_t struct to apply
*
* @return: &new position
*/
pos_t *move_do(pos_t *pos, move_t *move)
{
# ifdef DEBUG_MOVE
//log(1, "new move: ");
//move_print(0, move, M_PR_NL | M_PR_LONG);
# endif
pos_t *new = pos_dup(pos);
piece_t piece = PIECE(move->piece), newpiece = piece, captured = move->capture;
int color = COLOR(move->piece);
square_t from = move->from, to = move->to;
u64 bb_from = SQ88_2_BB(from), bb_to = SQ88_2_BB(to);
if (move->capture || piece == PAWN) /* 50 moves */
new->clock_50 = 0;
else
new->clock_50++;
if (move->flags & M_CAPTURE) { /* capture */
if (move->flags & M_EN_PASSANT) {
uchar ep_file = F88(pos->en_passant);
square_t ep_grab = color == WHITE ? SQ88(ep_file, 4): SQ88(ep_file, 3);
u64 bb_ep_grab = SQ88_2_BB(ep_grab);
log_f(5, "en-passant=%d,%d\n", ep_file, color == WHITE ? 4 : 3);
piece_del(&new->board[ep_grab].s_piece->list);
new->board[ep_grab].piece = 0;
new->occupied[OPPONENT(color)] &= ~bb_ep_grab;
new->bb[OPPONENT(color)][BB_PAWN] &= ~bb_ep_grab;
} else {
piece_del(&new->board[to].s_piece->list);
new->board[to].piece = 0;
new->occupied[OPPONENT(color)] &= ~bb_to;
new->bb[OPPONENT(color)][PIECETOBB(captured)] &= ~bb_to;
}
} else if (move->flags & M_CASTLE_Q) {
uchar row = R88(from);
square_t rook_from = SQ88(0, row);
square_t rook_to = SQ88(3, row);
u64 bb_rook_from = SQ88_2_BB(rook_from);
u64 bb_rook_to = SQ88_2_BB(rook_to);
new->board[rook_to] = new->board[rook_from];
new->board[rook_to].s_piece->square = rook_to;
new->occupied[color] &= ~bb_rook_from;
new->occupied[color] |= bb_rook_to;
new->bb[color][PIECETOBB(BB_ROOK)] &= ~bb_rook_from;
new->bb[color][PIECETOBB(BB_ROOK)] |= bb_rook_to;
new->board[rook_from].piece = 0;
new->board[rook_from].s_piece = NULL;
//new->castle &= color == WHITE? ~CASTLE_W: ~CASTLE_B;
} else if (move->flags & M_CASTLE_K) {
uchar row = R88(from);
square_t rook_from = SQ88(7, row);
square_t rook_to = SQ88(5, row);
u64 bb_rook_from = SQ88_2_BB(rook_from);
u64 bb_rook_to = SQ88_2_BB(rook_to);
new->board[rook_to] = new->board[rook_from];
new->board[rook_to].s_piece->square = rook_to;
new->occupied[color] &= ~bb_rook_from;
new->occupied[color] |= bb_rook_to;
new->bb[color][PIECETOBB(BB_ROOK)] &= ~bb_rook_from;
new->bb[color][PIECETOBB(BB_ROOK)] |= bb_rook_to;
new->board[rook_from].piece = 0;
new->board[rook_from].s_piece = NULL;
// new->castle &= color == WHITE? ~CASTLE_W: ~CASTLE_B;
}
new->board[to] = new->board[from];
/* fix dest square */
new->board[to].s_piece->square = to;
if (move->flags & M_PROMOTION) {
log_f(5, "promotion to %s\n", P_SYM(move->promotion));
log_f(5, "newpiece=%#x p=%#x\n", move->promotion, PIECE(move->promotion));
newpiece = PIECE(move->promotion);
new->board[to].piece = move->promotion;
new->board[to].s_piece->piece = move->promotion;
}
/* replace old occupied bitboard by new one */
new->occupied[color] &= ~bb_from;
new->occupied[color] |= bb_to;
new->bb[color][PIECETOBB(piece)] &= ~bb_from;
new->bb[color][PIECETOBB(newpiece)] |= bb_to;
if (move->flags & M_PROMOTION) {
log_f(5, "promotion color=%d bbpiece=%d\n", color, PIECETOBB(newpiece));
//bitboard_print(new->bb[color][PIECETOBB(newpiece)]);
}
/* set en_passant */
new->en_passant = 0;
if (piece == PAWN) {
if (R88(from) == 1 && R88(to) == 3)
pos->en_passant = SQ88(F88(from), 2);
else if (R88(from) == 6 && R88(to) == 4)
pos->en_passant = SQ88(F88(from), 5);
}
/* always make "from" square empty */
new->board[from].piece = 0;
new->board[from].s_piece = NULL;
//printf("old turn=%d ", color);
//printf("new turn=%d\n", new->turn);
//fflush(stdout);
/* adjust castling flags */
if ((bb_from | bb_to) & E1bb)
new->castle &= ~(CASTLE_WQ | CASTLE_WK);
else if ((bb_from | bb_to) & A1bb)
new->castle &= ~CASTLE_WQ;
else if ((bb_from | bb_to) & H1bb)
new->castle &= ~CASTLE_WK;
if ((bb_from | bb_to) & E8bb)
new->castle &= ~(CASTLE_BQ | CASTLE_BK);
else if ((bb_from | bb_to) & A8bb)
new->castle &= ~CASTLE_BQ;
else if ((bb_from | bb_to) & H8bb)
new->castle &= ~CASTLE_BK;
SET_COLOR(new->turn, OPPONENT(color)); /* pos color */
return new;
}
void move_undo(pos_t *pos, __unused move_t *move)
{
pos_del(pos);
}

View File

@@ -0,0 +1,79 @@
/* move.h - move management.
*
* Copyright (C) 2021 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#ifndef MOVE_H
#define MOVE_H
#include "chessdefs.h"
#include "position.h"
#include "pool.h"
#include "piece.h"
/* move flags
*/
typedef unsigned char move_flags_t;
#define M_NORMAL 0x00
#define M_CHECK 0x01 /* unsure if we know */
#define M_CAPTURE 0x02
#define M_EN_PASSANT 0x04
#define M_PROMOTION 0x08
#define M_CASTLE_K 0x10
#define M_CASTLE_Q 0x20
/* moves_print flags
*/
#define M_PR_CAPT 0x01
#define M_PR_NCAPT 0x02
#define M_PR_NUM 0x04
#define M_PR_NL 0x08
#define M_PR_EVAL 0x20 /* separate captures */
#define M_PR_SEPARATE 0x40 /* separate captures */
#define M_PR_LONG 0x80
typedef struct move_s {
piece_t piece;
square_t from, to;
piece_t capture; /* captured piece */
piece_t promotion; /* promoted piece */
move_flags_t flags;
eval_t negamax;
eval_t eval;
eval_t eval_simple;
pos_t *pos;
struct list_head list; /* next move */
} move_t;
pool_t *moves_pool_init();
void moves_pool_stats();
int move_print(int movenum, move_t *move, move_flags_t flags);
void moves_print(pos_t *move, move_flags_t flags);
void move_del(struct list_head *ptr);
int moves_del(pos_t *pos);
int pseudo_moves_castle(pos_t *pos, bool color, bool doit, bool do_king);
int pseudo_moves_gen(pos_t *pos, piece_list_t *piece, bool doit, bool do_king);
int pseudo_moves_pawn(pos_t *pos, piece_list_t *piece, bool doit);
int moves_gen(pos_t *pos, bool color, bool doit, bool do_king);
int moves_gen_king_moves(pos_t *pos, bool color, bool doit);
void moves_sort(pos_t *pos);
void moves_gen_eval_sort(pos_t *pos);
void moves_gen_all(pos_t *pos);
void moves_gen_all_nomoves(pos_t *pos);
pos_t *move_do(pos_t *pos, move_t *move);
void move_undo(pos_t *pos, move_t *move);
#endif /* MOVE_H */

View File

@@ -0,0 +1,118 @@
/* piece.c - piece list management.
*
* Copyright (C) 2021 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#include <malloc.h>
#include <ctype.h>
#include <debug.h>
#include <pool.h>
#include <list.h>
#include "chessdefs.h"
#include "piece.h"
#include "board.h"
#include "bitboard.h"
#include "position.h"
static pool_t *pieces_pool;
struct piece_details piece_details[] = {
[E_EMPTY] = { ' ', ' ', " ", " ", "", 0 },
[E_PAWN] = { 'P', 'p', "", "", "Pawn", PAWN_VALUE },
[E_KNIGHT] = { 'N', 'n', "", "", "Knight", KNIGHT_VALUE },
[E_BISHOP] = { 'B', 'b', "", "", "Bishop", BISHOP_VALUE },
[E_ROOK] = { 'R', 'r', "", "", "Rook", ROOK_VALUE },
[E_QUEEN] = { 'Q', 'q', "", "", "Queen", QUEEN_VALUE },
[E_KING] = { 'K', 'k', "", "", "King", KING_VALUE }
};
void piece_list_print(struct list_head *list)
{
struct list_head *p_cur, *tmp;
piece_list_t *piece;
list_for_each_safe(p_cur, tmp, list) {
piece = list_entry(p_cur, piece_list_t, list);
printf("%s%c%c ", P_SYM(piece->piece),
FILE2C(F88(piece->square)),
RANK2C(R88(piece->square)));
}
printf("\n");
}
pool_t *piece_pool_init()
{
if (!pieces_pool)
pieces_pool = pool_create("pieces", 128, sizeof(piece_list_t));
return pieces_pool;
}
void piece_pool_stats()
{
if (pieces_pool)
pool_stats(pieces_pool);
}
piece_list_t *piece_add(pos_t *pos, piece_t piece, square_t square)
{
piece_list_t *new;
short color = COLOR(piece);
# ifdef DEBUG_PIECE
log_f(3, "piece=%02x square=%02x\n", piece, square);
log_f(5, "Adding %s %s on %c%c\n", color? "Black": "White",
P_NAME(piece), FILE2C(F88(square)), RANK2C(R88(square)));
# endif
if ((new = pool_get(pieces_pool))) {
/* first piece is always king */
if (PIECE(piece) == KING)
list_add(&new->list, &pos->pieces[color]);
else
list_add_tail(&new->list, &pos->pieces[color]);
new->piece = piece;
new->square = square;
new->castle = 0;
new-> value = piece_details[PIECE(piece)].value;
}
return new;
}
void piece_del(struct list_head *ptr)
{
piece_list_t *piece = list_entry(ptr, piece_list_t, list);
# ifdef DEBUG_PIECE
log_f(3, "piece=%02x square=%02x\n", piece->piece, piece->square);
# endif
list_del(ptr);
pool_add(pieces_pool, piece);
return;
}
int pieces_del(pos_t *pos, short color)
{
struct list_head *p_cur, *tmp, *head;
int count = 0;
head = &pos->pieces[color];
list_for_each_safe(p_cur, tmp, head) {
piece_del(p_cur);
count++;
}
# ifdef DEBUG_PIECE
log_f(3, "color=%d removed=%d\n", color, count);
# endif
return count;
}

View File

@@ -0,0 +1,71 @@
/* piece.h - piece definitions.
*
* Copyright (C) 2021 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#ifndef PIECE_H
#define PIECE_H
#include <ctype.h>
#include "chessdefs.h"
#include "list.h"
#include "pool.h"
#define PIECE_DEFAULT_VALUE 0
/* initial default values */
#define PAWN_VALUE 100
#define KNIGHT_VALUE 300
#define BISHOP_VALUE 300
#define ROOK_VALUE 500
#define QUEEN_VALUE 900
#define KING_VALUE 20000
typedef struct piece_list_s {
piece_t piece;
square_t square;
short castle;
s64 value;
struct list_head list;
} piece_list_t;
/* some default values for pieces
*/
extern struct piece_details {
char abbrev_w; /* used for game notation */
char abbrev_b;
char *symbol_w;
char *symbol_b; /* used for game notation */
char *name;
s64 value;
} piece_details[];
#define P_NAME(p) piece_details[E_PIECE(p)].name
#define P_LETTER(p) piece_details[E_PIECE(p)].abbrev_w
#define P_SYM(p) piece_details[E_PIECE(p)].symbol_b
#define P_CSHORT(p) (IS_WHITE(p)? piece_details[E_PIECE(p)].abbrev_w: \
piece_details[E_PIECE(p)].abbrev_b)
#define P_CSYM(p) (IS_WHITE(p)? piece_details[E_PIECE(p)].symbol_w: \
piece_details[E_PIECE(p)].symbol_b)
#define P_VALUE(p) (piece_details[E_PIECE(p)].value)
/* use short name or symbol - no effect
*/
#define P_USE_UTF 1
void piece_list_print(struct list_head *list);
pool_t *piece_pool_init();
void piece_pool_stats();
piece_list_t *piece_add(pos_t *pos, piece_t piece, square_t square);
void piece_del(struct list_head *ptr);
int pieces_del(pos_t *pos, short color);
#endif

View File

@@ -0,0 +1,323 @@
/* position.c - position management.
*
* Copyright (C) 2021 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
#include "chessdefs.h"
#include "position.h"
#include "move.h"
#include "fen.h"
#include "piece.h"
#include "eval.h"
static pool_t *pos_pool;
#define BYTE_PRINT "%c%c%c%c%c%c%c%c"
#define BYTE2BIN(b) ((b) & 0x01 ? '1' : '0'), \
((b) & 0x02 ? '1' : '0'), \
((b) & 0x04 ? '1' : '0'), \
((b) & 0x08 ? '1' : '0'), \
((b) & 0x10 ? '1' : '0'), \
((b) & 0x20 ? '1' : '0'), \
((b) & 0x40 ? '1' : '0'), \
((b) & 0x80 ? '1' : '0')
inline void bitboard_print(bitboard_t bb)
{
int i;
printf("%#018lx\n", bb);
for (i=56; i>=0; i-=8)
printf("\t"BYTE_PRINT"\n",
BYTE2BIN(bb>>i));
}
inline void bitboard_print2(bitboard_t bb1, bitboard_t bb2)
{
int i;
printf("\tW: %#018lx\tB: %#018lx\n", bb1, bb2);
for (i=56; i>=0; i-=8)
printf("\t"BYTE_PRINT"\t\t"BYTE_PRINT"\n",
BYTE2BIN(bb1>>i),
BYTE2BIN(bb2>>i));
}
/**
* pos_pieces_print() - Print position pieces
* @pos: &position
*/
void pos_pieces_print(pos_t *pos)
{
printf("White pieces (%d): \t", popcount64(pos->occupied[WHITE]));
piece_list_print(&pos->pieces[WHITE]);
printf("Black pieces (%d): \t", popcount64(pos->occupied[BLACK]));
piece_list_print(&pos->pieces[BLACK]);
}
/**
* pos_bitboards_print() - Print position bitboards
* @pos: &position
*/
void pos_bitboards_print(pos_t *pos)
{
printf("Bitboards occupied :\n");
bitboard_print2(pos->occupied[WHITE], pos->occupied[BLACK]);
printf("Bitboards controlled :\n");
bitboard_print2(pos->controlled[WHITE], pos->controlled[BLACK]);
}
/**
* pos_print() - Print position on stdout.
* @pos: &position
*/
void pos_print(pos_t *pos)
{
int rank, file;
piece_t piece;
board_t *board = pos->board;
piece_list_t *wk = list_first_entry(&pos->pieces[WHITE], piece_list_t, list),
*bk = list_first_entry(&pos->pieces[BLACK], piece_list_t, list);
printf(" +---+---+---+---+---+---+---+---+\n");
for (rank = 7; rank >= 0; --rank) {
printf("%c |", rank + '1');
for (file = 0; file < 8; ++file) {
piece = board[SQ88(file, rank)].piece;
printf(" %s |", P_CSYM(piece));
}
printf("\n +---+---+---+---+---+---+---+---+\n");
}
printf(" A B C D E F G H\n\n");
printf("Turn: %s.\n", IS_WHITE(pos->turn) ? "white" : "black");
printf("Kings: W:%c%c B:%c%c\n",
FILE2C(F88(wk->square)),
RANK2C(R88(wk->square)),
FILE2C(F88(bk->square)),
RANK2C(R88(bk->square)));
printf("Possible en-passant: [%#x] ", pos->en_passant);
if (pos->en_passant == 0)
printf("None.\n");
else
printf("%d %d = %c%c\n",
F88(pos->en_passant),
R88(pos->en_passant),
FILE2C(F88(pos->en_passant)),
RANK2C(R88(pos->en_passant)));
printf("castle [%#x] : ", pos->castle);
if (pos->castle & CASTLE_WK)
printf("K");
if (pos->castle & CASTLE_WQ)
printf("Q");
if (pos->castle & CASTLE_BK)
printf("k");
if (pos->castle & CASTLE_BQ)
printf("q");
printf("\n50 half-moves-rule = %d\n", pos->clock_50);
printf("Current move = %d\n", pos->curmove);
printf("Squares controlled: W:%d B:%d\n", popcount64(pos->controlled[WHITE]),
popcount64(pos->controlled[BLACK]));
printf("Mobility: W:%u B:%u\n", pos->mobility[WHITE],
pos->mobility[BLACK]);
}
/**
* pos_check() - extensive position consistenci check.
* @pos: &position
*/
void pos_check(pos_t *pos)
{
int rank, file;
piece_t piece;
board_t *board = pos->board;
/* check that board and bitboard reflect same information */
for (rank = 7; rank >= 0; --rank) {
for (file = 0; file < 8; ++file) {
piece_list_t *ppiece;
printf("checking %c%c ", file+'a', rank+'1');
piece = board[SQ88(file, rank)].piece;
ppiece= board[SQ88(file, rank)].s_piece;
printf("piece=%s ", P_CSYM(piece));
if (ppiece)
printf("ppiece=%s/sq=%#x ", P_CSYM(ppiece->piece), ppiece->square);
switch(PIECE(piece)) {
case PAWN:
printf("pawn" );
break;
case KNIGHT:
printf("knight ");
break;
case BISHOP:
printf("bishop ");
break;
case ROOK:
printf("rook ");
break;
case QUEEN:
printf("queen ");
break;
case KING:
printf("king ");
break;
}
printf("\n");
}
}
}
pos_t *pos_clear(pos_t *pos)
{
int file, rank;
board_t *board = pos->board;
for (file = 0; file < 8; ++file) {
for (rank = 0; rank < 8; ++rank) {
/*printf("file = %d rank = %d SQ88 = %#2x = %d addr=%p\n", file, rank,
SQ88(file, rank), SQ88(file, rank),
&board[SQ88(file, rank)].piece);
*/
board[SQ88(file, rank)].piece = EMPTY;
}
}
SET_WHITE(pos->turn);
pos->node_count = 0;
pos->castle = 0;
pos->clock_50 = 0;
pos->curmove = 0;
pos->eval = 0;
pos->en_passant = 0;
pos->occupied[WHITE] = 0;
pos->occupied[BLACK] = 0;
for (int color=0; color<2; ++color)
for (int piece = BB_ALL; piece < BB_END; ++piece)
pos->bb[color][piece] = 0;
pos->controlled[WHITE] = 0;
pos->controlled[BLACK] = 0;
pos->mobility[WHITE] = 0;
pos->mobility[BLACK] = 0;
pos->moves_generated = false;
pos->moves_counted = false;
/* remove pieces / moves */
pieces_del(pos, WHITE);
pieces_del(pos, BLACK);
moves_del(pos);
return pos;
}
/**
* pos_del() - delete a position.
* @pos: &position.
*/
void pos_del(pos_t *pos)
{
pieces_del(pos, WHITE);
pieces_del(pos, BLACK);
moves_del(pos);
pool_add(pos_pool, pos);
}
pos_t *pos_startpos(pos_t *pos)
{
static char *startfen="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
return fen2pos(pos, startfen);
}
pos_t *pos_get()
{
pos_t *pos = pool_get(pos_pool);
if (pos) {
INIT_LIST_HEAD(&pos->pieces[WHITE]);
INIT_LIST_HEAD(&pos->pieces[BLACK]);
INIT_LIST_HEAD(&pos->moves[WHITE]);
INIT_LIST_HEAD(&pos->moves[BLACK]);
pos_clear(pos);
} else {
fprintf(stderr, "zobaaa\n");
}
return pos;
}
/**
* pos_dup() - duplicate a position.
* @pos: &position to duplicate.
*
* New position is the same as source one (with duplicated pieces list),
* except:
* - moves list is empty
* - bestmove is NULL
* - nodecount is set to zero
* - eval is set to EVAL_INVALID
* - moves_generated ans moves_counted are unset
* - check is set to zero
*
* @return: The new position.
*
* TODO: merge with pos_get - NULL for init, non null for duplicate
*/
pos_t *pos_dup(pos_t *pos)
{
struct list_head *p_cur, *piece_list;
piece_list_t *oldpiece;
board_t *board;
pos_t *new = pool_get(pos_pool);
if (new) {
board = new->board;
*new = *pos;
for (int color = 0; color < 2; ++color) {
INIT_LIST_HEAD(&new->pieces[color]);
INIT_LIST_HEAD(&new->moves[color]);
/* duplicate piece list */
piece_list = &pos->pieces[color]; /* white/black piece list */
list_for_each(p_cur, piece_list) {
oldpiece = list_entry(p_cur, piece_list_t, list);
board[oldpiece->square].s_piece =
piece_add(new, oldpiece->piece, oldpiece->square);
}
}
new->bestmove = NULL;
new->node_count = 0;
new->eval = EVAL_INVALID;
new->moves_generated = false;
new->moves_counted = false;
new->check[WHITE] = new->check[BLACK] = 0;
}
return new;
}
pool_t *pos_pool_init()
{
if (!pos_pool)
pos_pool = pool_create("positions", 128, sizeof(pos_t));
return pos_pool;
}
void pos_pool_stats()
{
if (pos_pool)
pool_stats(pos_pool);
}

View File

@@ -0,0 +1,66 @@
/* position.h - position management definitions.
*
* Copyright (C) 2021 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#ifndef POSITION_H
#define POSITION_H
#include <stdint.h>
#include "pool.h"
#include "list.h"
#include "bitops.h"
#include "board.h"
#include "chessdefs.h"
typedef struct pos_s {
u64 node_count; /* evaluated nodes */
piece_t turn; /* we use only color bit */
castle_t castle;
u16 clock_50;
u16 curmove;
eval_t eval;
int check[2];
int eval_simple_phase;
eval_t eval_simple;
move_t *bestmove;
bool moves_generated;
bool moves_counted;
board_t board[BOARDSIZE];
square_t en_passant;
bitboard_t bb[2][BB_END]; /* use: pieces[BLACK][BB_PAWN] */
bitboard_t occupied[2]; /* OR of bb[COLOR][x] */
bitboard_t controlled[2];
u16 mobility[2];
struct list_head pieces[2]; /* pieces list, King is first */
struct list_head moves[2];
} pos_t;
void bitboard_print(bitboard_t bb);
void bitboard_print2(bitboard_t bb1, bitboard_t bb2);
void pos_pieces_print(pos_t *pos);
void pos_bitboards_print(pos_t *pos);
void pos_print(pos_t *pos);
pos_t *pos_clear(pos_t *pos);
void pos_del(pos_t *pos);
pos_t *pos_startpos(pos_t *pos);
pos_t *pos_create();
pool_t *pos_pool_init();
void pos_pool_stats();
pos_t *pos_get();
pos_t *pos_dup(pos_t *pos);
void pos_check(pos_t *pos);
#endif /* POSITION_H */

View File

@@ -0,0 +1,237 @@
/* search.c - search good moves.
*
* Copyright (C) 2023 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#include <br.h>
#include <list.h>
#include "debug.h"
#include "move.h"
#include "eval.h"
#include "search.h"
/**
* negamax() - search position negamax.
* @pos: &position to search
* @depth: Wanted depth.
* @color: 1 for white, -1 for black.
*
* Calculate the negamax value of @pos. This is an extensive search, with
* absolutely no cutoff.
*
* @return: The @pos negamax evaluation.
*/
eval_t negamax(pos_t *pos, int depth, int color)
{
move_t *move;
pos_t *newpos;
eval_t best = EVAL_MIN, score;
pos->node_count++;
if (depth == 0) {
moves_gen_all_nomoves(pos);
score = eval(pos) * color;
return score;
}
moves_gen_all(pos);
list_for_each_entry(move, &pos->moves[pos->turn], list) {
newpos = move_do(pos, move);
score = -negamax(newpos, depth - 1, -color);
pos->node_count += newpos->node_count;
move->negamax = score;
if (score > best) {
best = score;
pos->bestmove = move;
}
move_undo(newpos, move);
}
return best;
}
/**
* pvs() - Principal Variation Search.
* @pos: &position to search
* @depth: wanted depth.
* @alpha: alpha value.
* @beta: beta value.
* @color: 1 for white, -1 for black.
*
* Calculate the PVS value of @pos.
* See https://en.wikipedia.org/wiki/Principal_variation_search
*
* Moves list should be first generated and evaluated/sorted.
*
* @return: The @pos PVS evaluation.
*/
eval_t pvs(pos_t *pos, int depth, int alpha, int beta, int color)
{
move_t *move;
pos_t *newpos;
eval_t score = EVAL_INVALID;
bool firstchild = true;
pos->node_count++;
if (depth == 0) {
//return quiesce(p, alpha, beta); /* leaf node */
moves_gen_all_nomoves(pos);
score = eval(pos) * color;
log_f(2, "Terminal: depth=%d ", depth);
log_f(2, "score=%d alpha=%d beta=%d\n", score, alpha, beta);
return score;
}
moves_gen_all(pos);
//moves_print(pos, M_PR_EVAL);
/* do the full search for first child */
//move = list_first_entry_or_null(&pos->moves[pos->turn], move_t, list);
list_for_each_entry(move, &pos->moves[pos->turn], list) {
newpos = move_do(pos, move);
log(2, "%.*s", 5 - depth, " ");
if (firstchild) { /* first child */
score = -pvs(newpos, depth - 1, -beta, -alpha, -color);
log_f(2, "First child depth=%d move=", depth);
//move_print(0, move, 0);
log(2, "score=%d alpha=%d beta=%d\n", score, alpha, beta);
pos->bestmove = move;
} else {
/* search with a null window */
score = -pvs(newpos, depth - 1, -alpha - 1, -alpha, -color);
log_f(2, "Other child depth=%d move=", depth);
//move_print(0, move, 0);
log_f(2, "score=%d alpha=%d beta=%d ", score, alpha, beta);
/* for fail-soft: if (score > alpha && score < beta) */
if (score > alpha) {
/* if failed high, do a full re-search */
log_f(2, "doing full search.");
score = -pvs(newpos, depth - 1, -beta, -alpha, -color);
}
log(2, "\n");
}
pos->node_count += newpos->node_count;
move_undo(newpos, move);
if (score >= beta) { /* fail-hard hard beta cut-off */
log(2, "%.*s", 5 - depth, " ");
log_f(2, "depth=%d score=%d alpha=%d beta=%d beta cut-off.\n",
depth, score, alpha, beta);
return beta;
}
if (score > alpha) {
log(2, "%.*s", 5 - depth, " ");
log_f(2, "depth=%d setting new alpha from %d to %d\n",
depth, alpha, score);
alpha = score;
pos->bestmove = move;
}
move->pos = NULL;
move->negamax = score;
firstchild = false;
}
return alpha;
}
/*
* int negascout (pos_t *pos, int depth, int alpha, int beta )
* { /\* compute minimax value of position p *\/
* move_t *move;
* pos_t *newpos;
* eval_t best = EVAL_MIN, score;
*
* int a, b, t, i;
*
* if (depth == 0) {
* //return quiesce(p, alpha, beta); /\* leaf node *\/
* moves_gen_all_nomoves(pos);
* score = eval(pos) * color;
* return score;
* }
* moves_gen_all(pos);
* a = alpha;
* b = beta;
* list_for_each_entry(move, &pos->moves[pos->turn], list) {
* log(1, "%.*s", 5 - depth, " ");
* newpos = move_do(pos, move);
* // for ( i = 1; i <= w; i++ ) {
* t = -negascout (newpos, depth - 1, -b, -alpha);
* if ( (t > a) && (t < beta) && (i > 1) )
* t = -NegaScout ( p_i, -beta, -alpha ); /\* re-search *\/
* alpha = max( alpha, t );
* if ( alpha >= beta )
* return alpha; /\* cut-off *\/
* b = alpha + 1; /\* set new null window *\/
* }
* return alpha;
* }
*/
/*
* int quiesce(pos_t *pos, int alpha, int beta)
* {
* int stand_pat = eval(pos);
*
* if( stand_pat >= beta )
* return beta;
* if( alpha < stand_pat )
* alpha = stand_pat;
*
* /\*
* * until( every_capture_has_been_examined ) {
* * MakeCapture();
* * score = -Quiesce( -beta, -alpha );
* * TakeBackMove();
* *
* * if( score >= beta )
* * return beta;
* * if( score > alpha )
* * alpha = score;
* * }
* *\/
* return alpha;
* }
*/
/**
* ab_negamax() - search position negamax with alpha-beta cutoff.
* @pos: &position to search
* @depth: Wanted depth.
* @color: 1 for white, -1 for black.
*
* Calculate the negamax value of @pos, with alpha-beta pruning.
*
* @return: The @pos negamax evaluation.
*/
/*int ab_negamax(pos_t *pos, int alpha, int beta, int depth)
{
move_t *move;
pos_t *newpos;
eval_t best = EVAL_MIN, score;
if(depth == 0) {
//return quiesce( alpha, beta );
moves_gen_all_nomoves(pos);
score = eval(pos) * color;
return score;
}
for ( all moves) {
score = -alphaBeta( -beta, -alpha, depthleft - 1 );
if( score >= beta )
return beta; // fail hard beta-cutoff
if( score > alpha )
alpha = score; // alpha acts like max in MiniMax
}
return alpha;
}
*/

View File

@@ -0,0 +1,22 @@
/* search.h - search for perfect move.
*
* Copyright (C) 2021 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#ifndef SEARCH_H
#define SEARCH_H
#include "position.h"
eval_t negamax(pos_t *pos, int depth, int color);
eval_t pvs(pos_t *pos, int depth, int alpha, int beta, int color);
#endif /* SEARCH_H */

44
src/util.c Normal file
View File

@@ -0,0 +1,44 @@
/* util.c - various util functions.
*
* Copyright (C) 2024 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#include <stdio.h>
#include <stdlib.h>
#include "util.h"
#include "bitboard.h"
/**
* bitboard_print_simple - print simple bitboard representation
* @bitboard: the bitboard
* @title: a string or NULL
*/
void raw_bitboard_print(const bitboard bitboard, const char *title)
{
if (title)
printf("%s\n", title);
for (rank r = RANK_8; r >= RANK_1; --r) {
printf("%d ", r);
for (file f = FILE_A; f <= FILE_H; ++f)
printf(" %c", bitboard & (BB(f, r)) ? 'X': '.');
printf(" A B C D E F G H\n");
}
printf(" \n");
return;
}
/*int main()
{
char *foo = safe_malloc(1000);
exit(0);
}
*/

60
src/util.h Normal file
View File

@@ -0,0 +1,60 @@
/* util.h - various util functions.
*
* Copyright (C) 2024 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
* You should have received a copy of the GNU General Public License along with this
* program. If not, see <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*
* SPDX-License-Identifier: GPL-3.0-or-later <https://spdx.org/licenses/GPL-3.0-or-later.html>
*
*/
#ifndef _UTIL_H
#define _UTIL_H
#include <stdio.h>
#include <stdlib.h>
#include "bug.h"
#include "chessdefs.h"
/*
#define bug_on(expr) do { \
if (unlikely(expr)) { \
fprintf(stderr, \
"** BUG IN %s[%s:%d]: assertion \"" #expr "\" failed.\n", \
__func__, __FILE__,__LINE__); \
abort(); \
} \
} while (0)
#define warn_on(expr) ({ \
int _ret = !!(expr); \
if (unlikely(_ret)) { \
fprintf(stderr, \
"** WARN ON %s[%s:%d]: assertion \"" #expr "\" failed.\n", \
__func__, __FILE__,__LINE__); \
} \
_ret; \
})
*/
#undef safe_malloc
#define safe_malloc(size) ({ \
void *_ret = malloc(size); \
bug_on(_ret == NULL); \
_ret; \
})
#undef safe_free
#define safe_free(ptr) do { \
bug_on(ptr == NULL); \
free(_ret); \
} while (0)
void raw_bitboard_print(const bitboard bitboard, const char *title);
#endif /* UTIL_H */

View File

@@ -1,20 +1,22 @@
#include "debug.h" #include "debug.h"
#include "pool.h" #include "pool.h"
#include "../src/position.h" #include "../src/position.h"
#include "../src/fen.h" #include "../src/fen.h"
int main(int ac, char**av) int main(int ac, char**av)
{ {
pos_t *pos; position *pos;
debug_init(5, stderr, true); debug_init(5, stderr, true);
piece_pool_init();
pos_pool_init(); pos_pool_init();
pos = pos_get(); pos = pos_new();
if (ac == 1) { if (ac == 1) {
pos_startpos(pos); startpos(pos);
} else { } else {
fen2pos(pos, av[1]); fen2pos(pos, av[1]);
} }
pos_print(pos); pos_print(pos);
printf("fen=[%s]\n", pos2fen(pos, NULL));
} }

0
util.c Normal file
View File