83 Commits

Author SHA1 Message Date
926dfa0765 untabify Makefile, cosmetic change in pos_set_checkers_pinners_blockers() 2024-04-10 17:12:20 +02:00
374116b1e7 simplify pos_set_checkers_pinners_blockers() (cont'd) 2024-04-10 15:59:24 +02:00
9b5c2253b1 Makefile: add -ginline-points 2024-04-10 13:02:23 +02:00
e301e6c726 bug fix in perft() - stupid initialization ! 2024-04-10 12:57:39 +02:00
e78eae21e6 cleanup move_do() 2024-04-10 12:57:08 +02:00
711306c92a simplify/improve pos_set_checkers_pinners_blockers() 2024-04-10 12:54:47 +02:00
660722fadc cleanup 2024-04-10 12:53:31 +02:00
e8240c6cab move_make_promotions(), clean move_do(), pos_gen_pseudomoves() 2024-04-09 08:15:43 +02:00
eb590f1438 bug fix, wrong perft recursion ! 2024-04-09 08:11:31 +02:00
f2ce20a504 add bb_pawn_attacks[][], bb_shift() 2024-04-09 08:10:53 +02:00
027aa2c132 bb: bb_{first_bb,next,multiple{}, chessdefs: relative sq diffs 2024-04-04 10:03:43 +02:00
30af886594 comment 2024-04-02 21:18:01 +02:00
afecbeb955 movegen-test: add set_checkers_pinners_blockers call 2024-04-02 20:40:44 +02:00
05748e19ab Makefile: build static 2024-04-02 20:38:50 +02:00
4816b4a53a experiment: add pos_set_checkers_pinners_blockers() 2024-03-30 18:45:13 +01:00
96744cea20 perft-test: option to run perft/perft2/both 2024-03-29 10:00:01 +01:00
24207583d1 perft2: is_in_check() before recursion 2024-03-29 09:59:14 +01:00
92d6909546 update (C) notice 2024-03-28 10:37:52 +01:00
85ae4a2230 better comments on perft() and perft2() 2024-03-28 09:41:39 +01:00
ad8a9609ce misc.c: add a few basic clock functions 2024-03-28 08:33:27 +01:00
ad704c216b Merge branch 'perft': perft() and perft2() - see comments.
perft: normal "get_next_legal()" before movegen
perft2: is_in_check() after movegen
2024-03-27 18:09:25 +01:00
26b9a5b58a brchess func calls changes, always run perft() & perft2() 2024-03-27 12:53:42 +01:00
65fe74c9c5 movegen: don't separate promotions, perft: loop uses next_legal() 2024-03-27 12:52:39 +01:00
9b2f5ff751 move_{do,undo}: do not save/restore pos state 2024-03-27 12:42:45 +01:00
edcc87be5a a few more perft debug tests 2024-03-27 12:41:38 +01:00
09afd98971 fen2pos: no more pos_checkers etc... position.c: pos_check -> pos_ok (bool) 2024-03-27 12:40:16 +01:00
08ba989170 is_legal: fix check+pinned and knight check; perft-test + perft2() 2024-03-26 17:43:59 +01:00
7637bdad10 attack.c: sq_is_attacked() and is_in_check() 2024-03-26 17:34:11 +01:00
70d6c23c00 position add: pos_set_pinners_blockers() 2024-03-26 17:31:44 +01:00
aaeab03089 revert captured in position before change to move struct 2024-03-23 19:49:35 +01:00
ce2e0e8459 add forgotten changes in bitboard-switch branch (git is so... difficult) 2024-03-23 17:41:15 +01:00
d0279125ae move_{do,undo}: FIX forgotten king[] update, add few bug_on() 2024-03-23 17:37:40 +01:00
798047b84d Merge branch 'bitboard-switch' 2024-03-23 17:26:26 +01:00
856e3e52da add movedo-test 2024-03-21 07:00:20 +01:00
51a348c1e4 add pos_cmp (as a debug check after move_{do,undo}) 2024-03-21 06:58:56 +01:00
51c35e21f4 castling: lowercase macros, nove-{do,undo}: full (untested) version 2024-03-20 10:00:07 +01:00
3a06407d5a move: exclusive M_CAPTURE / M_EN_PASSANT 2024-03-20 09:58:42 +01:00
ae6328ce26 position: add captured piece 2024-03-20 09:57:10 +01:00
08064dd1a1 start bb-based move_do 2024-03-19 18:30:31 +01:00
49705bc707 rename few macros to lowercase, add M_DPUSH move flag 2024-03-19 18:30:10 +01:00
8527c3dee1 movegen: separate all captures (easier later handling) 2024-03-18 10:21:25 +01:00
dc916f5c56 move.h: revert flags to direct bit mask 2024-03-18 09:15:16 +01:00
748953a767 move-gen: separate pawn capture from en-passant (easier later testing) 2024-03-18 09:13:51 +01:00
9c2e76442d add a struct_group for move_do() irreversible changes 2024-03-17 17:34:21 +01:00
49302c7a60 lowercase move flags macros 2024-03-17 17:33:48 +01:00
db38b507ff add gmon.out 2024-03-17 17:30:51 +01:00
9d40a53aea simplify pos_next_legal() 2024-03-16 12:14:59 +01:00
260d8d34bd move.h: simplify flags. movegen.c: add pos_next_legal() 2024-03-16 10:06:55 +01:00
037d49e4ca move-do: copy from pre-bitboard version 2024-03-15 10:53:26 +01:00
4eb620a873 add occ param in sq_attackers() 2024-03-15 09:14:10 +01:00
92dcb1e778 fix king move in pos_is_legal() 2024-03-15 09:12:42 +01:00
c8aea61529 pos_checkers(): add occ parameter 2024-03-15 09:11:28 +01:00
b3f0dd0534 add move_str() 2024-03-15 09:10:32 +01:00
0f06ccb8db simplify piece_details structure/functions (need to rewrite) 2024-03-15 09:08:49 +01:00
3e477f7442 movegen-test: add SF/uci promotion parsing 2024-03-15 09:07:02 +01:00
aba0113344 add piece-test 2024-03-15 09:04:44 +01:00
cc7d91ebfb default compile-command: make testing 2024-03-15 09:03:30 +01:00
17d1dc52f9 movegen: pseudo_is_legal() and pos_legalmoves() 2024-03-12 10:45:20 +01:00
cc3754ae00 add position blockers 2024-03-12 10:44:25 +01:00
08082faed3 moves_print() and move_sort_by_sq(): use movelist_t instead of pos_t 2024-03-12 10:42:24 +01:00
6ee4cd1642 cleanup 2024-03-11 16:12:45 +01:00
b7fdcca66d pos_check(): add adjacent kings test 2024-03-11 16:11:51 +01:00
890cb05296 add move_make_promote_capture and move_make_capture 2024-03-11 16:10:16 +01:00
301ca24783 add funcs comments and const parameters 2024-03-11 16:07:12 +01:00
d81dca6e23 add sq_line array, bb_sq_aligned3, renamed sq_manh to sq_taxi 2024-03-11 16:04:45 +01:00
87e7695873 new pos/bb funcs, legal(), better castling gen, etc. [see commit details]
- new sq_pinners
- new pseudo_is_legal() (unfinished)
- improve castling pseudo move gen

- more position and lower level bitboard helper funcs:
  - pos_{_occ,between_occ,between_count,pinners}
  - bb_{rank,file,rel_rank,_sq_aligned,_sq_between)
- rename some bitboard globals
- replace bb ranks/files enums with defines (issue with clang)
  -> Need to find a way to use enum safely
- tests:
  - add common-test.h
  - new attack-test.c
2024-03-10 10:58:14 +01:00
b351d198b8 sq_attackers() + others (see dedails). Ready for move do/undo ?
- add many "const" in func parameters
- attack.c: sq_attackers()
- move print_board_raw from position.c to to board.c
- move some fen_check() tests to pos_check()
- add REL_RANK() macro. TODO: add one more for bitboards
- fen.c: more tests for FEN validity
- position.c: add pos_checkers() and pos_check()
- tests: add common-test.h (for shared FEN positions access)
2024-03-04 21:34:29 +01:00
a499893f32 add board_print, board_print_mask 2024-03-02 07:10:23 +01:00
dc6ceb3407 Makefile cleanup 2024-02-29 10:05:44 +01:00
beaa7bfcbc movegen: start to fix early bugs (wrong masks, etc...) 2024-02-29 09:33:18 +01:00
be32bae86a strengthen FEN parsing 2024-02-29 09:31:40 +01:00
8f0840fc2f add functions documentation - should be done earlier !! 2024-02-29 09:31:00 +01:00
6d412e7fce add move.c from pre-bitboard version 2024-02-29 09:27:29 +01:00
7859228f89 movegen-test: add fen test array 2024-02-29 09:19:24 +01:00
a8e3ec70f8 add square attackers fct 2024-02-29 09:18:19 +01:00
f1a081a7b6 add pawn movegen (untested) 2024-02-26 19:15:42 +01:00
ca4e274957 add in-between masks (with/without dest square. TODO: keep only one !) 2024-02-26 19:14:20 +01:00
e50d9a73e6 Makefile: cleanup 2024-02-26 19:11:46 +01:00
ccc0dfd2f6 temp commit for machine transfer 2024-02-22 09:37:02 +01:00
fa5c9bb8ab bitboard8_sprint -> bitboard_rank_sprint (temp, need BB+rank as input) 2024-02-22 09:29:10 +01:00
d00eab54e7 board.h: fix sq_make/sq_file 2024-02-22 09:13:12 +01:00
9c02a02c1e fen: add fen_test() 2024-02-22 09:11:25 +01:00
4d8f69e8c9 position: raw_board_print in octal, fix mask in pos_set_sq/pos_clr_sq 2024-02-22 08:35:26 +01:00
38 changed files with 4397 additions and 1813 deletions

View File

@@ -1,3 +1,3 @@
((nil . ((compile-command . (concat "make -C "
(vc-root-dir)
" -k -j2")))))
" -k -j2 testing")))))

2
.gitignore vendored
View File

@@ -4,6 +4,7 @@ vgcore.*
*.i
*.old
*.save
perf.data
/GPATH
/GRTAGS
/GTAGS
@@ -17,4 +18,5 @@ vgcore.*
/tmp/
/notused/
valgrind.out
gmon.out
compile_commands.json

199
Makefile
View File

@@ -1,6 +1,6 @@
# Makefile - GNU make only.
# Makefile - brchess Makefile, **GNU make only**
#
# Copyright (C) 2021-2023 Bruno Raoult ("br")
# Copyright (C) 2021-2024 Bruno Raoult ("br")
# Licensed under the GNU General Public License v3.0 or later.
# Some rights reserved. See COPYING.
#
@@ -12,6 +12,7 @@
SHELL := /bin/bash
CC := gcc
#CC := clang
LD := ld
BEAR := bear
TOUCH := touch
@@ -20,10 +21,11 @@ RMDIR := rmdir
MAKE := make
SRCDIR := ./src
INCDIR := ./src
INCDIR := ./src # used by ./test sources
OBJDIR := ./obj
BINDIR := ./bin
DEPDIR := ./dep
TSTDIR := ./test
BRLIB := ./brlib
BRINCDIR := $(BRLIB)/include
@@ -36,54 +38,97 @@ SRC := $(wildcard $(SRCDIR)/*.c) # project sources
SRC_FN := $(notdir $(SRC)) # source basename
OBJ := $(addprefix $(OBJDIR)/,$(SRC_FN:.c=.o))
LIB := br_$(shell uname -m) # library name
TSTSRC := $(wildcard $(TSTDIR)/*.c)
DEP_FN := $(SRC_FN) $(LIBSRC_FN)
LIB := br_$(shell uname -m) # library name
LIBS := $(strip -l$(LIB) -lreadline)
DEP_FN := $(SRC_FN)
DEP := $(addprefix $(DEPDIR)/,$(DEP_FN:.c=.d))
TARGET_FN := brchess
TARGET := $(addprefix $(BINDIR)/,$(TARGET_FN))
LDFLAGS := -L$(BRLIBDIR)
LIBS := $(strip -l$(LIB) -lreadline)
ASMFILES := $(SRC:.c=.s) $(TSTSRC:.c=.s)
CPPFILES := $(SRC:.c=.i) $(TSTSRC:.c=.i)
##################################### pre-processor flags
CPPFLAGS := -I$(BRINCDIR) -I$(INCDIR)
CPPFLAGS += -DBUG_ON
CPPFLAGS += -DWARN_ON
CPPFLAGS += -NDEBUG #
#CPPFLAGS += -DDEBUG # global
CPPFLAGS += -DDEBUG_DEBUG # enable log() functions
#CPPFLAGS += -DDEBUG_DEBUG_C # enable verbose log() settings
CPPFLAGS += -DDEBUG_POOL # memory pools management
#CPPFLAGS += -DDEBUG_FEN # FEN decoding
CPPFLAGS += -DDEBUG_MOVE # move generation
CPPFLAGS += -DDEBUG_EVAL # eval functions
CPPFLAGS += -DDEBUG_PIECE # piece list management
CPPFLAGS += -DDEBUG_SEARCH # move search
CPPFLAGS += -DNDEBUG # assert
CPPFLAGS += -DBUG_ON # brlib bug.h
CPPFLAGS += -DWARN_ON # brlib bug.h
#CPPFLAGS += -DDEBUG # global - unused
#CPPFLAGS += -DDEBUG_DEBUG # enable log() functions
#CPPFLAGS += -DDEBUG_DEBUG_C # enable log() settings
#CPPFLAGS += -DDEBUG_POOL # memory pools management
#CPPFLAGS += -DDEBUG_POS # position.c
#CPPFLAGS += -DDEBUG_MOVE # move generation
# fen.c
#CPPFLAGS += -DDEBUG_FEN # FEN decoding
# attack.c
#CPPFLAGS += -DDEBUG_ATTACK_ATTACKERS1 # sq_attackers details
CPPFLAGS += -DDEBUG_ATTACK_ATTACKERS # sq_attackers
CPPFLAGS += -DDEBUG_ATTACK_PINNERS # sq_pinners details
#CPPFLAGS += -DDEBUG_EVAL # eval functions
#CPPFLAGS += -DDEBUG_PIECE # piece list management
#CPPFLAGS += -DDEBUG_SEARCH # move search
CPPFLAGS += -DDIAGRAM_SYM # diagram with symbols
# remove extraneous spaces (due to spaces before comments)
CPPFLAGS := $(strip $(CPPFLAGS))
##################################### compiler flags
CFLAGS := -std=gnu11
CFLAGS += -O3
CFLAGS += -g
### dev OR release
# dev
# CFLAGS += -O1
CFLAGS += -g # symbols (gdb, perf, etc.)
CFLAGS += -ginline-points # inlined funcs debug info
# for gprof
#CFLAGS += -pg
# Next one may be useful for valgrind (when invalid instructions)
#CFLAGS += -mno-tbm
# release
CFLAGS += -Ofast
CFLAGS += -march=native
CFLAGS += -flto
CFLAGS += -Wall
CFLAGS += -Wextra
CFLAGS += -march=native
CFLAGS += -Wmissing-declarations
# for gprof
# CFLAGS += -pg
# Next one may be useful for valgrind (when invalid instructions)
# CFLAGS += -mno-tbm
CFLAGS := $(strip $(CFLAGS))
# development CFLAGS - unused - TODO
#DEV_CFLAGS := -O1
#DEV_CFLAGS += -g
# release CFLAGS - unused - TODO
#REL_CFLAGS := -Ofast
##################################### linker flags
LDFLAGS := --static
LDFLAGS += -L$(BRLIBDIR)
LDFLAGS += -flto
LDFLAGS := $(strip $(LDFLAGS))
##################################### archiver/dependency flags
ARFLAGS := rcs
DEPFLAGS = -MMD -MP -MF $(DEPDIR)/$*.d
DEPFLAGS = -MMD -MP -MF $(DEPDIR)/$*.d
##################################### archiver/dependency flags
ALL_CFLAGS = $(DEPFLAGS) $(CPPFLAGS) $(CFLAGS)
ALL_LDFLAGS = $(LDFLAGS) $(LIBS)
##################################### General targets
.PHONY: all compile clean cleanall
@@ -94,15 +139,14 @@ compile: brlib objs
libs: brlib
clean: cleandep cleanobj cleanbin
clean: cleandep cleanasmcpp cleanobj cleanbin
cleanall: clean cleandepdir cleanobjdir cleanallbrlib cleanbindir
##################################### cleaning functions
# rmfiles - deletes a list of files in a directory if they exist.
# rmfiles - delete a list of files if they exist.
# $(1): the directory
# $(2): the list of files to delete
# $(3): The string to include in action output - "cleaning X files."
# $(2): The string to include in action output - "cleaning X files."
# see: https://stackoverflow.com/questions/6783243/functions-in-makefiles
#
# Don't use wildcard like "$(DIR)/*.o", so we can control mismatches between
@@ -118,7 +162,7 @@ define rmfiles
fi
endef
# rmdir - deletes a directory if it exists.
# rmdir - delete a directory if it exists.
# $(1): the directory
# $(2): The string to include in action output - "removing X dir."
#
@@ -179,19 +223,18 @@ cleanobjdir: cleanobj
# "normal" ones, but do not imply to rebuild target.
$(OBJDIR)/%.o: $(SRCDIR)/%.c | $(OBJDIR) $(DEPDIR)
@echo compiling brchess module: $< "->" $@.
@$(CC) -c $(DEPFLAGS) $(CPPFLAGS) $(CFLAGS) $< -o $@
@$(CC) -c $(ALL_CFLAGS) $< -o $@
##################################### brlib libraries
.PHONY: cleanbrlib cleanallbrlib libs brlib
.PHONY: cleanbrlib cleanallbrlib brlib
cleanbrlib:
$(MAKE) -C $(BRLIB) clean
@#$(call rmfiles,$(DLIB) $(SLIB),library)
cleanallbrlib:
$(MAKE) -C $(BRLIB) cleanall
brlib: libs
brlib:
$(MAKE) -C $(BRLIB) libs
##################################### brchess binaries
@@ -205,19 +248,22 @@ cleanbin:
cleanbindir:
$(call rmdir,$(BINDIR),binaries)
# We don't use static lib, but we could build it here
#$(TARGET): $(DLIB) $(OBJ) | $(BINDIR) $(SLIB)
$(TARGET): libs $(OBJ) | $(BINDIR) $(SLIB)
@echo generating $@ executable.
$(TARGET): libs $(OBJ) | $(BINDIR)
@echo generating $@.
$(CC) $(LDFLAGS) $(OBJ) $(LIBS) -o $@
##################################### pre-processed (.i) and assembler (.s) output
.PHONY: cleanasmcpp
cleanasmcpp:
@$(call rmfiles,$(ASMFILES) $(CPPFILES),asm and pre-processed)
%.i: %.c
@echo generating $@
@echo "generating $@ (cpp processed)."
@$(CC) -E $(CPPFLAGS) $(CFLAGS) $< -o $@
%.s: %.c
@echo generating $@
@echo "generating $@ (asm)."
@$(CC) -S -fverbose-asm $(CPPFLAGS) $(CFLAGS) $< -o $@
##################################### LSP (ccls)
@@ -230,17 +276,13 @@ $(CCLSROOT):
@$(TOUCH) $@
# generate compile_commands.json.
# Need to add includes and Makefile dependencies.
# TODO: add Makefile dependencies.
# also, if cclsfile is newer than sources, no need to clean objects file
# (and to run bear).
# maybe run cleanobj cleanlibobj in commands ?
$(CCLSFILE): cleanobj cleanbrlib $(SRC) $(LIBSRC) | $(CCLSROOT)
$(CCLSFILE): cleanobj cleanbrlib libs | $(CCLSROOT)
@echo "Generating ccls compile commands file ($@)."
@$(BEAR) -- $(MAKE) compile
#.PHONY: bear
#bear: cleanobj cleanlibobj Makefile | $(CCLSROOT)
# @$(BEAR) -- make compile
@$(BEAR) -- $(MAKE) testing
##################################### valgrind (mem check)
.PHONY: memcheck
@@ -258,20 +300,63 @@ memcheck: targets
@$(VALGRIND) $(VALGRINDFLAGS) $(BINDIR)/brchess
##################################### test binaries
TEST = bin/fen-test bin/bitboard-test
.PHONY: testing test
FENTESTOBJS = obj/fen.o obj/position.o obj/piece.o obj/util.o obj/bitboard.o
BITBOARDOBJS = obj/position.o obj/piece.o obj/bitboard.o obj/fen.o \
obj/hyperbola-quintessence.o
TEST := piece-test fen-test bitboard-test movegen-test attack-test
TEST += movedo-test perft-test
PIECE_OBJS := piece.o
FEN_OBJS := $(PIECE_OBJS) fen.o position.o bitboard.o board.o \
hyperbola-quintessence.o attack.o
BB_OBJS := $(FEN_OBJS)
MOVEGEN_OBJS := $(BB_OBJS) move.o move-gen.o
ATTACK_OBJS := $(MOVEGEN_OBJS)
MOVEDO_OBJS := $(ATTACK_OBJS) move-do.o
PERFT_OBJS := $(MOVEDO_OBJS) search.o misc.o
TEST := $(addprefix $(BINDIR)/,$(TEST))
PIECE_OBJS := $(addprefix $(OBJDIR)/,$(PIECE_OBJS))
FEN_OBJS := $(addprefix $(OBJDIR)/,$(FEN_OBJS))
BB_OBJS := $(addprefix $(OBJDIR)/,$(BB_OBJS))
MOVEGEN_OBJS := $(addprefix $(OBJDIR)/,$(MOVEGEN_OBJS))
ATTACK_OBJS := $(addprefix $(OBJDIR)/,$(ATTACK_OBJS))
MOVEDO_OBJS := $(addprefix $(OBJDIR)/,$(MOVEDO_OBJS))
PERFT_OBJS := $(addprefix $(OBJDIR)/,$(PERFT_OBJS))
test:
echo TEST=$(TEST)
echo FEN_OBJS=$(FEN_OBJS)
testing: $(TEST)
bin/fen-test: test/fen-test.c $(FENTESTOBJS)
$(CC) $(CPPFLAGS) $(CFLAGS) $< $(FENTESTOBJS) $(LDFLAGS) $(LIBS) -o $@
bin/piece-test: test/piece-test.c $(FEN_OBJS)
@echo compiling $@ test executable.
@$(CC) $(ALL_CFLAGS) $< $(FEN_OBJS) $(ALL_LDFLAGS) -o $@
bin/bitboard-test: test/bitboard-test.c $(BITBOARDOBJS)
$(CC) $(CPPFLAGS) $(CFLAGS) $< $(BITBOARDOBJS) $(LDFLAGS) $(LIBS) -o $@
bin/fen-test: test/fen-test.c test/common-test.h $(FEN_OBJS)
@echo compiling $@ test executable.
@$(CC) $(ALL_CFLAGS) $< $(FEN_OBJS) $(ALL_LDFLAGS) -o $@
bin/bitboard-test: test/bitboard-test.c test/common-test.h $(BB_OBJS)
@echo compiling $@ test executable.
@$(CC) $(ALL_CFLAGS) $< $(BB_OBJS) $(ALL_LDFLAGS) -o $@
bin/movegen-test: test/movegen-test.c test/common-test.h $(MOVEGEN_OBJS)
@echo compiling $@ test executable.
@$(CC) $(ALL_CFLAGS) $< $(MOVEGEN_OBJS) $(ALL_LDFLAGS) -o $@
bin/attack-test: test/attack-test.c test/common-test.h $(ATTACK_OBJS)
@echo compiling $@ test executable.
@$(CC) $(ALL_CFLAGS) $< $(ATTACK_OBJS) $(ALL_LDFLAGS) -o $@
bin/movedo-test: test/movedo-test.c test/common-test.h $(MOVEDO_OBJS)
@echo compiling $@ test executable.
@$(CC) $(ALL_CFLAGS) $< $(MOVEDO_OBJS) $(ALL_LDFLAGS) -o $@
bin/perft-test: test/perft-test.c test/common-test.h $(PERFT_OBJS)
@echo compiling $@ test executable.
@$(CC) $(ALL_CFLAGS) $< $(PERFT_OBJS) $(ALL_LDFLAGS) -o $@
##################################### Makefile debug
.PHONY: showflags wft

2
brlib

Submodule brlib updated: f9aec10459...8ff163dcf5

214
src/attack.c Normal file
View File

@@ -0,0 +1,214 @@
/* attack.c - attack 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 <stdarg.h>
#include "chessdefs.h"
#include "bitboard.h"
#include "position.h"
#include "hyperbola-quintessence.h"
#include "attack.h"
/**
* sq_is_attacked() - find if a square is attacked
* @pos: position
* @occ: occupation mask used
* @sq: square to test
* @c: attacker color
*
* Find if a @c piece attacks @sq.
*
* Algorithm: We perform a reverse attack, and check if any given
* piece type on @sq can attack a @c piece of same type.
*
* For example, if @c is white, we test for all T in P,N,B,R,Q,K if
* T on @sq could attack a white T piece.
*
* @Return: true if @sq is attacked by a @c piece, false otherwise.
*/
bool sq_is_attacked(const pos_t *pos, const bitboard_t occ, const square_t sq, const color_t c)
{
color_t opp = OPPONENT(c);
/* bishop / queen */
if (hyperbola_bishop_moves(occ, sq) & (pos->bb[c][BISHOP] | pos->bb[c][QUEEN]))
return true;
/* rook / queen */
if (hyperbola_rook_moves(occ, sq) & (pos->bb[c][ROOK] | pos->bb[c][QUEEN]))
return true;
/* pawn */
if (bb_pawn_attacks[opp][sq] & pos->bb[c][PAWN])
return true;
/* knight */
if (bb_knight_moves(pos->bb[c][KNIGHT], sq))
return true;
/* king */
if (bb_king_moves(pos->bb[c][KING], sq))
return true;
return false;
}
/**
* is_in_check() - find if a king is in check.
* @pos: position
* @color: king color
*
* Find if a @c king is in check. This function is a wrapper over @sq_is_attacked().
*
* @Return: true if @sq is attacked by a @c piece, false otherwise.
*/
bool is_in_check(const pos_t *pos, const color_t color)
{
bitboard_t occ = pos_occ(pos);
return sq_is_attacked(pos, occ, pos->king[color], OPPONENT(color));
}
/**
* sq_attackers() - find attackers on a square
* @pos: position
* @occ: occupation mask used
* @sq: square to test
* @c: attacker color
*
* Find all @c attacks on @sq. En-passant is not considered.
*
* Algorithm: We perform a reverse attack, and check if any given
* piece type on @sq can attack a @c piece of same type.
*
* For example, if @c is white, we test for all T in P,N,B,R,Q,K if
* T on @sq could attack a white T piece.
*
* @Return: a bitboard of attackers.
*/
bitboard_t sq_attackers(const pos_t *pos, const bitboard_t occ, const square_t sq, const color_t c)
{
bitboard_t attackers = 0, tmp;
bitboard_t sqbb = mask(sq);
//bitboard_t occ = pos_occ(pos);
bitboard_t to;
color_t opp = OPPONENT(c);
/* pawn */
to = pos->bb[c][PAWN];
tmp = pawn_shift_upleft(sqbb, opp) & to;
attackers |= tmp;
# ifdef DEBUG_ATTACK_ATTACKERS1
bb_print("att pawn upleft", tmp);
# endif
tmp = pawn_shift_upright(sqbb, opp) & to;
attackers |= tmp;
# ifdef DEBUG_ATTACK_ATTACKERS1
bb_print("att pawn upright", tmp);
# endif
/* knight & king */
to = pos->bb[c][KNIGHT];
tmp = bb_knight_moves(to, sq);
attackers |= tmp;
# ifdef DEBUG_ATTACK_ATTACKERS1
bb_print("att knight", tmp);
# endif
to = pos->bb[c][KING];
tmp = bb_king_moves(to, sq);
attackers |= tmp;
# ifdef DEBUG_ATTACK_ATTACKERS1
bb_print("att king", tmp);
# endif
/* bishop / queen */
to = pos->bb[c][BISHOP] | pos->bb[c][QUEEN];
tmp = hyperbola_bishop_moves(occ, sq) & to;
attackers |= tmp;
# ifdef DEBUG_ATTACK_ATTACKERS1
bb_print("att bishop/queen", tmp);
# endif
/* rook / queen */
to = pos->bb[c][ROOK] | pos->bb[c][QUEEN];
tmp = hyperbola_rook_moves(occ, sq) & to;
attackers |= tmp;
# ifdef DEBUG_ATTACK_ATTACKERS1
bb_print("att rook/queen", tmp);
bb_print("ATTACKERS", attackers);
printf("attackers=%lx\n", attackers);
# endif
return attackers;
}
/**
* sq_pinners() - get "pinners" on a square
* @pos: position
* @sq: square to test
* @color: attacker color
*
* Find all @c pieces which are separated from @sq by only one piece (of
* any color).
*
* @Return: bitboard of pinners.
*/
bitboard_t sq_pinners(const pos_t *pos, const square_t sq, const color_t color)
{
bitboard_t attackers, pinners = 0;
bitboard_t occ = pos_occ(pos);
bitboard_t maybe_pinner, tmp, lines;
/* bishop type */
attackers = pos->bb[color][BISHOP] | pos->bb[color][QUEEN];
/* occupancy on sq diag and antidiag */
lines = (bb_sqdiag[sq] | bb_sqanti[sq]) & occ;
bit_for_each64(maybe_pinner, tmp, attackers) {
bitboard_t between = bb_between_excl[maybe_pinner][sq];
/* keep only squares between AND on sq diag/anti */
if (popcount64(between & lines) == 1)
pinners |= mask(maybe_pinner);
}
/* same for rook type */
attackers = pos->bb[color][ROOK] | pos->bb[color][QUEEN];
lines = (bb_sqrank[sq] | bb_sqfile[sq]) & occ;
bit_for_each64(maybe_pinner, tmp, attackers) {
bitboard_t between = bb_between_excl[maybe_pinner][sq];
if (popcount64(between & lines) == 1)
pinners |= mask(maybe_pinner);
}
# ifdef DEBUG_ATTACK_ATTACKERS1
char str[32];
printf("pinners : %s\n", pos_pinners2str(pos, str, sizeof(str)));
printf("pinners : %lx\n", pinners);
# endif
return pinners;
}
/**
* sq_attackers() - find all attackers on a square
* @pos: position
* @sq: square to test
*
* Find all attacks on @sq. En-passant is not considered.
* Just a wrapper over @sq_attackers().
*
* @Return: a bitboard of attackers.
*/
bitboard_t sq_attackers_all(const pos_t *pos, const square_t sq)
{
bitboard_t occ = pos_occ(pos);
return sq_attackers(pos, occ, sq, WHITE) | sq_attackers(pos, occ, sq, BLACK);
}

26
src/attack.h Normal file
View File

@@ -0,0 +1,26 @@
/* attack.h - attack 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 _ATTACK_H
#define _ATTACK_H
#include "chessdefs.h"
#include "bitboard.h"
bool sq_is_attacked(const pos_t *pos, const bitboard_t occ, const square_t sq, const color_t c);
bool is_in_check(const pos_t *pos, const color_t color);
bitboard_t sq_attackers(const pos_t *pos, const bitboard_t occ, const square_t sq, const color_t c);
bitboard_t sq_attackers_all(const pos_t *pos, const square_t sq);
bitboard_t sq_pinners(const pos_t *pos, const square_t sq, const color_t c);
#endif

View File

@@ -20,7 +20,14 @@
#include "piece.h"
#include "board.h"
#include "bitboard.h"
#include "position.h"
bitboard_t bb_sq[64];
bitboard_t bb_sqrank[64], bb_sqfile[64], bb_sqdiag[64], bb_sqanti[64];
bitboard_t bb_between_excl[64][64];
bitboard_t bb_between[64][64];
bitboard_t bb_line[64][64];
bitboard_t bb_knight[64], bb_king[64], bb_pawn_attacks[2][64];
/* vectors are clockwise from N */
static int knight_vector[] = {
@@ -34,32 +41,63 @@ static int king_vector[8] = {
SOUTH, SOUTH_WEST, WEST, NORTH_WEST
};
bitboard_t bb_sq[SQUARE_MAX];
bitboard_t bb_rank[64], bb_file[64], bb_diagonal[64], bb_antidiagonal[64];
/**
* bitboard_between_excl() - get bitboard of squares between two squares.
* @sq1, @sq2: The two square_t squares
*
* From: http://www.talkchess.com/forum3/viewtopic.php?f=7&t=12499&start=14
* This function may be used instead of bb_XXX arrays if cache pressure is high.
*
* @Return: bitboard_t, squares between @sq1 and @sq2 (excl. @sq1 and @sq2).
*/
bitboard_t bitboard_between_excl(square_t sq1, square_t sq2)
{
const bitboard_t m1 = -1;
const bitboard_t a2a7 = C64(0x0001010101010100);
const bitboard_t b7h1 = C64(0x0002040810204080);
bitboard_t btwn_bits, ray_bits;
u32 rank_diff, file_diff, anti_diff, diag_diff;
bitboard_t bb_knight[64], bb_king[64];
bitboard_t bb_pawn_push[2][64], bb_bpawn_attack[2][64], bb_pawn_ep[2][64];
btwn_bits = (m1 << sq1) ^ (m1 << sq2); /* includes sq1 and sq2 */
rank_diff = ((sq2 | 7) - sq1) >> 3, /* signed */
file_diff = (sq2 & 7) - (sq1 & 7); /* signed */
anti_diff = rank_diff + file_diff;
rank_diff = rank_diff & 15;
file_diff = file_diff & 15;
anti_diff = anti_diff & 15;
diag_diff = rank_diff ^ file_diff;
ray_bits = 2 * ((rank_diff - 1) >> 26);
ray_bits |= bswap64((m1 + diag_diff) & b7h1);
ray_bits |= (m1 + anti_diff) & b7h1;
ray_bits |= (m1 + file_diff) & a2a7;
ray_bits *= btwn_bits & -btwn_bits;
return ray_bits & btwn_bits;
}
/**
* bitboard_init() - initialize general bitboards
*
* Generate the following bitboards :
* bb_sq[64]: square to bitboard
* bb_rank[64]: square to rank
* bb_file[64]: square to file
* bb_diagonal[64]: square to diagonal
* bb_antidiagonal[64]: square to antidiagonal
* bb_sqrank[64]: square to rank
* bb_sqfile[64]: square to file
* bb_sqdiag[64]: square to diagonal
* bb_sqanti[64]: square to antidiagonal
*
* bb_between_excl[64][64]: strict squares between two squares
* bb_between[64][64]: squares between two squares including second square
*
* And the following pseudo move masks:
* bb_knight[64]: knight moves
* bb_king[64]: king moves
* bb_pawn[2][64]: white pawn moves (not attacks)
* bb_pawn_att[2][64]: white pawn attacks
*
*/
void bitboard_init(void)
{
/* for each square, the 4 masks: file, rank, diagonal, antidiagonal */
struct { int df, dr; } dirs[4] = {
struct { int df, dr; } vecs[4] = {
{ 0, 1 }, /* vertical/file */
{ 1, 0 }, /* horizontal/rank */
{ 1, 1 }, /* diagonal */
@@ -67,33 +105,66 @@ void bitboard_init(void)
} ;
bitboard_t tmpbb[64][4] = { 0 };
/* 1) square to bitboard */
for (square_t sq = A1; sq <= H8; ++sq)
bb_sq[sq] = mask(sq);
/* 1) square to bitboard
* in-between, sq2 excluded
*/
for (square_t sq1 = A1; sq1 <= H8; ++sq1) {
bb_sq[sq1] = mask(sq1);
for (square_t sq2 = A1; sq2 <= H8; ++sq2)
bb_between_excl[sq1][sq2] = bitboard_between_excl(sq1, sq2);
}
/* 2) square to rank/file/diagonal/antidiagonal */
/* 2) sq1-to-sq2 mask, sq2 included
* square to file/rank/dia/anti bitmaps
*/
for (square_t sq = 0; sq < 64; ++sq) {
int r = sq_rank(sq), f = sq_file(sq);
for (int mult = -7; mult < 8; ++mult) {
for (int dir = 0; dir < 4; ++dir) {
int dst_f = f + mult * dirs[dir].df;
int dst_r = r + mult * dirs[dir].dr;
if (sq_coord_ok(dst_f) && sq_coord_ok(dst_r)) {
int dst = sq_make(dst_f, dst_r);
tmpbb[sq][dir] |= mask(dst);
file_t f = sq_file(sq);
rank_t r = sq_rank(sq);
for (int vec = 0; vec < 4; ++vec) {
tmpbb[sq][vec] |= mask(sq_make(f, r));
for (int dir = -1; dir <= 1; dir += 2) {
file_t df = dir * vecs[vec].df, f2 = f + df;
rank_t dr = dir * vecs[vec].dr, r2 = r + dr;
bitboard_t mask_between = 0;
while (sq_coord_ok(f2) && sq_coord_ok(r2)) {
square_t dest = sq_make(f2, r2);
tmpbb[sq][vec] |= mask(dest);
mask_between |= mask(dest);
bb_between[sq][dest] = mask_between;
f2 += df, r2 += dr;
}
}
}
}
for (square_t sq = 0; sq < 64; ++sq) {
bb_file[sq] = tmpbb[sq][0];
bb_rank[sq] = tmpbb[sq][1];
bb_diagonal[sq] = tmpbb[sq][2];
bb_antidiagonal[sq] = tmpbb[sq][3];
bb_sqfile[sq] = tmpbb[sq][0];
bb_sqrank[sq] = tmpbb[sq][1];
bb_sqdiag[sq] = tmpbb[sq][2];
bb_sqanti[sq] = tmpbb[sq][3];
}
for (square_t sq1 = 0; sq1 < 64; ++sq1) {
for (square_t sq2 = 0; sq2 < 64; ++sq2) {
if (sq1 != sq2) {
if (bb_sqfile[sq1] == bb_sqfile[sq2])
bb_line[sq1][sq2] = bb_sqfile[sq1];
else if (bb_sqrank[sq1] == bb_sqrank[sq2])
bb_line[sq1][sq2] = bb_sqrank[sq1];
else if (bb_sqdiag[sq1] == bb_sqdiag[sq2])
bb_line[sq1][sq2] = bb_sqdiag[sq1];
else if (bb_sqanti[sq1] == bb_sqanti[sq2])
bb_line[sq1][sq2] = bb_sqanti[sq1];
}
}
}
/* 3) knight and king moves */
/* 3) pawn, knight and king attacks
*/
for (square_t sq = A1; sq <= H8; ++sq) {
if (sq >= A2)
bb_pawn_attacks[BLACK][sq] = pawn_attacks_bb(mask(sq), BLACK);
if (sq <= H7)
bb_pawn_attacks[WHITE][sq] = pawn_attacks_bb(mask(sq), WHITE);
for (int vec = 0; vec < 8; ++vec) {
int dst = sq + knight_vector[vec];
if (sq_ok(dst)) {
@@ -111,21 +182,37 @@ void bitboard_init(void)
}
}
/**
* bb_knight_moves() - get bitboard of knight pseudo-moves
* @notmine: bitboard_t of squares not occupied by own pieces
* @sq: knight square
*
* @Return: bitboard of available moves.
*/
bitboard_t bb_knight_moves(bitboard_t notmine, square_t sq)
{
return bb_knight[sq] & notmine;
}
/**
* bb_king_moves() - get bitboard of king pseudo-moves
* @notmine: bitboard_t of squares not occupied by own pieces
* @sq: king square
*
* @Return: bitboard of available moves.
*/
bitboard_t bb_king_moves(bitboard_t notmine, square_t sq)
{
return bb_king[sq] & notmine;
}
/**
* bitboard_print() - print simple bitboard representation
* bb_print() - print simple bitboard representation
* @title: a string or NULL
* @bitboard: the bitboard
*/
void bitboard_print(const char *title, const bitboard_t bitboard)
void bb_print(const char *title, const bitboard_t bitboard)
{
//char c = p? p: 'X';
if (title)
@@ -142,19 +229,19 @@ void bitboard_print(const char *title, const bitboard_t bitboard)
}
/**
* bitboard_print_multi() - print multiple bitboards horizontally
* bb_print_multi() - print multiple bitboards horizontally
* @title: a string or NULL
* @n: number of bitboards
* @bb_ptr...: pointers to bitboards
*
* @n is the number of bitboards to print. If @n -s > 8, it is reduced to 8;
* @n is the number of bitboards to print. If @n > 10, it is reduced to 10
*/
void bitboard_print_multi(const char *title, int n, ...)
void bb_print_multi(const char *title, int n, ...)
{
bitboard_t bb[8];
va_list ap;
n = min(n, 8);
n = min(n, 10);
va_start(ap, n);
for (int i = 0; i < n; ++i) { /* save all bitboards */
@@ -184,16 +271,60 @@ void bitboard_print_multi(const char *title, int n, ...)
}
/**
* bitboard_rank_sprint() - print an u8 rank binary representation
* bb_rank_sprint() - print an u8 rank binary representation
* @str: the destination string
* @bb8: the uchar to print
*
* @return: @str, filled with ascii representation
*/
char *bitboard_rank_sprint(char *str, const uchar bb8)
char *bb_rank_sprint(char *str, const uchar bb8)
{
for (file_t f = FILE_A; f <= FILE_H; ++f) {
*(str+f) = bb8 & mask(f) ? '1': '.';
file_t f;
for (f = FILE_A; f <= FILE_H; ++f) {
*(str + f) = bb8 & mask(f) ? '1': '.';
}
*(str + f) = 0;
//printf(" 0 1 2 3 4 5 6 7\n");
//printf("\n");
return str;
}
/**
* bb_sq2str() - convert bitboard to a string with a list of squares.
* @bb: bitboard
* @str: destination string
* @len: max @str length
*
* @str will be filled with the list of string representation of @bb, up to @len
* characters.
* 3 characters are used per square, so, for example, @str len should be :
* - For a valid position checkers (two checkers max): 2*3 + 1 = 7.
* - For a valid position pinners (8 pinners): 8*3 + 1 = 25.
* - for a full bitboard: 64*3 + 1 = 193.
*
* If @len is not enough to fill all moves, the last fitting move is replaced by "...".
*
* @return: The string.
*/
char *bb_sq2str(const bitboard_t bb, char *str, const int len)
{
bitboard_t tmp, sq;
int nocc = popcount64(bb);
int needed = 3 * nocc + 1;
int willdo = (int) len >= needed ? nocc: (len - 1) / 3 - 1;
int current = 0;
//printf("sq2str bb=%lx len=%d willdo=%d\n", bb, len, willdo);
bit_for_each64(sq, tmp, bb) {
if (current == willdo) {
strcpy(str + current * 3, "...");
} else {
strcpy(str + current * 3, sq_to_string(sq));
str[current * 3 + 2] = ' ';
}
if (++current > willdo)
break;
}
str[current * 3] = 0;
return str;
}

View File

@@ -14,50 +14,266 @@
#ifndef _BITBOARD_H
#define _BITBOARD_H
#include "brlib.h"
#include "bitops.h"
#include <brlib.h>
#include <bitops.h>
#include "chessdefs.h"
#include "board.h"
typedef u64 bitboard_t;
#include "piece.h"
/* mapping square -> bitboard */
extern bitboard_t bb_sq[64];
/* squares between sq1 and sq2, exclusing both */
extern bitboard_t bb_between_excl[64][64];
/* squares between sq1 and sq2, including sq2 */
extern bitboard_t bb_between[64][64];
/* mapping square -> rank/file/diagonal/antidiagonal */
extern bitboard_t bb_rank[64], bb_file[64], bb_diagonal[64], bb_antidiagonal[64];
extern bitboard_t bb_knight[64], bb_king[64];
#define mask(i) ( 1ULL << (i) )
enum {
FILE_Abb = 0x0101010101010101ULL,
FILE_Bbb = 0x0202020202020202ULL,
FILE_Cbb = 0x0404040404040404ULL,
FILE_Dbb = 0x0808080808080808ULL,
FILE_Ebb = 0x1010101010101010ULL,
FILE_Fbb = 0x2020202020202020ULL,
FILE_Gbb = 0x4040404040404040ULL,
FILE_Hbb = 0x8080808080808080ULL,
};
enum {
RANK_1bb = 0x00000000000000ffULL,
RANK_2bb = 0x000000000000ff00ULL,
RANK_3bb = 0x0000000000ff0000ULL,
RANK_4bb = 0x00000000ff000000ULL,
RANK_5bb = 0x000000ff00000000ULL,
RANK_6bb = 0x0000ff0000000000ULL,
RANK_7bb = 0x00ff000000000000ULL,
RANK_8bb = 0xff00000000000000ULL
};
/* https://www.chessprogramming.org/Flipping_Mirroring_and_Rotating#Rotation
/**
* bb_sqrank[64]: square to rank
* bb_sqfile[64]: square to file
* bb_sqdiag[64]: square to diagonal
* bb_sqanti[64]: square to antidiagonal
*/
static __always_inline bitboard_t bb_rotate_90(bitboard_t b)
extern bitboard_t bb_sqrank[64], bb_sqfile[64], bb_sqdiag[64], bb_sqanti[64];
/* line (rank, file, diagonal or anti-diagonal) between two squares */
extern bitboard_t bb_line[64][64];
/* pawn, knight and king attacks */
extern bitboard_t bb_knight[64], bb_king[64], bb_pawn_attacks[2][64];
/* TODO (maybe C23?) when we can ensure an enum can be u64
*
* enum {
* 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),
* };
*
* enum {
* FILE_Abb = 0x0101010101010101ull, FILE_Bbb = 0x0202020202020202ull,
* FILE_Cbb = 0x0404040404040404ull, FILE_Dbb = 0x0808080808080808ull,
* FILE_Ebb = 0x1010101010101010ull, FILE_Fbb = 0x2020202020202020ull,
* FILE_Gbb = 0x4040404040404040ull, FILE_Hbb = 0x8080808080808080ull,
*
* RANK_1bb = 0x00000000000000ffull, RANK_2bb = 0x000000000000ff00ull,
* RANK_3bb = 0x0000000000ff0000ull, RANK_4bb = 0x00000000ff000000ull,
* RANK_5bb = 0x000000ff00000000ull, RANK_6bb = 0x0000ff0000000000ull,
* RANK_7bb = 0x00ff000000000000ull, RANK_8bb = 0xff00000000000000ull
* };
*/
/* generated with bash:
* R="ABCDEFGH"
* F="12345678"
* for i in {0..63}; do
* printf "#define %c%cbb %#018llxull\n" ${R:i/8:1} ${F:i%8:1} $((1 << i))
* done
*/
#define A1bb 0x0000000000000001ull
#define A2bb 0x0000000000000002ull
#define A3bb 0x0000000000000004ull
#define A4bb 0x0000000000000008ull
#define A5bb 0x0000000000000010ull
#define A6bb 0x0000000000000020ull
#define A7bb 0x0000000000000040ull
#define A8bb 0x0000000000000080ull
#define B1bb 0x0000000000000100ull
#define B2bb 0x0000000000000200ull
#define B3bb 0x0000000000000400ull
#define B4bb 0x0000000000000800ull
#define B5bb 0x0000000000001000ull
#define B6bb 0x0000000000002000ull
#define B7bb 0x0000000000004000ull
#define B8bb 0x0000000000008000ull
#define C1bb 0x0000000000010000ull
#define C2bb 0x0000000000020000ull
#define C3bb 0x0000000000040000ull
#define C4bb 0x0000000000080000ull
#define C5bb 0x0000000000100000ull
#define C6bb 0x0000000000200000ull
#define C7bb 0x0000000000400000ull
#define C8bb 0x0000000000800000ull
#define D1bb 0x0000000001000000ull
#define D2bb 0x0000000002000000ull
#define D3bb 0x0000000004000000ull
#define D4bb 0x0000000008000000ull
#define D5bb 0x0000000010000000ull
#define D6bb 0x0000000020000000ull
#define D7bb 0x0000000040000000ull
#define D8bb 0x0000000080000000ull
#define E1bb 0x0000000100000000ull
#define E2bb 0x0000000200000000ull
#define E3bb 0x0000000400000000ull
#define E4bb 0x0000000800000000ull
#define E5bb 0x0000001000000000ull
#define E6bb 0x0000002000000000ull
#define E7bb 0x0000004000000000ull
#define E8bb 0x0000008000000000ull
#define F1bb 0x0000010000000000ull
#define F2bb 0x0000020000000000ull
#define F3bb 0x0000040000000000ull
#define F4bb 0x0000080000000000ull
#define F5bb 0x0000100000000000ull
#define F6bb 0x0000200000000000ull
#define F7bb 0x0000400000000000ull
#define F8bb 0x0000800000000000ull
#define G1bb 0x0001000000000000ull
#define G2bb 0x0002000000000000ull
#define G3bb 0x0004000000000000ull
#define G4bb 0x0008000000000000ull
#define G5bb 0x0010000000000000ull
#define G6bb 0x0020000000000000ull
#define G7bb 0x0040000000000000ull
#define G8bb 0x0080000000000000ull
#define H1bb 0x0100000000000000ull
#define H2bb 0x0200000000000000ull
#define H3bb 0x0400000000000000ull
#define H4bb 0x0800000000000000ull
#define H5bb 0x1000000000000000ull
#define H6bb 0x2000000000000000ull
#define H7bb 0x4000000000000000ull
#define H8bb 0x8000000000000000ull
#define FILE_Abb 0x0101010101010101ull
#define FILE_Bbb 0x0202020202020202ull
#define FILE_Cbb 0x0404040404040404ull
#define FILE_Dbb 0x0808080808080808ull
#define FILE_Ebb 0x1010101010101010ull
#define FILE_Fbb 0x2020202020202020ull
#define FILE_Gbb 0x4040404040404040ull
#define FILE_Hbb 0x8080808080808080ull
#define RANK_1bb 0x00000000000000ffull
#define RANK_2bb 0x000000000000ff00ull
#define RANK_3bb 0x0000000000ff0000ull
#define RANK_4bb 0x00000000ff000000ull
#define RANK_5bb 0x000000ff00000000ull
#define RANK_6bb 0x0000ff0000000000ull
#define RANK_7bb 0x00ff000000000000ull
#define RANK_8bb 0xff00000000000000ull
/*
static __always_inline bitboard_t bb_rank(int rank)
{
return b;
return RANK_1bb << (rank * 8);
}
static __always_inline bitboard_t bb_rel_rank(int rank, color)
{
return RANK_1bb << (rank * 8);
}
static __always_inline bitboard_t bb_file(int file)
{
return FILE_Abb << file;
}
*/
/**
* bb_first_bb() - return bitboard of first square of a bitboard.
* @bb: bitboard
*
* bb must be non-zero.
*
* @return: bitboard of first square (lsb) of @bb.
*/
static __always_inline square_t bb_first_bb(bitboard_t bb)
{
return bb & -bb;
}
/**
* bb_next() - clear and return next (lsb) square of a bitboard.
* @bb: &bitboard
*
* The bitboard addressed by @bb must be non-zero.
*
* @return: first bit (lsb) of @bb.
*/
static __always_inline square_t bb_next(bitboard_t *bb)
{
square_t sq = ctz64(*bb);
*bb &= *bb - 1;
return sq;
}
/**
* bb_multiple() - test if a bitboard has multiple bits.
* @bb: bitboard
*
* @return: true if @bb has more than 1 bit, false otherwise.
*/
static __always_inline bool bb_multiple(bitboard_t bb)
{
return !!(bb & (bb - 1));
}
/**
* bb_shift() - shift bitboard
* @bb: bitboard
*
* No control is done on off-board shifting (i.e. shifting -1 from A2 gives H3).
*
* @return: true if @bb has more than 1 bit, false otherwise.
*/
static __always_inline bitboard_t bb_shift(bitboard_t bb, int shift)
{
return shift >= 0 ? bb << shift : bb >> -shift;
}
#define bb_rank(r) ((u64) RANK_1bb << ((r) * 8))
#define bb_file(f) ((u64) FILE_Abb << (f))
#define bb_rel_rank(r, c) bb_rank(sq_rel_rank(r, c))
#define bb_rel_file(f, c) bb_file(sq_rel_rank(f, c))
/**
* bb_sq_aligned() - check if two squares are aligned (same file or rank).
* @sq1, @sq2: the two squares.
*
* @return: true if @sq1 and @sq2 are on same line, false otherwise.
*/
static __always_inline bool bb_sq_aligned(square_t sq1, square_t sq2)
{
return bb_line[sq1][sq2];
}
/**
* bb_sq_aligned3() - check if 3 squares are aligned (same file or rank).
* @sq1, @sq2, @sq3: the three squares.
*
* @return: true if @sq1, @sq2, and @sq3 are aligned, false otherwise.
*/
static __always_inline bool bb_sq_aligned3(square_t sq1, square_t sq2, square_t sq3)
{
return bb_line[sq1][sq2] & mask(sq3);
}
/**
* bb_sq_between() - check if a square is between two squares
* @sq: the possibly "in-between" square
* @sq1: square 1
* @sq2: square 2
*
* @return: bitboard of @sq if between @sq1 and @sq2.
*/
static __always_inline bitboard_t bb_sq_between(square_t sq, square_t sq1, square_t sq2)
{
return bb_between_excl[sq1][sq2] & mask(sq);
}
/* TODO: when OK, replace with macros */
@@ -94,13 +310,30 @@ static __always_inline bitboard_t shift_nw(const bitboard_t bb)
return (bb & ~FILE_Abb) << NORTH_WEST;
}
extern void bitboard_init(void);
/* pawn moves/attacks (for bitboards) */
#define pawn_shift_up(bb, c) ((c) == WHITE ? shift_n(bb): shift_s(bb))
#define pawn_shift_upleft(bb, c) ((c) == WHITE ? shift_nw(bb): shift_se(bb))
#define pawn_shift_upright(bb, c) ((c) == WHITE ? shift_ne(bb): shift_sw(bb))
extern bitboard_t bb_knight_moves(bitboard_t occ, square_t sq);
extern bitboard_t bb_king_moves(bitboard_t occ, square_t sq);
#define pawn_attacks_bb(bb, c) (pawn_shift_upleft(bb, c) | \
pawn_shift_upright(bb, c))
extern void bitboard_print(const char *title, const bitboard_t bitboard);
extern void bitboard_print_multi(const char *title, const int n, ...);
extern char *bitboard8_sprint(char *str, const uchar bb8);
/* pawn move (for single pawn) - NO SQUARE CONTROL HERE !
* Need to make functions with control instead.
*/
#define pawn_push_up(sq, c) ((sq) + ((c) == WHITE ? NORTH: SOUTH))
//#define pawn_push_upleft(sq, c) ((sq) + ((c) == WHITE ? NORTH_WEST: SOUTH_EAST))
//#define pawn_push_upright(sq, c) ((sq) + ((c) == WHITE ? NORTH_EAST: SOUTH_WEST))
bitboard_t bitboard_between_excl(square_t sq1, square_t sq2);
void bitboard_init(void);
bitboard_t bb_knight_moves(bitboard_t notmine, square_t sq);
bitboard_t bb_king_moves(bitboard_t notmine, square_t sq);
void bb_print(const char *title, const bitboard_t bitboard);
void bb_print_multi(const char *title, const int n, ...);
char *bb_rank_sprint(char *str, const uchar bb8);
char *bb_sq2str(const bitboard_t bb, char *str, int len);
#endif /* _BITBOARD_H */

View File

@@ -1,4 +1,4 @@
/* board.c - 8x8 board.
/* board.c - 8x8 functions.
*
* Copyright (C) 2024 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
@@ -11,10 +11,14 @@
*
*/
#include <stdio.h>
#include <ctype.h>
#include "brlib.h"
#include "board.h"
#include "bitboard.h"
char *sq_strings[] = {
static const char *sq_strings[] = {
"a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1",
"a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2",
"a3", "b3", "c3", "d3", "e3", "f3", "g3", "h3",
@@ -25,7 +29,100 @@ char *sq_strings[] = {
"a8", "b8", "c8", "d8", "e8", "f8", "g8", "h8",
};
const char *sq_string(const int sq)
/**
* sq_to_string() - return a square string
* @square: square (0-64)
*
* @Return: Pointer to @square string representation ("a1"-"h8").
*/
const char *sq_to_string(const square_t square)
{
return sq_strings[sq];
return sq_strings[square];
}
/**
* sq_from_string() - return a square from a string
* @sqstr: the square representation (a1-h8)
*
* @Return: square_t representation of str.
*/
square_t sq_from_string(const char *sqstr)
{
file_t f = C2FILE(sqstr[0]);
rank_t r = C2RANK(sqstr[1]);
return sq_coord_ok(f) && sq_coord_ok(r) ? sq_make(f, r): SQUARE_NONE;
}
/**
* board_print() - Print a board
* @board: &board_t to print
*/
void board_print(const piece_t *board)
{
printf(" +---+---+---+---+---+---+---+---+\n");
for (int rank = 7; rank >= 0; --rank) {
printf("%c |", rank + '1');
for (int file = 0; file < 8; ++file) {
piece_t pc = board[sq_make(file, rank)];
# ifdef DIAGRAM_SYM
printf(" %s |", pc? piece_to_sym(pc): " ");
# else
printf(" %s |", pc? piece_to_fen(pc): " ");
# endif
}
printf("\n +---+---+---+---+---+---+---+---+\n");
}
printf(" A B C D E F G H\n");
}
/**
* board_print_mask() - Print a board position with some reversed squares
* @board: &board_t to print
* @mask: a bitboard indicating reverse color displayed squares
*
* Squares corresponding to @mask will be displayed in reverse colors.
*/
void board_print_mask(const piece_t *board, const bitboard_t mask)
{
// 6: blink
# define REVERSE "\e[7m▌"
# define RESET "▐\e[0m"
printf(" +---+---+---+---+---+---+---+---+\n");
for (int rank = 7; rank >= 0; --rank) {
printf("%c |", rank + '1');
for (int file = 0; file < 8; ++file) {
square_t sq = sq_make(file, rank);
piece_t pc = board[sq];
bitboard_t set = mask(sq) & mask;
printf("%s", set? REVERSE : " ");
# ifdef DIAGRAM_SYM
printf("%s", pc? piece_to_sym(pc): " ");
# else
printf("%s", pc? piece_to_char_color(pc): " ");
# endif
printf("%s|", set? RESET : " ");
}
printf("\n +---+---+---+---+---+---+---+---+\n");
}
printf(" A B C D E F G H\n");
}
/**
* board_print_raw - print raw (octal or FEN symbol) board
* @bb: the bitboard
* @type: int, 0 for octal, 1 for fen symbol
*/
void board_print_raw(const piece_t *board, const int type)
{
for (rank_t r = RANK_8; r >= RANK_1; --r) {
for (file_t f = FILE_A; f <= FILE_H; ++f) {
piece_t p = board[sq_make(f, r)];
if (type) {
printf("%s ", p == EMPTY? ".": piece_to_char(p));
} else {
printf("%02o ", p);
}
}
printf("\n");
}
}

View File

@@ -11,12 +11,21 @@
*
*/
#ifndef BOARD_H
#define BOARD_H
#ifndef _BOARD_H
#define _BOARD_H
#include "brlib.h"
#include "chessdefs.h"
#include "piece.h"
#include "bitboard.h"
/* 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')
/* a square is defined as
* rrrfff
@@ -24,43 +33,6 @@
#define SQ_FILEMASK (007) /* warning, octal */
#define SQ_RANKMASK (070)
typedef enum {
_SSQUARE_ = -1, /* force signed enum */
A1 = 0, 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,
SQUARE_MAX = 64,
SQUARE_NONE = 64
} square_t;
typedef enum {
_SFILE_ = -1, /* force signed enum */
FILE_A = 0, FILE_B, FILE_C, FILE_D, FILE_E, FILE_F, FILE_G, FILE_H,
FILE_MAX,
} file_t;
typedef enum {
_SRANK_ = -1, /* force signed enum */
RANK_1 = 0, RANK_2, RANK_3, RANK_4, RANK_5, RANK_6, RANK_7, RANK_8,
RANK_MAX,
} rank_t;
typedef enum {
NORTH = 8,
EAST = 1,
SOUTH = -NORTH,
WEST = -EAST,
NORTH_EAST = (NORTH + EAST),
SOUTH_EAST = (SOUTH + EAST),
SOUTH_WEST = (SOUTH + WEST),
NORTH_WEST = (NORTH + WEST),
} dir_t;
/* flip a 0-63 square:
* Vertical: G8 (62) becomes G1 (6)
@@ -73,7 +45,7 @@ typedef enum {
/* TODO: revert to macros after bitboard migration */
static __always_inline square_t sq_make(file_t file, rank_t rank)
{
return (rank << 6) + file;
return (rank << 3) + file;
}
static __always_inline file_t sq_file(square_t square)
{
@@ -81,22 +53,41 @@ static __always_inline file_t sq_file(square_t square)
}
static __always_inline rank_t sq_rank(square_t square)
{
return square >> 6;
return square >> 3;
}
#define sq_ok(sq) ((sq) >= A1 && (sq) <= H8)
#define sq_coord_ok(c) ((c) >= 0 && (c) < 8)
/* Chebyshev distance: max( |r2 - r1|, |f2 - f1| )
/**
* sq_dist() - Chebyshev (king) distance between two squares (macro).
* @sq1, @sq2: The two squares.
*
* See: https://www.chessprogramming.org/Distance
* Distance is max( |r2 - r1|, |f2 - f1| )
*
* @Return: the Chebyshev distance.
*/
#define sq_dist(sq1, sq2) (max(abs(sq_file(sq2) - sq_file(sq1)), \
abs(sq_rank(sq2) - sq_rank(sq1))))
/* Manhattan distance: |r2 - r1| + |f2 - f1|
/**
* sq_taxi() - Manhattan (taxi) distance between two squares (macro).
* @sq1, @sq2: The two squares.
*
* See: https://www.chessprogramming.org/Distance
* Distance is |r2 - r1| + |f2 - f1|.
*
* @Return: the Manhattan distance.
*/
#define sq_manh(sq1, sq2) (abs(sq_file(sq2) - sq_file(sq1)) + \
#define sq_taxi(sq1, sq2) (abs(sq_file(sq2) - sq_file(sq1)) + \
abs(sq_rank(sq2) - sq_rank(sq1)))
extern const char *sq_string(const square_t sq);
extern const char *sq_to_string(const square_t sq);
extern square_t sq_from_string(const char *sq_string);
#endif /* BOARD_H */
extern void board_print(const piece_t *board);
extern void board_print_mask(const piece_t *board, const bitboard_t mask);
extern void board_print_raw(const piece_t *board, const int type);
#endif /* _BOARD_H */

View File

@@ -1,6 +1,6 @@
/* chessdefs.h - generic chess definitions.
/* chessdefs.h - generic/catchall chess 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.
* Some rights reserved. See COPYING.
*
@@ -16,18 +16,36 @@
#include "brlib.h" /* brlib types */
#define C64(const_u64) const_u64##ULL
#define U64(const_s64) const_s64##LL
#define ONE 1ull
#define C64(const_u64) const_u64##ULL
#define mask(i) ( (u64) (ONE << (i)) )
//typedef ushort board;
#define BOARDSIZE (8*8)
#define BOARDSIZE (8*8)
/* 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')
/**
* sq_rel - get relative square
* @sq: white point of view square
* @c: color
*
* Get relative (mirrored if @c is BLACK) square.
* Example: sq_rel(A1, WHITE) = A1, sq_rel(B2, BLACK) = B7
*
* @return: Relative square.
*/
#define sq_rel(sq, c) ((square_t)((sq) ^ (56 * (c))))
/**
* sq_rel_rank - get relative rank
* @rank: white point of view rank
* @c: color
*
* Get relative (mirrored if @c is BLACK) rank.
* Example: sq_rel(RANK_2, WHITE) = RANK_2, sq_rel(RANK_6, BLACK) = RANK_3
*
* @return: Relative rank.
*/
#define sq_rel_rank(rank, c) ((rank_t)((7 * (c)) ^ rank))
#define sq_rel_file(file, c) ((file_t)((7 * (c)) ^ file))
/* castle_t bits structure
*/
@@ -36,10 +54,27 @@ typedef enum {
CASTLE_WQ = (1 << 1), /* 0x02 00000010 */
CASTLE_BK = (1 << 2), /* 0x04 00000100 */
CASTLE_BQ = (1 << 3), /* 0x08 00001000 */
CASTLE_W = (CASTLE_WK | CASTLE_WQ), /* 00000011 W castle mask */
CASTLE_B = (CASTLE_BK | CASTLE_BQ), /* 00001100 B castle mask */
CASTLE_K = (1 << 0), /* generic K/Q, bits 0 and 1 */
CASTLE_Q = (1 << 1),
CASTLE_KQ = (CASTLE_K |CASTLE_Q)
} castle_rights_t;
#define CASTLE_W (CASTLE_WK | CASTLE_WQ) /* 00000011 W castle mask */
#define CASTLE_B (CASTLE_BK | CASTLE_BQ) /* 00001100 B castle mask */
/* determine is oo or ooo is possible with castle flags f and color c
*/
//#define NORM_CASTLE(f, c) ((f) >> (2 * (c))) /* shift flags to bits 0/1 */
//#define
//(NORM_CASTLE(f, c) & CASTLE_Q)
#define can_oo(f, c) ((f) & (CASTLE_K << ((c) * 2)))
#define can_ooo(f, c) ((f) & (CASTLE_Q << ((c) * 2)))
#define can_castle(f, c) ((f) & (CASTLE_KQ << ((c) * 2)))
#define clr_oo(f, c) ((f) & ~(CASTLE_K << (2 * (c))))
#define clr_ooo(f, c) ((f) & ~(CASTLE_Q << (2 * (c))))
#define clr_castle(f, c) ((f) & ~(CASTLE_KQ << (2 * (c)) ))
/* game phases
*/
@@ -47,19 +82,93 @@ typedef enum {
#define MIDDLEGAME 1
#define ENDGAME 2
/* bitboard
/* forward defs */
typedef struct __pos_s pos_t;
typedef struct __movelist_s movelist_t;
/* basic types
*/
//typedef u64 bitboard_t;
typedef u64 bitboard_t;
/* eval type
*/
//typedef s32 eval_t;
/* forward typedefs
/* forward enum definition is impossible in C11, to simplify
* cross-dependancies, all important enum are moved here.
*/
//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;
typedef enum {
_SSQUARE_ = -1, /* force signed enum */
A1 = 0, 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,
SQUARE_MAX = 64,
SQUARE_NONE = 64
} square_t;
typedef enum {
_SFILE_ = -1, /* force signed enum */
FILE_A = 0, FILE_B, FILE_C, FILE_D, FILE_E, FILE_F, FILE_G, FILE_H,
FILE_MAX,
} file_t;
typedef enum {
_SRANK_ = -1, /* force signed enum */
RANK_1 = 0, RANK_2, RANK_3, RANK_4, RANK_5, RANK_6, RANK_7, RANK_8,
RANK_MAX,
} rank_t;
typedef enum {
NORTH = 8,
EAST = 1,
SOUTH = -NORTH,
WEST = -EAST,
NORTH_EAST = (NORTH + EAST),
SOUTH_EAST = (SOUTH + EAST),
SOUTH_WEST = (SOUTH + WEST),
NORTH_WEST = (NORTH + WEST),
} dir_t;
/* define diff for relative squares */
#define sq_up(c) ((c) == WHITE ? NORTH: SOUTH)
#define sq_upleft(c) ((c) == WHITE ? NORTH_WEST: SOUTH_EAST)
#define sq_upright(c) ((c) == WHITE ? NORTH_EAST: SOUTH_WEST)
#include <time.h>
typedef struct mclock {
clockid_t clocktype;
ulong elapsed_l;
double elapsed_f;
struct timespec start;
} mclock_t;
#define CLOCK_WALL CLOCK_REALTIME
#define CLOCK_SYSTEM CLOCK_MONOTONIC_RAW
#define CLOCK_PROCESS CLOCK_PROCESS_CPUTIME_ID
#define CLOCK_THREAD CLOCK_THREAD_CPUTIME_ID
/**
* CLOCK_DEFINE - define a clock type.
* @name: clock name
* @type: clock type
*
* This macro is equivalent to:
* mclock_t name;
* clock_init(&name, type);
*/
#define CLOCK_DEFINE(name, type) struct mclock name = { .clocktype = type }
void clock_init(mclock_t *clock, clockid_t type);
void clock_start(mclock_t *clock);
s64 clock_elapsed_μs(mclock_t *clock);
s64 clock_elapsed_ms(mclock_t *clock);
double clock_elapsed_sec(mclock_t *clock);
#endif /* _CHESSDEFS_H */

131
src/fen.c
View File

@@ -1,4 +1,4 @@
/* fen.c - fen notation.
/* fen.c - fen parsing/generation/test.
*
* Copyright (C) 2021-2024 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
@@ -21,10 +21,11 @@
#include <bug.h>
#include "chessdefs.h"
#include "util.h"
//#include "piece.h"
//#include "bitboard.h"
#include "position.h"
#include "fen.h"
#include "piece.h"
#include "util.h"
/* FEN description:
* 1 : pieces on board (no space allowed):
@@ -59,6 +60,79 @@ static const char *castle_str = "KQkq";
#define SKIP_BLANK(p) for(;isspace(*(p)); (p)++)
/**
* fen_check(pos_t *pos) - test (and try to fix) fen-generated position.
* @pos: position
*
* Test and fix the following:
* - inconsistent castle flags (if K & R are not in correct position)
* - inconsistent en-passant square (turn, bad pawn position)
*
* pos_check() is also called, leading to fatal errors if something is wrong.
*
* @return: 0 if OK, 1 if OK after fix, -1 if fatal issue.
*/
static int fen_check(pos_t *pos)
{
char *colstr[2] = { "white", "black"};
int warning = 0;
/* en passant, depends on who plays next */
if (pos->en_passant != SQUARE_NONE) {
rank_t eprank = sq_rank(pos->en_passant);
file_t epfile = sq_file(pos->en_passant);
rank_t rank5 = sq_rel_rank(RANK_5, pos->turn);
rank_t rank6 = sq_rel_rank(RANK_6, pos->turn);
rank_t rank7 = sq_rel_rank(RANK_7, pos->turn);
piece_t pawn = pos->turn == WHITE? B_PAWN: W_PAWN;
if (warn(eprank != rank6 ||
pos->board[sq_make(epfile, rank5)] != pawn ||
pos->board[sq_make(epfile, rank6)] != EMPTY ||
pos->board[sq_make(epfile, rank7)] != EMPTY,
"fen warn: wrong en-passant settings. (fixed)\n")) {
# ifdef DEBUG_FEN
printf("ep5=%o ep6=%o ep7=%o\n", sq_make(epfile, rank5),
sq_make(epfile, rank6), sq_make(epfile, rank7));
# endif
warning++;
pos->en_passant = SQUARE_NONE;
}
}
for (int color = WHITE; color <= BLACK; ++color) {
rank_t rank1 = color == WHITE? RANK_1: RANK_8;
/* castling */
/* where K and R should be for valid castle flag */
bitboard_t k = bb_sq[sq_make(FILE_E, rank1)];
bitboard_t r_k = bb_sq[sq_make(FILE_H, rank1)];
bitboard_t r_q = bb_sq[sq_make(FILE_A, rank1)];
/* where they are */
bitboard_t kings = pos->bb[color][KING];
bitboard_t rooks = pos->bb[color][ROOK];
castle_rights_t castle_k = color == WHITE? CASTLE_WK: CASTLE_BK;
castle_rights_t castle_q = color == WHITE? CASTLE_WQ: CASTLE_BQ;
if (pos->castle & castle_k) {
if (warn(!(k & kings && r_k & rooks),
"fen warn: wrong %s short castling K or R position (fixed)\n",
colstr[color])) {
warning++;
pos->castle &= ~castle_k;
}
}
if (pos->castle & castle_q) {
if (warn(!(k & kings && r_q & rooks),
"fen warn: wrong %s long castling K or R position (fixed)\n",
colstr[color])) {
warning++;
pos->castle &= ~castle_q;
}
}
}
return pos_ok(pos, 0) ? warning: -1;
}
/**
* startpos - create a game start position
* @pos: a position pointer or NULL
@@ -92,7 +166,6 @@ pos_t *fen2pos(pos_t *pos, const char *fen)
pos_t tmppos;
pos_clear(&tmppos);
/* 1) get piece placement information
*/
for (rank = 7, file = 0; *cur && !isspace(*cur); ++cur) {
@@ -105,9 +178,9 @@ pos_t *fen2pos(pos_t *pos, const char *fen)
file += *cur - '0';
continue;
}
if ((piece = char_color_to_piece(*cur)) != EMPTY) {
if ((piece = piece_from_fen(*cur)) != EMPTY) {
# ifdef DEBUG_FEN
log_i(5, "f=%d r=%d *p=%c piece=%#04x t=%d c=%d\n", file, rank, *cur,
printf("f=%d r=%d *p=%c piece=%#04x t=%d c=%d\n", file, rank, *cur,
piece, PIECE(piece), COLOR(piece));
# endif
pos_set_sq(&tmppos, sq_make(file, rank), piece);
@@ -142,42 +215,50 @@ pos_t *fen2pos(pos_t *pos, const char *fen)
/* 4) en passant
*/
tmppos.en_passant = 0;
if (*cur == '-') {
cur++;
} else {
tmppos.en_passant = sq_make(C2FILE(*cur), C2RANK(*(cur+1)));
tmppos.en_passant = sq_from_string(cur);
cur += 2;
}
SKIP_BLANK(cur);
/* 5) half moves since last capture or pawn move (50 moves rule)
*/
sscanf(cur, "%hd%n", &tmppos.clock_50, &consumed);
tmppos.clock_50 = 0;
tmppos.plycount = 1;
if (sscanf(cur, "%hd%n", &tmp, &consumed) != 1)
goto end; /* early end, ignore w/o err */
tmppos.clock_50 = tmp;
cur += consumed;
SKIP_BLANK(cur);
/* 6) current full move number, starting with 1
*/
sscanf(cur, "%hd", &tmp);
if (sscanf(cur, "%hd", &tmp) != 1)
goto end;
if (tmp <= 0) /* fix faulty numbers*/
tmp = 1;
tmp = 2 * (tmp - 1) + (tmppos.turn == BLACK); /* plies, +1 if black turn */
tmppos.plycount = tmp;
# ifdef DEBUG_FEN
raw_board_print(&tmppos);
# endif
end:
if (warn(err_line, "FEN error line %d: charpos=%d char=%#x(%c)\n",
err_line, err_pos, err_char, err_char)) {
return NULL;
}
if (fen_check(&tmppos) < 0)
return NULL;
if (!pos)
pos = pos_new();
*pos = tmppos;
pos = pos_dup(&tmppos);
//puts("prout 1");
//pos_print_raw(&tmppos, 1);
//puts("prout 2");
# ifdef DEBUG_FEN
pos_print_raw(&tmppos, 1);
# endif
return pos;
}
@@ -209,13 +290,23 @@ char *pos2fen(const pos_t *pos, char *fen)
for (file_t f = FILE_A; f <= FILE_H;) {
square_t sq = sq_make(f, r);
piece_t piece = pos->board[sq];
if (pos->board[sq] == EMPTY) {
# ifdef DEBUG_FEN
printf("r=%d f=%d p=%d pos=%d\n", r, f, piece, cur);
# endif
if (piece == EMPTY) {
int len = 0;
for (; f <= FILE_H && pos->board[sq_make(f, r)] == EMPTY; f++)
len++;
# ifdef DEBUG_FEN
printf("empty=%d char=%c\n", len, '0' + len);
# endif
fen[cur++] = '0' + len;
} else {
fen[cur++] = piece_to_char_color(piece);
fen[cur++] = *piece_to_fen(piece);
# ifdef DEBUG_FEN
printf("f1=%d r=%d c=%c t=%d c=%d \n", f, r,
*(piece_to_fen(piece)), PIECE(piece), COLOR(piece));
# endif
f++;
}
}
@@ -240,7 +331,7 @@ char *pos2fen(const pos_t *pos, char *fen)
/* 4) en passant
*/
if (!pos->en_passant) {
if (pos->en_passant == SQUARE_NONE) {
fen[cur++] = '-';
} else {
fen[cur++] = FILE2C(sq_file(pos->en_passant));

View File

@@ -14,7 +14,7 @@
#ifndef FEN_H
#define FEN_H
#include "position.h"
#include "chessdefs.h"
#define FENSTRLEN 92 /* secure FEN string size */

View File

@@ -44,11 +44,10 @@ uchar bb_rank_attacks[64 * 8];
* 2) shift left result 2 more bits, as bit 0 is unused and already cleared:
* (O <<= 2)
*
* TODO ? create masks excluding slider (eg. bb_diagonal ^ bb_sq[square]),
* TODO ? create masks excluding slider (eg. bb_diag ^ bb_sq[square]),
* to save one operation in hyperbola_moves().
* TODO ? replace rank attack with this idea, mapping rank to diagonal ?
* See http://timcooijmans.blogspot.com/2014/04/
*
*/
void hyperbola_init()
{
@@ -56,7 +55,8 @@ void hyperbola_init()
*/
for (int occ = 0; occ < 64; ++occ) {
for (int file = 0; file < 8; ++file) {
uchar attacks = 0;
int attacks = 0;
//int o = mask << 1; /* skip right square */
/* set f left attacks */
for (int slide = file - 1; slide >= 0; --slide) {
@@ -69,43 +69,60 @@ void hyperbola_init()
for (int slide = file + 1; slide < 8; ++slide) {
int b = bb_sq[slide];
attacks |= b;
if ((occ << 1) & b)
if ((occ << 1) & b) /* piece on b, we stop */
//if ((o & b) == b)
break;
}
bb_rank_attacks[occ * 8 + file] = attacks;
bb_rank_attacks[(occ << 3) + file] = attacks;
//if (((occ << 3) + file) == 171) {
//char str[64], str2[64];
//printf("mask=%x=%s file=%d att=%x=%s\n",
// occ, bitboard_rank_sprint(str, occ), file,
// attacks, bitboard_rank_sprint(str2, attacks));
//}
}
}
}
/**
* hyperbola_rank_moves() - generate rank moves for a sliding piece.
* hyperbola_rank_moves() - get rank moves for a sliding piece.
* @pieces: occupation bitboard
* @sq: piece square
*
* Rank attacks are not handled by HQ, so we do it with a
* Rank attacks are not handled by HQ, so this function uses a pre-calculated
* rank attacks table (@bb_rank_attacks).
*
* @Return: The moves mask for piece
* @Return: bitboard of @piece available pseudo-moves.
*/
static bitboard_t hyperbola_rank_moves(bitboard_t occ, square_t sq)
bitboard_t hyperbola_rank_moves(bitboard_t occ, square_t sq)
{
uint32_t rank = sq & SQ_FILEMASK;
uint32_t file = sq & SQ_RANKMASK;
uint64_t o = (occ >> rank) & 0x7e; /* 01111110 clear bits 0 & 7 */
return ((bitboard_t)bb_rank_attacks[o * 4 + file]) << rank;
u32 rank = sq & SQ_RANKMASK;
u32 file = sq & SQ_FILEMASK;
u64 o = (occ >> rank) & 0176; /* 01111110 clear bits 0 & 7 */
//char zob[128], zob2[128];
//printf("rank_moves: occ=%lx=%s file=%d o=%lx=%s index=%ld=%ld attack=%lx=%s\n", occ,
// bitboard_rank_sprint(zob, occ), file, o,
// bitboard_rank_sprint(zob, o), (o << 2) + file, (o * 4) + file,
// (bitboard_t)bb_rank_attacks[(o << 2) + file] << rank,
// bitboard_rank_sprint(zob2, (bitboard_t)bb_rank_attacks[(o << 2) + file] << rank));
return ((bitboard_t)bb_rank_attacks[(o << 2) + file]) << rank;
}
/**
* hyperbola_moves() - generate hyperbola moves mask for a given sliding piece
* hyperbola_moves() - get hyperbola pseudo-moves for a sliding piece
* @pieces: occupation bitboard
* @sq: piece square
* @mask: mask considered
* @mask: the appropriate mask (pre-calculated)
*
* See https://www.chessprogramming.org/Hyperbola_Quintessence
* This function can be used for files, diagonal, and anti-diagonal attacks.
* @mask is the corresponding pre-calculated table (@bb_sqfile, @bb_sqdiag,
* or @bb_sqanti).
* See https://www.chessprogramming.org/Hyperbola_Quintessence for details.
*
* @Return: The moves mask for piece
* @Return: bitboard of piece available pseudo-moves.
*/
static bitboard_t hyperbola_moves(const bitboard_t pieces, const square_t sq,
bitboard_t hyperbola_moves(const bitboard_t pieces, const square_t sq,
const bitboard_t mask)
{
bitboard_t o = pieces & mask;
@@ -117,32 +134,77 @@ static bitboard_t hyperbola_moves(const bitboard_t pieces, const square_t sq,
& mask;
}
static bitboard_t hyperbola_file_moves(bitboard_t occ, square_t sq)
/**
* hyperbola_file_moves() - get file pseudo-moves for a sliding piece.
* @pieces: occupation bitboard
* @sq: piece square
*
* @Return: bitboard of piece available pseudo-moves on its file.
*/
bitboard_t hyperbola_file_moves(const bitboard_t occ, const square_t sq)
{
return hyperbola_moves(occ, bb_file[sq], sq);
return hyperbola_moves(occ, sq, bb_sqfile[sq]);
}
static bitboard_t hyperbola_diagonal_moves(bitboard_t occ, square_t sq)
/**
* hyperbola_diag_moves() - get diagonal pseudo-moves for a sliding piece.
* @pieces: occupation bitboard
* @sq: piece square
*
* @Return: bitboard of piece available pseudo-moves on its diagonal.
*/
bitboard_t hyperbola_diag_moves(const bitboard_t occ, const square_t sq)
{
return hyperbola_moves(occ, bb_diagonal[sq], sq);
return hyperbola_moves(occ, sq, bb_sqdiag[sq]);
}
static bitboard_t hyperbola_antidiagonal_moves(bitboard_t occ, square_t sq)
/**
* hyperbola_anti_moves() - get anti-diagonal pseudo-moves for a sliding piece.
* @pieces: occupation bitboard
* @sq: piece square
*
* @Return: bitboard of piece available pseudo-moves on its anti-diagonal.
*/
bitboard_t hyperbola_anti_moves(const bitboard_t occ, const square_t sq)
{
return hyperbola_moves(occ, bb_antidiagonal[sq], sq);
return hyperbola_moves(occ, sq, bb_sqanti[sq]);
}
bitboard_t hyperbola_bishop_moves(bitboard_t occ, square_t sq)
/**
* hyperbola_bishop_moves() - get bitboard of bishop pseudo-moves
* @occ: occupation bitboard
* @sq: bishop square
*
* @Return: bitboard of bishop available pseudo-moves.
*/
bitboard_t hyperbola_bishop_moves(const bitboard_t occ, const square_t sq)
{
return hyperbola_diagonal_moves(occ, sq) + hyperbola_antidiagonal_moves(occ, sq);
return hyperbola_diag_moves(occ, sq) | hyperbola_anti_moves(occ, sq);
}
bitboard_t hyperbola_rook_moves(bitboard_t occ, square_t sq)
/**
* hyperbola_rook_moves() - get bitboard of rook pseudo-moves
* @occ: occupation bitboard
* @sq: rook square
*
* @Return: bitboard of rook available pseudo-moves.
*/
bitboard_t hyperbola_rook_moves(const bitboard_t occ, const square_t sq)
{
return hyperbola_file_moves(occ, sq) + hyperbola_rank_moves(occ, sq);
return hyperbola_file_moves(occ, sq) | hyperbola_rank_moves(occ, sq);
}
bitboard_t hyperbola_queen_moves(bitboard_t occ, square_t sq)
/**
* hyperbola_queen_moves() - get bitboard of queen pseudo-moves
* @occ: occupation bitboard
* @sq: queen square
*
* This function is a wrapper over @hyperbola_bishop_moves() and
* @hyperbola_rook_moves().
*
* @Return: bitboard of queen available pseudo-moves.
*/
bitboard_t hyperbola_queen_moves(const bitboard_t occ, const square_t sq)
{
return hyperbola_bishop_moves(occ, sq) + hyperbola_rook_moves(occ, sq);
return hyperbola_bishop_moves(occ, sq) | hyperbola_rook_moves(occ, sq);
}

View File

@@ -18,8 +18,16 @@
#include "bitboard.h"
void hyperbola_init(void);
extern bitboard_t hyperbola_bishop_moves(bitboard_t occ, square_t sq);
extern bitboard_t hyperbola_rook_moves(bitboard_t occ, square_t sq);
extern bitboard_t hyperbola_queen_moves(bitboard_t occ, square_t sq);
bitboard_t hyperbola_rank_moves(const bitboard_t occ, const square_t sq);
bitboard_t hyperbola_moves(const bitboard_t pieces, const square_t sq,
const bitboard_t mask);
bitboard_t hyperbola_file_moves(const bitboard_t occ, const square_t sq);
bitboard_t hyperbola_diag_moves(const bitboard_t occ, const square_t sq);
bitboard_t hyperbola_anti_moves(const bitboard_t occ, const square_t sq);
bitboard_t hyperbola_bishop_moves(const bitboard_t occ, const square_t sq);
bitboard_t hyperbola_rook_moves(const bitboard_t occ, const square_t sq);
bitboard_t hyperbola_queen_moves(const bitboard_t occ, const square_t sq);
#endif /* _HYPERBOLA_QUINTESSENCE_H */

112
src/misc.c Normal file
View File

@@ -0,0 +1,112 @@
/* misc.c - generic/catchall 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 <time.h>
#include "chessdefs.h"
/*
* 1 sec = 1000 millisec
* 1 millisec = 1000 microsec
* 1 microsec = 1000 nanosec
* milli = sec * 1000 + nanosec / 1000000
*
*/
/* We use microsec for all intermediate calcluation */
#define NANO_IN_MICRO 1000ll /* nanosecond in millisecond */
#define MICRO_IN_SEC 1000000ll /* millisecond in second */
#define MILLI_IN_SEC 1000ll /* millisecond in second */
#define MICRO_IN_MILLI 1000ll
//#define NANO_IN_MILLI 1000000ll /* nanosecond in millisecond */
//#define NANO_IN_SEC (NANOS_IN_MS * MS_IN_SEC)
/**
* clock_start - start or restart a clock.
* @clock: &mclock_t clock
*
* Save current time according to @clock type.
*/
void clock_start(mclock_t *clock)
{
clock_gettime(clock->clocktype, &clock->start);
}
/**
* clock_init - initializes a clock type.
* @clock: &mclock_t clock
* @type: clock type
*
* See the clock_gettime(2) for details.
* CLOCK_WALL (a.k.a CLOCK_REALTIME): Wall clock.
* CLOCK_SYSTEM (a.k.a CLOCK_MONOTONIC_RAW): System clock.
* CLOCK_PROCESS (a.k.a CLOCK_PROCESS_CPUTIME_ID): Process CPU clock (incl. threads).
* CLOCK_THREAD (a.k.a CLOCK_THREAD_CPUTIME_ID): Thread CPU clock.
*/
void clock_init(mclock_t *clock, clockid_t type)
{
clock->clocktype = type;
clock_start(clock);
}
/**
* clock_elapsed_μs - return a mclock_t elapsed time in microseconds.
* @clock: &mclock_t clock
*
* The elapsed time is calculated between current time and last clock_start(@clock)
* call time.
*
* @return: microseconds elapsed since last clock_start().
*/
s64 clock_elapsed_μs(mclock_t *clock)
{
struct timespec current;
s64 μs;
clock_gettime(clock->clocktype, &current);
μs = ((s64)current.tv_sec - (s64)clock->start.tv_sec) * MICRO_IN_SEC +
((s64)current.tv_nsec - (s64)clock->start.tv_nsec) / NANO_IN_MICRO ;
return μs;
}
/**
* clock_elapsed_ms - return a mclock_t elapsed time in milliseconds.
* @clock: &mclock_t clock
*
* The elapsed time is calculated between current time and last clock_start(@clock)
* call time.
*
* @return: milliseconds elapsed since last clock_start().
*/
s64 clock_elapsed_ms(mclock_t *clock)
{
return clock_elapsed_μs(clock) / MICRO_IN_MILLI;
}
/**
* clock_elapsed_sec - return a mclock_t elapsed time in seconds.
* @clock: &mclock_t clock
*
* The elapsed time is calculated between current time and last clock_start(@clock)
* call time.
*
* @return: seconds elapsed since last clock_start().
*/
double clock_elapsed_sec(mclock_t *clock)
{
return (double) clock_elapsed_μs(clock) / (double) MICRO_IN_SEC;
}

193
src/move-do.c Normal file
View File

@@ -0,0 +1,193 @@
/* move-do.c - move do/undo.
*
* 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>
*
*/
#include <malloc.h>
#include <ctype.h>
#include <stdlib.h>
#include "brlib.h"
#include "likely.h"
#include "bug.h"
#include "chessdefs.h"
#include "move.h"
#include "position.h"
#include "move-do.h"
/**
* move_do() - do move.
* @pos: &pos_t position
* @move: move to apply
* @state: &state_t address where irreversible changes will be saved
*
* @move is applied to @pos:
* - bitboards and board are updated
* - counters are updated:
* - move count
* - 50-moves rule count
* - flags are possibly updated:
* - castling
* - en-passant
* - captured piece (excl. en-passant)
*
* @return: pos.
*/
pos_t *move_do(pos_t *pos, const move_t move) //, state_t *state)
{
//# ifdef DEBUG_MOVE_DO
// move_print(move, M_PR_NL | M_PR_LONG);
//# endif
//*state = pos->state; /* save irreversible changes */
color_t us = pos->turn, them = OPPONENT(us);
square_t from = move_from(move), to = move_to(move);
piece_t piece = pos->board[from];
piece_t captured = pos->board[to];
piece_type_t ptype = PIECE(piece);
color_t pcolor = COLOR(piece);
piece_t new_piece = piece;
int up = sq_up(us);
++pos->clock_50;
++pos->plycount;
pos->en_passant = SQUARE_NONE;
pos->turn = them;
pos->captured = captured;
bug_on(pcolor != us);
if (is_promotion(move)) {
bug_on(sq_rank(to) != sq_rel_rank(RANK_8, us));
new_piece = MAKE_PIECE(move_promoted(move), us);
}
if (captured != EMPTY) {
pos->clock_50 = 0;
//pos->captured = pos->board[to]; /* save capture info */
bug_on(pos->board[to] == EMPTY || COLOR(pos->captured) != them);
pos_clr_sq(pos, to); /* clear square */
} else if (is_castle(move)) { /* handle rook move */
square_t rookfrom, rookto;
if (is_castle_K(move)) {
rookfrom = sq_rel(H1, us);
rookto = sq_rel(F1, us);
} else {
rookfrom = sq_rel(A1, us);
rookto = sq_rel(D1, us);
}
pos_set_sq(pos, rookto, pos->board[rookfrom]);
pos_clr_sq(pos, rookfrom);
pos->castle = clr_castle(pos->castle, us);
} else if (ptype == PAWN) { /* pawn non capture or e.p. */
pos->clock_50 = 0;
if (is_dpush(move)) /* if pawn double push, set e.p. */
pos->en_passant = from + up;
else if (is_enpassant(move)) { /* clear grabbed pawn */
square_t grabbed = to - up;
pos_clr_sq(pos, grabbed);
}
}
pos_clr_sq(pos, from); /* always clear "from" and set "to" */
pos_set_sq(pos, to, new_piece);
if (ptype == KING)
pos->king[us] = to;
/* update castling flags
* As we always consider flags are valid, we :
* - adjust our flags if relative from is "E1", "A1", H1"
* - adjust opp flags if relative to if "A8", H8"
*/
if (can_castle(pos->castle, us)) { /* do we save time with this test ? */
square_t rel_e1 = sq_rel(E1, us);
square_t rel_a1 = sq_rel(A1, us);
square_t rel_h1 = sq_rel(H1, us);
if (from == rel_e1)
pos->castle = clr_castle(pos->castle, us);
else if (from == rel_a1)
pos->castle = clr_ooo(pos->castle, us);
else if (from == rel_h1)
pos->castle = clr_oo(pos->castle, us);
}
if (can_castle(pos->castle, them)) { /* do we save time with this test ? */
square_t rel_a8 = sq_rel(A8, us);
square_t rel_h8 = sq_rel(H8, us);
if (to == rel_a8)
pos->castle = clr_ooo(pos->castle, them);
else if (to == rel_h8)
pos->castle = clr_oo(pos->castle, them);
}
return pos;
}
/**
* move_undo() - undo move.
* @pos: &pos_t position
* @move: move to undo
* @state: &state_t address where irreversible changes were saved
*
* @move is applied to @pos:
* - bitboards and board are updated
* - previous information is restored:
* - castling
* - en-passant
* - captured piece (excl. en-passant)
* - move count
* - 50-moves rule count
*
* @return: pos.
*/
pos_t *move_undo(pos_t *pos, const move_t move)//, const state_t *state)
{
//# ifdef DEBUG_MOVE
//log(1, "new move: ");
//move_print(0, move, M_PR_NL | M_PR_LONG);
//# endif
color_t them = pos->turn, us = OPPONENT(them);
square_t from = move_from(move), to = move_to(move);
piece_t piece = pos->board[to];
int up = sq_up(them);
if (is_promotion(move))
piece = MAKE_PIECE(PAWN, us);
pos_clr_sq(pos, to); /* always clear "to" ... */
pos_set_sq(pos, from, piece); /* ... and set "from" */
if (PIECE(piece) == KING)
pos->king[us] = from;
if (pos->captured != EMPTY) {
pos_set_sq(pos, to, pos->captured); /* restore captured piece */
} else if (is_castle(move)) { /* make reverse rook move */
square_t rookfrom, rookto;
if (is_castle_K(move)) {
rookfrom = sq_rel(F1, us);
rookto = sq_rel(H1, us);
} else {
rookfrom = sq_rel(D1, us);
rookto = sq_rel(A1, us);
}
pos_set_sq(pos, rookto, pos->board[rookfrom]);
pos_clr_sq(pos, rookfrom);
} else if (is_enpassant(move)) { /* restore grabbed pawn */
square_t grabbed = to + up;
pos_set_sq(pos, grabbed, MAKE_PIECE(PAWN, them));
}
//pos->state = *state; /* restore irreversible changes */
pos->turn = us;
return pos;
}

22
src/move-do.h Normal file
View File

@@ -0,0 +1,22 @@
/* move-do.h - move do/undo.
*
* 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 MOVE_DO_H
#define MOVE_DO_H
#include "position.h"
pos_t *move_do(pos_t *pos, const move_t move);//, state_t *state);
pos_t *move_undo(pos_t *pos, const move_t move);//, const state_t *state);
#endif /* MOVE_DO_H */

480
src/move-gen.c Normal file
View File

@@ -0,0 +1,480 @@
/* move-gen.c - move generation
*
* 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 "bitops.h"
#include "bug.h"
#include "chessdefs.h"
#include "board.h"
#include "bitboard.h"
#include "piece.h"
#include "position.h"
#include "move.h"
#include "hyperbola-quintessence.h"
#include "attack.h"
#include "move-gen.h"
/**
* pseudo_is_legal() - check if a move is legal.
* @pos: position
* @move: move_t to verify
*
* @return: true if move is valid, false otherwise.
*/
bool pseudo_is_legal(const pos_t *pos, const move_t move)
{
color_t us = pos->turn, them = OPPONENT(us);
square_t from = move_from(move), to = move_to(move);
square_t king = pos->king[us];
bitboard_t kingbb = pos->bb[us][KING];
bitboard_t occ = pos_occ(pos);
u64 pinned = mask(from) & pos->blockers;
u64 checkers = pos->checkers;
/* (1) - Castling & King
* For castling, we need to check intermediate squares attacks only.
* Attention: To test if K is in check after moving, we need to exclude
* king from occupation bitboard (to catch king moving away from checker
* on same line) !
*/
if (unlikely(from == king)) {
if (unlikely(is_castle(move))) {
square_t dir = to > from? 1: -1;
if (sq_attackers(pos, occ, from + dir, them))
return false;
}
return !sq_attackers(pos, occ ^ kingbb, to, them);
}
/* (2) - King is in check
* Double-check is already handled in (1), as only K moves were generated
* by pseudo legal move generator.
* Here, allowed dest squares are only on King-checker line, or on checker
* square.
* attacker.
* Special cases:
* e.p., legal if the grabbed pawn is giving check
* pinned piece: always illegal
*/
if (checkers) {
if (pinned)
return false;
if (bb_multiple(checkers))
return false;
square_t checker = ctz64(checkers);
if (is_enpassant(move)) {
return pos->en_passant + sq_up(them) == checker;
}
return true;
//bitboard_t between = bb_between[king][checker] | pos->checkers;
//return mask(to) & between;
}
/* (3) - pinned pieces
* We verify here that pinned piece P stays on line King-P.
*/
if (mask(from) & pos->blockers) {
return bb_line[from][king] & mask(to); /* is to on pinner line ? */
}
/* (4) - En-passant
* pinned pieces are handled in pinned section.
* One case not handled anywhere else: when the two "disappearing" pawns
* would discover a R/Q horizontal check.
*/
if (is_enpassant(move)) {
bitboard_t rank5 = us == WHITE? RANK_5bb: RANK_4bb;
if ((pos->bb[us][KING] & rank5)) {
bitboard_t exclude = mask(pos->en_passant - sq_up(us)) | mask(from);
bitboard_t rooks = (pos->bb[them][ROOK] | pos->bb[them][QUEEN]) & rank5;
while (rooks) {
square_t rook = bb_next(&rooks);
if (hyperbola_rank_moves(occ ^ exclude, rook) & kingbb)
return false;
}
}
}
return true;
}
/**
* pos_next_legal() - get next legal move in position.
* @pos: position
* @movelist: &pseudo-legal movelist
* @start: &int, starting position in @movelist
*
* Get next valid move in @pos move list, from move @start, or MOVE_NONE.
* @start is set to next non-checked move in pseudo-legal list.
* Position pseudo-legal moves must be already calculated before calling this function.
*
* @return: move, or MOVE_NONE if no move.
*/
move_t pos_next_legal(const pos_t *pos, movelist_t *movelist, int *start)
{
const int nmoves = movelist->nmoves;
const move_t *moves = movelist->move;
move_t move;
while (*start < nmoves) {
if (pseudo_is_legal(pos, (move = moves[(*start)++] )))
return move;
}
return MOVE_NONE;
}
/**
* pos_all_legal() - get the list of legal moves from pseudo-legal.
* @pos: position
* @movelist: &pseudo-legal movelist_t
* @dest: &destination movelist_t
*
* The pseudo-legal moves must be already calculated before calling this function.
* No check is done on @dest limits.
*
* @Return: @dest
*/
movelist_t *pos_all_legal(const pos_t *pos, movelist_t *movelist, movelist_t *dest)
{
int tmp = dest->nmoves = 0;
move_t move;
while ((move = pos_next_legal(pos, movelist, &tmp)) != MOVE_NONE)
dest->move[dest->nmoves++] = move;
return dest;
}
/**
* gen_pseudo_king() - generate king pseudo-legal moves.
* @pos: position
* @movelist: &movelist_t array to store pseudo-moves
*
*/
static inline __unused move_t *gen_pseudo_king(move_t *moves, square_t from,
bitboard_t mask)
{
//color_t us = pos->turn;
//square_t from = pos->king[us];
//bitboard_t not_my_pieces = ~pos->bb[us][ALL_PIECES];
bitboard_t to_bb = bb_king_moves(mask, from);
square_t to;
while (moves) {
to = bb_next(&to_bb);
*moves++ = move_make(from, to);
}
return moves;
}
/**
* pos_gen_check_pseudomoves() - generate position pseudo-legal moves when in check
* @pos: position
* @movelist: &movelist_t array to store pseudo-moves
*
* Generate all @pos pseudo moves for player-to-move.
* @movelist is filled with the moves.
*
* Only a few validity checks are done here (i.e. moves are not generated):
* - castling, if king is in check
* - castling, if king passes an enemy-controlled square (not final square).
* When immediately known, a few move flags are also applied in these cases:
* - castling: M_CASTLE_{K,Q}
* - capture (excl. en-passant): M_CAPTURE
* - en-passant: M_EN_PASSANT
* - pawn double push: M_DPUSH
* - promotion: M_PROMOTION
* - promotion and capture
*
* TODO: move code to specific functions (especially castling, pawn push/capture)
*
* @Return: The total number of moves.
*/
/**
* gen_pseudo_escape() - generate position pseudo-legal moves when in check
* @pos: square_t king position
* @mask: possible destinations to consider
* @moves: &move_t array to store pseudo-moves
*
* Generate all @pos pseudo moves for player-to-move, when in check.
* @movelist is filled with the moves.
*
* If king is doubles-checked, only King moves will be generated.
* Otherwise, only moves where destination in between King or checker, or checker
* square.
*
*/
/*
* static void __always_inline gen_pseudo_escape(pos_t *pos, movelist_t *movelist)
* {
* color_t us = pos->turn;
* color_t them = OPPONENT(us);
* square_t king = pos->king[us];
*
* gen_pseudo_king(pos, movelist);
*
* }
*/
/**
* move_make_promotions() - generate all promotions for given pawn and dest.
* @moves: &move_t array where to store moves
* @from: pawn position
* @to: promotion square
*
* Generate all (Q/R/B/N) promotion moves on @to for pawn @from.
*
* @Return: New @moves (incremented by 4).
*/
static inline move_t *move_make_promotions(move_t *moves, square_t from, square_t to)
{
for (piece_type_t pt = QUEEN; pt >= KNIGHT; --pt)
*moves++ = move_make_promote(from, to, pt);
return moves;
}
/**
* pos_gen_pseudomoves() - generate position pseudo-legal moves
* @pos: position
* @movelist: &movelist_t array to store pseudo-moves
*
* Generate all @pos pseudo moves for player-to-move.
* @movelist is filled with the moves.
*
* Only a few validity checks are done here (i.e. moves are not generated):
* - castling, if king is in check
* - castling, if king passes an enemy-controlled square (not final square).
* When immediately known, a few move flags are also applied in these cases:
* - castling: M_CASTLE_{K,Q}
* - capture (excl. en-passant): M_CAPTURE
* - en-passant: M_EN_PASSANT
* - pawn double push: M_DPUSH
* - promotion: M_PROMOTION
* - promotion and capture
*
* TODO: move code to specific functions (especially castling, pawn push/capture)
*
* @Return: The total number of moves.
*/
int pos_gen_pseudomoves(pos_t *pos, movelist_t *movelist)
{
color_t us = pos->turn;
color_t them = OPPONENT(us);
bitboard_t my_pieces = pos->bb[us][ALL_PIECES];
bitboard_t enemy_pieces = pos->bb[them][ALL_PIECES];
bitboard_t dest_squares = ~my_pieces;
bitboard_t occ = my_pieces | enemy_pieces;
bitboard_t empty = ~occ;
bitboard_t from_bb, to_bb;
bitboard_t tmp_bb;
move_t *moves = movelist->move;
//int *nmoves = &movelist->nmoves;
square_t from, to;
square_t king = pos->king[us];
//*nmoves = 0;
/* king - MUST BE FIRST (we stop if doubler check) */
to_bb = bb_king_moves(dest_squares, king);
while(to_bb) {
to = bb_next(&to_bb);
*moves++ = move_make(king, to);
}
if (bb_multiple(pos->checkers)) /* double check, we stop here */
goto finish;
if (pos->checkers) {
/* one checker: we limit destination squares to line between
* checker and king + checker square (think: knight).
*/
square_t checker = ctz64(pos->checkers);
dest_squares &= bb_between[king][checker] | pos->checkers;
enemy_pieces &= dest_squares;
} else {
/* no checker: castling moves
* Attention ! Castling flags are assumed correct
*/
bitboard_t rel_rank1 = bb_rel_rank(RANK_1, us);
//square_t from_square[2] = { E1, E8 }; /* verify king is on E1/E8 */
//bug_on(can_castle(pos->castle, us) && from != from_square[us]);
/* For castle, we check the opponent attacks on squares between from and to.
* To square attack check will be done in gen_is_legal.
*/
if (can_oo(pos->castle, us)) {
bitboard_t occmask = rel_rank1 & (FILE_Fbb | FILE_Gbb);
if (!(occ & occmask)) {
*moves++ = move_make_flags(king, king + 2, M_CASTLE_K);
}
}
if (can_ooo(pos->castle, us)) {
bitboard_t occmask = rel_rank1 & (FILE_Bbb | FILE_Cbb | FILE_Dbb);
if (!(occ & occmask)) { // &&
*moves++ = move_make_flags(king, king - 2, M_CASTLE_Q);
}
}
}
/* sliding pieces */
from_bb = pos->bb[us][BISHOP] | pos->bb[us][QUEEN];
while (from_bb) {
from = bb_next(&from_bb);
to_bb = hyperbola_bishop_moves(occ, from) & dest_squares;
while(to_bb) {
to = bb_next(&to_bb);
*moves++ = move_make(from, to);
}
}
from_bb = pos->bb[us][ROOK] | pos->bb[us][QUEEN];
while (from_bb) {
from = bb_next(&from_bb);
to_bb = hyperbola_rook_moves(occ, from) & dest_squares;
while(to_bb) {
to = bb_next(&to_bb);
*moves++ = move_make(from, to);
}
}
/* knight */
from_bb = pos->bb[us][KNIGHT];
while (from_bb) {
from = bb_next(&from_bb);
to_bb = bb_knight_moves(dest_squares, from);
while(to_bb) {
to = bb_next(&to_bb);
*moves++ = move_make(from, to);
}
}
/* pawn: relative rank and files */
bitboard_t rel_rank8 = bb_rel_rank(RANK_8, us);
bitboard_t rel_rank3 = bb_rel_rank(RANK_3, us);
/* pawn: push */
int shift = sq_up(us);
tmp_bb = bb_shift(pos->bb[us][PAWN], shift) & empty;
to_bb = tmp_bb & ~rel_rank8 & dest_squares; /* non promotion */
while(to_bb) {
to = bb_next(&to_bb);
from = to - shift;
*moves++ = move_make(from, to);
}
to_bb = tmp_bb & rel_rank8 & dest_squares; /* promotions */
while(to_bb) {
to = bb_next(&to_bb);
from = to - shift;
moves = move_make_promotions(moves, from, to);
}
/* possible second push */
to_bb = bb_shift(tmp_bb & rel_rank3, shift) & empty & dest_squares;
while(to_bb) {
to = bb_next(&to_bb);
from = to - shift - shift;
*moves++ = move_make_flags(from, to, M_DPUSH);
}
/* pawn: captures */
/*
* tmp_bb = pawn_attacks_bb(pos->bb[us][PAWN], us) & enemy_pieces;
* //bb_print("FAIL", tmp_bb);
* to_bb = tmp_bb & ~rel_rank8;
* while (to_bb) {
* to = bb_next(&to_bb);
* from_bb = bb_pawn_attacks[them][to] & pos->bb[us][PAWN];
* while (from_bb) {
* from = bb_next(&from_bb);
* *moves++ = move_make(from, to);
* }
* }
* to_bb = tmp_bb & rel_rank8;
* while (to_bb) {
* to = bb_next(&to_bb);
* from_bb = bb_pawn_attacks[them][to] & pos->bb[us][PAWN];
* while (from_bb) {
* from = bb_next(&from_bb);
* moves = move_make_promotions(moves, from, to);
* }
* }
*/
/* pawn: captures left */
bitboard_t filter = ~bb_rel_file(FILE_A, us);
shift = sq_upleft(us);
tmp_bb = bb_shift(pos->bb[us][PAWN] & filter, shift) & enemy_pieces;
to_bb = tmp_bb & ~rel_rank8;
while (to_bb) {
to = bb_next(&to_bb);
from = to - shift;
*moves++ = move_make(from, to);
}
to_bb = tmp_bb & rel_rank8;
while (to_bb) {
to = bb_next(&to_bb);
from = to - shift;
moves = move_make_promotions(moves, from, to);
}
/* pawn: captures right */
filter = ~bb_rel_file(FILE_H, us);
shift = sq_upright(us);
tmp_bb = bb_shift(pos->bb[us][PAWN] & filter, shift) & enemy_pieces;
to_bb = tmp_bb & ~rel_rank8;
while (to_bb) {
to = bb_next(&to_bb);
from = to - shift;
*moves++ = move_make(from, to);
}
to_bb = tmp_bb & rel_rank8;
while (to_bb) {
to = bb_next(&to_bb);
from = to - shift;
moves = move_make_promotions(moves, from, to);
}
/* pawn: en-passant
* TODO: special case when in-check here ?
*/
if ((to = pos->en_passant) != SQUARE_NONE) {
from_bb = bb_pawn_attacks[them][to] & pos->bb[us][PAWN];
while (from_bb) {
from = bb_next(&from_bb);
*moves++ = move_make_enpassant(from, to);
}
}
/*
* to_bb = mask(to);
* /\* if e.p not on file H, we may add an e.p move to "up-left" *\/
* filter = ~bb_rel_file(FILE_A, us);
* shift = sq_upleft(us);
* if (bb_shift(pos->bb[us][PAWN] & filter, shift) & to_bb)
* *moves++ = move_make_enpassant(to - shift, to);
*
* filter = ~bb_rel_file(FILE_H, us);
* shift = sq_upright(us);
* if (bb_shift(pos->bb[us][PAWN] & filter, shift) & to_bb)
* *moves++ = move_make_enpassant(to - shift, to);
* }
*/
/* TODO: add function per piece, and type, for easier debug
*/
finish:
return movelist->nmoves = moves - movelist->move;
}

View File

@@ -1,4 +1,4 @@
/* movegen.h - move generation
/* move-gen.h - move generation
*
* Copyright (C) 2024 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
@@ -21,10 +21,9 @@
#include "piece.h"
#include "move.h"
/**
* gen_all_pseudomoves() - generate all pseudo moves
*
*/
int gen_all_pseudomoves(pos_t *pos);
bool pseudo_is_legal(const pos_t *pos, const move_t move);
move_t pos_next_legal(const pos_t *pos, movelist_t *movelist, int *start);
movelist_t *pos_all_legal(const pos_t *pos, movelist_t *movelist, movelist_t *dest);
int pos_gen_pseudomoves(pos_t *pos, movelist_t *movelist);
#endif /* MOVEGEN_H */

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
/* move.h - move 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.
* Some rights reserved. See COPYING.
*
@@ -15,50 +15,120 @@
#define MOVE_H
#include "chessdefs.h"
#include "position.h"
//#include "pool.h"
#include "piece.h"
#include "board.h"
/* move structure:
* 3 2 2 1 1 1 1 1 1
* 1 5 4 8 7 5 4 2 1 6 5 0
* UUUUUUU FFFFFFF ppp ccc tttttt ffffff
* 3 3 2 2 1 1 1 1 1 1
* 1 0 4 3 8 7 5 4 2 1 6 5 0
* S UUUUUUU FFFFFF ccc ppp tttttt ffffff
*
* bits range type mask get desc
* ffffff 0-5 square_t 3f &63 from
* tttttt 6-11 square_t fc0 (>>6)&63 to
* ccc 12-14 piece_type_t 7000 (>>12)&7 captured
* ppp 15-17 piece_type_t 38000 (>>15)&7 promoted
* FFFFFFF 18-24 N/A 1fc0000 N/A flags
* UUUUUUU 25-31 unused fe000000 N/A future usage ?
* bits len off range type mask get desc
* ffffff 6 0 0-5 square_t 077 &077 from
* tttttt 6 6 6-11 square_t 07700 (>>6) &077 to
* ppp 3 12 12-14 piece_type_t 070000 (>>12) &07 promoted
* ccc 3 15 15-17 piece_type_t 0700000 (>>15) &07 captured
* FFFFFF 6 18 18-23 move_flags_t 077000000 (>>18) &077 N/A flags
* UUUUUUU 7 24 24-30 unused 017700000000 future usage
* S 1 31 31-31 - 020000000000 sign
*/
#define move_t u32
typedef s32 move_t;
#define M_
/* move flags */
#define M_FLAGS_BEG 18
#define M_HAS_FLAGS mask(_M_FLAGS_BEG + 0) /* probably unused */
#define M_CAPTURE mask(_M_FLAGS_BEG + 1)
#define M_ENPASSANT mask(_M_FLAGS_BEG + 2)
#define M_PROMOTION mask(_M_FLAGS_BEG + 3)
#define M_CASTLE_K mask(_M_FLAGS_BEG + 4)
#define M_CASTLE_Q mask(_M_FLAGS_BEG + 5)
#define M_CHECK mask(_M_FLAGS_BEG + 6) /* probably unknown/useless */
/* special move_t values */
#define MOVE_NONE ((move_t) -1)
#define MOVE_NULL ((move_t) 0) /* hack: from = to = A1 */
#define M_FLAGS (M_CAPTURE | M_ENPASSANT | M_PROMOTION | \
M_CASTLE_K | M_CASTLE_Q | M_CHECK)
#define M_NORMAL (~M_FLAGS)
enum {
M_OFF_FROM = 0,
M_OFF_TO = 6,
M_OFF_PROMOTED = 12,
M_OFF_CAPTURED = 15,
M_OFF_FLAGS = 18
};
typedef enum {
M_CAPTURE = mask(M_OFF_FLAGS + 0),
M_ENPASSANT = mask(M_OFF_FLAGS + 1),
M_PROMOTION = mask(M_OFF_FLAGS + 2),
M_CASTLE_K = mask(M_OFF_FLAGS + 3), /* maybe only one ? */
M_CASTLE_Q = mask(M_OFF_FLAGS + 5), /* maybe only one ? */
M_CHECK = mask(M_OFF_FLAGS + 6), /* maybe unknown/useless ? */
M_DPUSH = mask(M_OFF_FLAGS + 7) /* pawn double push */
} move_flags_t;
#define move_set_flags(move, flags) ((move) | (flags))
#define is_capture(m) ((m) & M_CAPTURE)
#define is_enpassant(m) ((m) & M_ENPASSANT)
#define is_promotion(m) ((m) & M_PROMOTION)
#define is_castle(m) ((m) & (M_CASTLE_K | M_CASTLE_Q))
#define is_castle_K(m) ((m) & M_CASTLE_K)
#define is_castle_Q(m) ((m) & M_CASTLE_Q)
#define is_check(m) ((m) & M_CHECK)
#define is_dpush(m) ((m) & M_DPUSH)
#define MOVES_MAX 256
static inline move_t move_make(square_t from, square_t to)
typedef struct __movelist_s {
move_t move[MOVES_MAX];
int nmoves; /* total moves (fill) */
} movelist_t;
static inline square_t move_from(move_t move)
{
return (to << 3) | from;
return move & 077;
}
static inline move_t move_from(move_t move)
static inline square_t move_to(move_t move)
{
return move & 56;
return (move >> M_OFF_TO) & 077;
}
static inline piece_type_t move_promoted(move_t move)
{
return (move >> M_OFF_PROMOTED) & 07;
}
static inline piece_type_t move_captured(move_t move)
{
return (move >> M_OFF_CAPTURED) & 07;
}
static inline move_t move_make(square_t from, square_t to)
{
return (to << M_OFF_TO) | from;
}
static inline move_t move_make_flags(square_t from, square_t to, move_flags_t flags)
{
return move_set_flags(move_make(from, to), flags);
}
static inline move_t move_make_capture(square_t from, square_t to)
{
return move_make_flags(from, to, M_CAPTURE);
}
static inline move_t move_make_enpassant(square_t from, square_t to)
{
return move_make_flags(from, to, M_ENPASSANT);
}
static inline move_t move_make_promote(square_t from, square_t to,
piece_type_t promoted)
{
return move_make_flags(from, to, M_PROMOTION) | (promoted << M_OFF_PROMOTED);
}
static inline move_t move_make_promote_capture(square_t from, square_t to,
piece_type_t promoted)
{
return move_make_promote(from, to, promoted) | M_CAPTURE;
}
static inline move_t move_set_captured(move_t move, piece_type_t captured)
{
return move | (captured << M_OFF_CAPTURED);
}
/* moves_print flags
@@ -67,37 +137,14 @@ static inline move_t move_from(move_t move)
#define M_PR_NCAPT 0x02
#define M_PR_NUM 0x04
#define M_PR_NL 0x08
#define M_UCI 0x10 /* UCI style - e7e8q */
#define M_PR_EVAL 0x20 /* separate captures */
#define M_PR_SEPARATE 0x40 /* separate captures */
#define M_PR_LONG 0x80
typedef struct {
move_t move[MOVES_MAX];
int nmoves; /* total moves (fill) */
int curmove; /* current move (use) */
} movelist_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);
char *move_str(char *dst, const move_t move, __unused const int flags);
void moves_print(movelist_t *moves, int flags);
void move_sort_by_sq(movelist_t *moves);
#endif /* MOVE_H */

View File

@@ -1,74 +0,0 @@
/* movegen.c - move generation
*
* 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 "bitops.h"
#include "bitboard.h"
#include "hyperbola-quintessence.h"
#include "piece.h"
#include "move.h"
//void add_pseudo_move(move_t *pmove, square_t from, square_t to)
//{
// pmov
//}
/**
* gen_all_pseudomoves() - generate all pseudo moves
*
*/
int gen_all_pseudomoves(pos_t *pos)
{
int me = pos->turn, other = OPPONENT(me);
bitboard_t my_pieces = pos->bb[me][ALL_PIECES], notmine = ~my_pieces,
other_pieces = pos->bb[other][ALL_PIECES],
occ = my_pieces | other_pieces, movebits;
int tmp1, tmp2, from, to;
movelist_t moves = pos->moves;
/* sliding pieces */
bit_for_each64(from, tmp1, pos->bb[me][BISHOP]) {
movebits = hyperbola_bishop_moves(occ, from) & notmine;
bit_for_each64(to, tmp2, movebits) {
moves.move[moves.nmoves++] = move_make(from, to);
}
}
bit_for_each64(from, tmp1, pos->bb[me][ROOK]) {
movebits = hyperbola_rook_moves(occ, from) & notmine;
bit_for_each64(to, tmp2, movebits) {
moves.move[moves.nmoves++] = move_make(from, to);
}
}
bit_for_each64(from, tmp1, pos->bb[me][QUEEN]) {
movebits = hyperbola_queen_moves(occ, from) & notmine;
bit_for_each64(to, tmp2, movebits) {
moves.move[moves.nmoves++] = move_make(from, to);
}
}
/* knight */
bit_for_each64(from, tmp1, pos->bb[me][KNIGHT]) {
movebits = bb_knight_moves(occ, from) & notmine;
bit_for_each64(to, tmp2, movebits) {
moves.move[moves.nmoves++] = move_make(from, to);
}
}
/* king */
movebits = bb_king_moves(occ, pos->king[me]) & notmine;
bit_for_each64(to, tmp2, movebits) {
moves.move[moves.nmoves++] = move_make(from, to);
}
/* TODO */
}

View File

@@ -25,22 +25,22 @@
* piece_details
*/
const struct piece_details piece_details[PIECE_MAX] = {
/* Abb AbbC Sym SymC Name start value */
[EMPTY] = { ' ', ' ', " ", " ", " ", 0, 0, 0 },
[W_PAWN] = { 'P', 'P', "", "", "Pawn", P_VAL_OPN, P_VAL_MID, P_VAL_END },
[W_KNIGHT] = { 'N', 'N', "", "", "Knight", N_VAL_OPN, N_VAL_MID, N_VAL_END },
[W_BISHOP] = { 'B', 'B', "", "", "Bishop", B_VAL_OPN, B_VAL_MID, B_VAL_END },
[W_ROOK] = { 'R', 'R', "", "", "Rook", R_VAL_OPN, R_VAL_MID, R_VAL_END },
[W_QUEEN] = { 'Q', 'Q', "", "", "Queen", Q_VAL_OPN, Q_VAL_MID, Q_VAL_END },
[W_KING] = { 'K', 'K', "", "", "King", K_VAL_OPN, K_VAL_MID, K_VAL_END },
[7] = { '7', '7', "<EFBFBD>", "<EFBFBD>", "Inv 7", 0, 0, 0 },
[8] = { '8', '8', "<EFBFBD>", "<EFBFBD>", "Inv 8", 0, 0, 0 },
[B_PAWN] = { 'P', 'p', "", "", "Pawn", P_VAL_OPN, P_VAL_MID, P_VAL_END },
[B_KNIGHT] = { 'N', 'n', "", "", "Knight", P_VAL_OPN, N_VAL_MID, N_VAL_END },
[B_BISHOP] = { 'B', 'b', "", "", "Bishop", P_VAL_OPN, B_VAL_MID, B_VAL_END },
[B_ROOK] = { 'R', 'r', "", "", "Rook", P_VAL_OPN, R_VAL_MID, R_VAL_END },
[B_QUEEN] = { 'Q', 'q', "", "", "Queen", P_VAL_OPN, Q_VAL_MID, Q_VAL_END },
[B_KING] = { 'K', 'k', "", "", "King", P_VAL_OPN, K_VAL_MID, K_VAL_END },
/* cap low fen sym name values */
[EMPTY] = { "", "", "", "", "", 0, 0, 0 },
[W_PAWN] = { "", "", "P", "", "Pawn", P_VAL_OPN, P_VAL_MID, P_VAL_END },
[W_KNIGHT] = { "N", "n", "N", "", "Knight", N_VAL_OPN, N_VAL_MID, N_VAL_END },
[W_BISHOP] = { "B", "b", "B", "", "Bishop", B_VAL_OPN, B_VAL_MID, B_VAL_END },
[W_ROOK] = { "R", "r", "R", "", "Rook", R_VAL_OPN, R_VAL_MID, R_VAL_END },
[W_QUEEN] = { "Q", "q", "Q", "", "Queen", Q_VAL_OPN, Q_VAL_MID, Q_VAL_END },
[W_KING] = { "K", "k", "K", "", "King", K_VAL_OPN, K_VAL_MID, K_VAL_END },
[7] = { "", "", "", "", "", 0, 0, 0 },
[8] = { "", "", "", "", "", 0, 0, 0 },
[B_PAWN] = { "", "", "p", "", "Pawn", P_VAL_OPN, P_VAL_MID, P_VAL_END },
[B_KNIGHT] = { "N", "n", "n", "", "Knight", P_VAL_OPN, N_VAL_MID, N_VAL_END },
[B_BISHOP] = { "B", "b", "b", "", "Bishop", P_VAL_OPN, B_VAL_MID, B_VAL_END },
[B_ROOK] = { "R", "r", "r", "", "Rook", P_VAL_OPN, R_VAL_MID, R_VAL_END },
[B_QUEEN] = { "Q", "q", "q", "", "Queen", P_VAL_OPN, Q_VAL_MID, Q_VAL_END },
[B_KING] = { "K", "k", "k", "", "King", P_VAL_OPN, K_VAL_MID, K_VAL_END },
};
const char pieces_str[6+6+1] = "PNBRQKpnbrqk";
@@ -51,24 +51,24 @@ bool piece_ok(piece_t p)
return !(p & ~(MASK_COLOR | MASK_PIECE)) && pt && (pt <= KING);
}
char piece_to_char(piece_t p)
char *piece_to_cap(piece_t p)
{
return piece_details[p].abbr;
return piece_details[p].cap;
}
char piece_to_char_color(piece_t p)
char *piece_to_char(piece_t p)
{
return piece_details[p].abbr_color;
return piece_details[p].fen;
}
char *piece_to_low(piece_t p)
{
return piece_details[p].low;
}
char *piece_to_sym(piece_t p)
{
return piece_details[PIECE(p)].sym;
}
char *piece_to_sym_color(piece_t p)
{
return piece_details[p].sym_color;
return piece_details[p].sym;
}
char *piece_to_name(piece_t p)
@@ -76,98 +76,20 @@ char *piece_to_name(piece_t p)
return piece_details[p].name;
}
piece_t char_to_piece(char c)
piece_type_t piece_t_from_char(char c)
{
char *p = strchr(pieces_str, c);
return p? (p - pieces_str) % 6 + 1: EMPTY;
return p? (p - pieces_str) % 6 + 1: NO_PIECE_TYPE;
}
piece_t char_color_to_piece(char c)
//piece_type_t piece_from_promotion(char c, color_t color)
//{
// piece_type_t piece = piece_t_from_char(c);
// return piece? SET_COLOR()p? (p - pieces_str) % 6 + 1: NO_PIECE_TYPE;
//}
piece_t piece_from_char(char c)
{
piece_t piece = char_to_piece(c);
return isupper(c)? piece: SET_BLACK(piece);
piece_type_t piece = piece_t_from_char(c);
return isupper(c)? SET_WHITE(piece): SET_BLACK(piece);
}
/*
* 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

@@ -31,11 +31,12 @@ typedef enum {
typedef enum {
ALL_PIECES = 0, /* 'all pieces' bitboard */
NO_PIECE_TYPE = 0,
PAWN = 1, KNIGHT, BISHOP, ROOK, QUEEN, KING,
PIECE_TYPE_MAX = 7 /* bit 4 */
} piece_type_t;
typedef enum {
typedef enum __piece_e {
EMPTY = 0,
NO_PIECE = 0,
W_PAWN = PAWN, W_KNIGHT, W_BISHOP, W_ROOK, W_QUEEN, W_KING,
@@ -70,13 +71,21 @@ typedef enum {
#define K_VAL_END 20000
/* some default values for pieces
* @abbr: char, piece capital letter (used for game notation)
* @abbr_c: char, capital for white, lowercase for black
* char *sym;
* char *sym_c;
* char *name;
* s64 opn_value;
* s64 mid_value;
* s64 end_value;
*/
extern const struct piece_details {
char abbr; /* used for game notation */
char abbr_color; /* lowercase = black */
char *sym; /* used for game notation */
char *sym_color; /* different W & B */
char *name;
char *cap; /* used for game notation */
char *low; /* used also for UCI promotion */
char *fen; /* cap=white, low=black */
char *sym; /* UTF-8 symbol */
char *name; /* piece name */
s64 opn_value; /* value opening */
s64 mid_value; /* value midgame */
s64 end_value; /* value endgame */
@@ -84,7 +93,7 @@ extern const struct piece_details {
extern const char pieces_str[6+6+1]; /* to search from fen/user input */
#define OPPONENT(p) !(p)
#define OPPONENT(color) !(color)
#define MASK_PIECE 0x07 /* 00000111 */
#define MASK_COLOR 0x08 /* 00001000 */
@@ -96,20 +105,26 @@ extern const char pieces_str[6+6+1]; /* to search from fen/user inp
#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))
#define SET_WHITE(p) (piece_t)((p) &= ~MASK_COLOR)
#define SET_BLACK(p) (piece_t)((p) |= MASK_COLOR)
#define SET_COLOR(p, c) (piece_t)(!(c)? SET_WHITE(p): SET_BLACK(p))
extern bool piece_ok(piece_t p);
bool piece_ok(piece_t p);
extern char piece_to_char(piece_t p);
extern char piece_to_char_color(piece_t p);
extern char *piece_to_sym(piece_t p);
extern char *piece_to_sym_color(piece_t p);
extern char *piece_to_name(piece_t p);
char *piece_to_cap(piece_t p);
char *piece_to_low(piece_t p);
char *piece_to_fen(piece_t p);
char *piece_to_sym(piece_t p);
char *piece_to_name(piece_t p);
extern piece_t char_to_piece(char c);
extern piece_t char_color_to_piece(char c);
#define piece_to_char(c) piece_to_fen(c)
//#define piece_to_char_t(p) piece_to_uci(p)
//piece_type_t char_to_piece(char c);
piece_type_t piece_t_from_char(char c);
piece_t piece_from_fen(char c);
#define piece_from_char(c) piece_from_fen(c)
/* use short name or symbol - no effect
*/

View File

@@ -24,32 +24,20 @@
#include "chessdefs.h"
#include "position.h"
#include "bitboard.h"
#include "hyperbola-quintessence.h"
#include "fen.h"
#include "piece.h"
#include "util.h"
//#include "eval.h"
//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 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') *
****************************************************/
#include "board.h"
#include "attack.h"
/**
* pos_new() - allocate a new position
*
* position is not initialized
* Position is not initialized.
* If BUG_ON compilation is defined, the program will fail.
*
* @Return: The new position or NULL.
*/
pos_t *pos_new(void)
{
@@ -60,31 +48,17 @@ pos_t *pos_new(void)
* 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 a copy, allocated with malloc(1), of @pos.
*
* @return: The new position.
* @Return: The new position.
*
* TODO: merge with pos_new - NULL for init, non null for duplicate
*/
pos_t *pos_dup(pos_t *pos)
pos_t *pos_dup(const pos_t *pos)
{
pos_t *newpos = safe_malloc(sizeof(pos_t));
//board = new->board;
*newpos = *pos;
//new->bestmove = NULL;
newpos->node_count = 0;
//new->eval = EVAL_INVALID;
//new->moves_generated = false;
//new->moves_counted = false;
//new->check[WHITE] = new->check[BLACK] = 0;
return newpos;
}
@@ -100,92 +74,379 @@ void pos_del(pos_t *pos)
/**
* pos_clear() - clear a position.
* @pos: &position.
*
* @return: @pos.
*/
pos_t *pos_clear(pos_t *pos)
{
# ifdef DEBUG_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);
# endif
pos->node_count = 0;
pos->turn = 0;
pos->turn = WHITE;
/* move_do/undo position state */
pos->en_passant = SQUARE_NONE;
pos->castle = 0;
pos->clock_50 = 0;
pos->plycount = 0;
pos->en_passant = 0;
pos->castle = 0;
memset(pos->board, 0, sizeof(pos->board));
//pos->curmove = 0;
//pos->eval = 0;
//pos->occupied[WHITE] = 0;
//pos->occupied[BLACK] = 0;
//pos->captured = NO_PIECE;
for (square_t sq = A1; sq <= H8; ++sq)
pos->board[sq] = EMPTY;
for (color_t color = WHITE; color <= BLACK; ++color) {
for (piece_type_t piece = 0; piece <= KING; ++piece)
pos->bb[color][piece] = 0;
pos->controlled[WHITE] = 0;
pos->controlled[BLACK] = 0;
//pos->controlled[color] = 0;
pos->king[color] = SQUARE_NONE;
}
//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);
pos->checkers = 0;
pos->pinners = 0;
pos->blockers = 0;
//pos->moves.nmoves = 0;
return pos;
}
/**
* pos_cmp() - compare two positions..
* @pos1, @pos2: The two &position.
*
* @return: true if equal, false otherwise.
*/
bool pos_cmp(__unused const pos_t *pos1, __unused const pos_t *pos2)
{
#define _cmpf(a) (pos1->a != pos2->a)
bool ret = false;
if (warn_on(_cmpf(node_count)))
goto end;
if (warn_on(_cmpf(turn)))
goto end;
/* move_do/undo position state */
if (warn_on(_cmpf(en_passant)))
goto end;
if (warn_on(_cmpf(castle)))
goto end;
if (warn_on(_cmpf(clock_50)))
goto end;
if (warn_on(_cmpf(plycount)))
goto end;
//if (warn_on(_cmpf(captured)))
// goto end;
for (square_t sq = A1; sq <= H8; ++sq)
if (warn_on(_cmpf(board[sq])))
goto end;
for (color_t color = WHITE; color <= BLACK; ++color) {
for (piece_type_t piece = 0; piece <= KING; ++piece)
if (warn_on(_cmpf(bb[color][piece])))
goto end;
//pos->controlled[color] = 0;
if (warn_on(_cmpf(king[color])))
goto end;
}
if (warn_on(_cmpf(checkers)))
goto end;
if (warn_on(_cmpf(pinners)))
goto end;
if (warn_on(_cmpf(blockers)))
goto end;
/*
* if (warn_on(_cmpf(moves.nmoves)))
* goto end;
* for (int i = 0; i < pos1->moves.nmoves; ++i)
* if (warn_on(_cmpf(moves.move[i])))
* goto end;
*/
ret = true;
end:
return ret;
#undef _cmpf
}
/**
* pos_checkers() - find all checkers on a king.
* @pos: &position
* @color: king color
*
* Get a bitboard of all checkers on @color king.
* Just a wrapper over @sq_attackers().
*
* @return: a bitboard of attackers.
*/
bitboard_t pos_checkers(const pos_t *pos, const color_t color)
{
bitboard_t occ = pos_occ(pos);
return sq_attackers(pos, occ, pos->king[color], OPPONENT(color));
}
/**
* pos_set_checkers_pinners_blockers() - calculate checkers, pinners and blockers.
* @pos: &position
*
* Set position checkers, pinners and blockers on player-to-play king.
* It should be faster than @pos_checkers + @pos_set_pinners_blockers, as
* some calculation will be done once.
*/
void pos_set_checkers_pinners_blockers(pos_t *pos)
{
int us = pos->turn, them = OPPONENT(us);
bitboard_t occ = pos_occ(pos);
bitboard_t attackers;
bitboard_t checkers = 0, blockers = 0, pinners = 0;
bitboard_t targets, tmpcheckers, maybeblockers, tmppinners;
square_t king = pos->king[us];
int pinner;
/* bishop type - we attack with a bishop from king position */
attackers = pos->bb[them][BISHOP] | pos->bb[them][QUEEN];
/* targets is all "target" pieces if K was a bishop */
targets = hyperbola_bishop_moves(occ, king) & occ;
/* checkers = only opponent B/Q */
tmpcheckers = targets & attackers;
checkers |= tmpcheckers;
/* maybe blockers = we remove checkers, to look "behind" */
maybeblockers = targets & ~tmpcheckers;
/* we find second targets, by removing first ones (excl. checkers) */
if (maybeblockers) {
targets = hyperbola_bishop_moves(occ ^ maybeblockers, king) ^ tmpcheckers;
/* pinners = only B/Q */
tmppinners = targets & attackers;
/* blockers = we find occupied squares between pinner and king */
while (tmppinners) {
pinner = bb_next(&tmppinners);
pinners |= mask(pinner);
blockers |= bb_between[pinner][king] & maybeblockers;
}
}
/* same for rook type */
attackers = pos->bb[them][ROOK] | pos->bb[them][QUEEN];
targets = hyperbola_rook_moves(occ, king) & occ;
tmpcheckers = targets & attackers;
checkers |= tmpcheckers;
maybeblockers = targets & ~tmpcheckers;
if (maybeblockers) {
targets = hyperbola_rook_moves(occ ^ maybeblockers, king) ^ tmpcheckers;
tmppinners = targets & attackers;
while (tmppinners) {
pinner = bb_next(&tmppinners);
pinners |= mask(pinner);
blockers |= bb_between[pinner][king] & maybeblockers;
}
}
/* pawns & knights */
checkers |= bb_pawn_attacks[us][king] & pos->bb[them][PAWN];
checkers |= bb_knight[king] & pos->bb[them][KNIGHT];
pos->checkers = checkers;
pos->pinners = pinners;
pos->blockers = blockers;
}
/**
* pos_set_pinners_blockers() - set position pinners and blockers.
* @pos: &position
*
* set position pinners and blockers on player-to-play king.
*/
void pos_set_pinners_blockers(pos_t *pos)
{
color_t color = pos->turn;
square_t king = pos->king[color];
bitboard_t tmp, occ = pos_occ(pos), blockers = 0;
int pinner;
pos->pinners = sq_pinners(pos, king, OPPONENT(pos->turn));
bit_for_each64(pinner, tmp, pos->pinners) {
//bitboard_t blocker =
// warn_on(popcount64(blocker) != 1);
blockers |= bb_between_excl[pinner][king] & occ;
}
pos->blockers = blockers;
return;
}
/**
* pos_king_pinners() - get the "pinners" on a king "pinners".
* @pos: &position
* @color: king color.
*
* get position "pinners" on @color king. Here, pinner means a piece separated from king
* by one piece (any color) only.
* This is just a wrapper over @sq_pinners().
*
* @return: pinners bitboard.
*/
bitboard_t pos_king_pinners(const pos_t *pos, const color_t color)
{
return sq_pinners(pos, pos->king[color], OPPONENT(pos->turn));
}
/**
* pos_king_blockers() - get the pin blockers on a king.
* @pos: &position
* @color: king color.
* @pinners: pinners bitboard.
*
* get @pinners blockers pieces on @color king.
*
* @return: blockers bitboard.
*/
bitboard_t pos_king_blockers(const pos_t *pos, const color_t color, const bitboard_t pinners)
{
bitboard_t tmp, blockers = 0, occ = pos_occ(pos);
square_t pinner, king = pos->king[color];
bit_for_each64(pinner, tmp, pinners) {
//warn_on(popcount64(blocker) != 1);
//if (popcount64(blocker) != 1) {
// printf("n blockers = %d\n", popcount64(blocker));
// bb_print("blockers", blocker);
//}
blockers |= bb_between_excl[pinner][king] & occ;
}
return blockers;
}
/**
* pos_ok() - extensive position consistency check.
* @pos: &position
* @strict: if true, call bug_on() on any error.
*
* Perform some validity check on position @pos:
* - pawns on 1st or 8th rank
* - number of pawns > 8 (per color)
* - total number of pieces > 16 or zero (per color)
* - number of kings != 1 (per color)
* - discrepancy between board and king (per color)
* - discrepancy between piece bitboards and ALL_PIECES bitboards (per color)
* - discrepancy between bitboards and board (per color)
* - side-to-move already checking opponent king
* - side-to-move in check more than twice
* - kings distance is 1
*
* In case of errors, and @strict is true, @bug_on() is called, and program will
* be terminated.
* This function should be called with @strict == false during initialization phase
* (eg after fen parsing), and with @strict == true otherwise (as we have some data
* corruption).
*
* TODO: add more checks:
* - kings attacking each other
*
* @return: (if @strict is false) return true if check is ok, false otherwise.
*/
bool pos_ok(__unused const pos_t *pos, __unused const bool strict)
{
int n, count = 0, bbcount = 0, error = 0;
__unused bitboard_t tmp;
/* pawns on 1st ot 8th rank */
tmp = (pos->bb[WHITE][PAWN] | pos->bb[BLACK][PAWN]) & (RANK_1bb | RANK_8bb);
error += warn_on(tmp);
for (color_t color = WHITE; color <= BLACK; ++color) {
/* pawn count */
n = popcount64(pos->bb[color][PAWN]);
error += warn_on(n > 8);
/* king count */
n = popcount64(pos->bb[color][KING]);
error += warn_on(n != 1);
/* king mismatch with board */
error += warn_on(PIECE(pos->board[pos->king[color]]) != KING);
/* pieces count */
n = popcount64(pos->bb[color][ALL_PIECES]);
error += warn_on(n == 0 || n > 16);
bbcount += n;
}
for (square_t sq = 0; sq < 64; ++sq) {
piece_t piece = pos->board[sq];
__unused bitboard_t match;
if (piece == EMPTY)
continue;
color_t c = COLOR(piece);
piece_type_t p = PIECE(piece);
match = pos->bb[c][p] & mask(sq);
error += warn_on(!match);
count++;
}
/* occupied occupation is different from bitboards */
error += warn_on(count != bbcount);
/* is opponent already in check ? */
error += warn_on(pos_checkers(pos, OPPONENT(pos->turn)));
/* is color to play in check more than twice ? */
error += warn_on(popcount64(pos_checkers(pos, OPPONENT(pos->turn))) > 2);
/* kings distance is less than 2 */
error += warn_on(sq_dist(pos->king[WHITE], pos->king[BLACK]) < 2);
bug_on(strict && error);
return error? false: true;
}
/**
* pos_print() - Print position and fen on stdout.
* @pos: &position
*/
void pos_print(pos_t *pos)
void pos_print(const pos_t *pos)
{
int rank, file;
piece_t pc, *board = pos->board;
char fen[92];
char str[128];
//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) {
pc = board[sq_make(file, rank)];
printf(" %s |", piece_to_sym_color(pc));
}
printf("\n +---+---+---+---+---+---+---+---+\n");
}
printf(" A B C D E F G H\n");
printf("%s\n", pos2fen(pos, fen));
//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("plies=%d clock50=%d\n", pos->plycount, 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]);
board_print(pos->board);
printf("fen %s\n", pos2fen(pos, str));
printf("checkers: %s\n", pos_checkers2str(pos, str, sizeof(str)));
printf("pinners : %s\n", pos_pinners2str(pos, str, sizeof(str)));
printf("blockers: %s\n", pos_blockers2str(pos, str, sizeof(str)));
}
/**
* pos_pieces_print() - Print position pieces
* pos_print_mask() - Print position and fen on stdout, with highlighted squares.
* @pos: &position
* @mask: mask of highlighted squares.
*/
void pos_print_mask(const pos_t *pos, const bitboard_t mask)
{
char fen[92];
board_print_mask(pos->board, mask);
printf("fen %s\n", pos2fen(pos, fen));
}
/**
* pos_print_raw - print simple position board (octal/FEN symbol values)
* @bb: the bitboard
* @type: int, 0 for octal, 1 for fen symbol
*/
void pos_print_raw(const pos_t *pos, const int type)
{
board_print_raw(pos->board, type);
return;
}
/**
* pos_print_pieces() - Print position pieces
* @pos: &position
*/
void pos_pieces_print(pos_t *pos)
void pos_print_pieces(const pos_t *pos)
{
int bit, count, cur;
char pname;
int sq, count, cur;
char *pname;
u64 tmp;
bitboard_t p;
for (int color = WHITE; color <= BLACK; ++color) {
@@ -193,123 +454,17 @@ void pos_pieces_print(pos_t *pos)
p = pos->bb[color][piece];
count = popcount64(p);
cur = 0;
pname = piece_to_char(piece);
printf("%c(0)%s", pname, count? ":": "");
pname = piece_to_char(p);
printf("%s(%d)%s", pname, count, count? ":": "");
if (count) {
bit_for_each64(bit, tmp, p) {
char cf = sq_file(bit), cr = sq_rank(bit);
printf("%s%c%c", cur? ",": "", FILE2C(cf), RANK2C(cr));
bit_for_each64(sq, tmp, p) {
// char cf = sq_file(bit), cr = sq_rank(bit);
printf("%s%s", cur? ",": "", sq_to_string(sq));
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]);
}
}
/*
inline void bitboard_print2_raw(bitboard_t bb1, bitboard_t bb2, char *title)
{
int i;
printf("%s%s", title? title: "", title? ":\n": "");
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));
}
*/
/**
* raw_board_print - print simple board (hex values)
* @bb: the bitboard
*/
void raw_board_print(const pos_t *pos)
{
for (rank_t r = RANK_8; r >= RANK_1; --r) {
for (file_t f = FILE_A; f <= FILE_H; ++f)
printf("%02x ", pos->board[sq_make(f, r)]);
printf(" \n");
}
return;
}
/**
* 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_check() - extensive position consistenci check.
* @pos: &position
*/
/*
* void pos_check(position *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");
* }
* }
* }
*/
/*
* void pos_del(pos_t *pos)
* {
* pieces_del(pos, WHITE);
* pieces_del(pos, BLACK);
* moves_del(pos);
* pool_add(pos_pool, pos);
* }
*/

View File

@@ -18,39 +18,47 @@
#include "brlib.h"
#include "bitops.h"
#include "struct-group.h"
#include "bitboard.h"
#include "chessdefs.h"
#include "bitboard.h"
#include "piece.h"
#include "move.h"
#include "board.h"
typedef struct {
typedef struct __pos_s {
u64 node_count; /* evaluated nodes */
int turn; /* WHITE or BLACK */
u16 clock_50;
u16 plycount; /* plies so far, start is 0 */
square_t en_passant;
castle_rights_t castle;
//eval_t eval;
//int check[2];
//int eval_simple_phase;
//eval_t eval_simple;
//move_t *bestmove;
//bool moves_generated;
//bool moves_counted;
/* data which cannot be recovered by move_undo (like castle_rights, ...),
* or would be expensive to recover (checkers, ...)
* following data can be accessed either directly, either via "movesave"
* structure name.
* For example, pos->en_passant and pos->state.en_passant are the same.
* This allows a memcpy on this data (to save/restore position state).
*/
struct_group_tagged(state_s, state,
square_t en_passant;
castle_rights_t castle;
u16 clock_50;
u16 plycount; /* plies so far, start from 1 */
piece_t captured; /* only for move_undo */
bitboard_t checkers; /* opponent checkers */
bitboard_t pinners; /* opponent pinners */
bitboard_t blockers; /* pieces blocking pin */
);
bitboard_t bb[2][PIECE_TYPE_MAX]; /* bb[0][PAWN], bb[1][ALL_PIECES] */
square_t king[2]; /* dup with bb, faster retrieval */
bitboard_t controlled[2];
//u16 mobility[2];
//struct list_head pieces[2]; /* pieces list, King is first */
//struct list_head moves[2];
piece_t board[BOARDSIZE];
movelist_t moves;
int nmoves;
bitboard_t bb[2][PIECE_TYPE_MAX]; /* bb[0][PAWN], bb[1][ALL_PIECES] */
//bitboard_t controlled[2]; /* unsure */
square_t king[2]; /* dup with bb, faster retrieval */
//movelist_t moves;
} pos_t;
typedef struct state_s state_t;
#define pos_pinned(p) (p->blockers & p->bb[p->turn][ALL_PIECES])
/**
* pos_set_sq - unconditionally set a piece on a square
* @pos: position
@@ -59,13 +67,13 @@ typedef struct {
*
* Both position board and bitboards are modified.
*/
static inline void pos_set_sq(pos_t *pos, square_t square, piece_t piece)
static __always_inline void pos_set_sq(pos_t *pos, square_t square, piece_t piece)
{
color_t color = COLOR(piece);
piece_type_t type = PIECE(piece);
pos->board[square] = piece;
pos->bb[color][type] |= 1 << square;
pos->bb[color][ALL_PIECES] |= 1 << square;
pos->bb[color][type] |= mask(square);
pos->bb[color][ALL_PIECES] |= mask(square);
if (type == KING)
pos->king[color] = square;
}
@@ -77,31 +85,93 @@ static inline void pos_set_sq(pos_t *pos, square_t square, piece_t piece)
*
* Both position board and bitboards are modified.
*/
static inline void pos_clr_sq(pos_t *pos, square_t square)
static __always_inline void pos_clr_sq(pos_t *pos, square_t square)
{
piece_t piece = pos->board[square];
piece_type_t type = PIECE(piece);
color_t color = COLOR(piece);
pos->board[square] = EMPTY;
pos->bb[color][type] &= ~(1 << square);
pos->bb[color][ALL_PIECES] &= ~(1 << square);
pos->bb[color][type] &= ~mask(square);
pos->bb[color][ALL_PIECES] &= ~mask(square);
if (type == KING)
pos->king[color] = SQUARE_NONE;
}
/**
* pos_occ() - get position occupation (all pieces)
* @pos: position
*
* @return: occupation bitboard.
*/
static __always_inline bitboard_t pos_occ(const pos_t *pos)
{
return pos->bb[WHITE][ALL_PIECES] | pos->bb[BLACK][ALL_PIECES];
}
/**
* pos_between_occ() - find occupation between two squares.
* @pos: position
* @sq1: square 1
* @sq2: square 2
*
* @return: bitboard of @betw if between @sq1 and @sq2.
*/
static __always_inline bitboard_t pos_between_occ(const pos_t *pos,
const square_t sq1, const square_t sq2)
{
return bb_between_excl[sq1][sq2] & pos_occ(pos);
}
/**
* pos_between_count() - count occupied squares between two squares.
* @pos: position
* @sq1: square 1
* @sq2: square 2
*
* @return: bitboard of @betw if between @sq1 and @sq2.
*/
static __always_inline int pos_between_count(const pos_t *pos,
const square_t sq1, const square_t sq2)
{
return popcount64(pos_between_occ(pos, sq1, sq2));
}
/**
* pos_checkers2str() - get of string of checkers.
* @p: position
* @str: destination string
* @len: max @str len.
*
* A wrapper over @bb_sq2str() for checkers bitmap.
*
* @return: @str.
*/
#define pos_checkers2str(p, str, len) bb_sq2str(p->checkers, str, len)
#define pos_pinners2str(p, str, len) bb_sq2str(p->pinners, str, len)
#define pos_blockers2str(p, str, len) bb_sq2str(p->blockers, str, len)
//void bitboard_print(bitboard_t bb, char *title);
//void bitboard_print2(bitboard_t bb1, bitboard_t bb2, char *title);
extern pos_t *pos_new();
extern pos_t *pos_dup(pos_t *pos);
extern void pos_del(pos_t *pos);
extern pos_t *pos_clear(pos_t *pos);
pos_t *pos_new();
pos_t *pos_dup(const pos_t *pos);
void pos_del(pos_t *pos);
pos_t *pos_clear(pos_t *pos);
bool pos_cmp(const pos_t *pos1, const pos_t *pos2);
extern void pos_print(pos_t *pos);
extern void pos_pieces_print(pos_t *pos);
void pos_set_checkers_pinners_blockers(pos_t *pos);
void pos_set_pinners_blockers(pos_t *pos);
bitboard_t pos_checkers(const pos_t *pos, const color_t color);
bitboard_t pos_king_pinners(const pos_t *pos, const color_t color);
bitboard_t pos_king_blockers(const pos_t *pos, const color_t color, const bitboard_t );
extern void raw_board_print(const pos_t *pos);
bool pos_ok(const pos_t *pos, const bool strict);
//extern pos_t *pos_startpos(pos_t *pos);
void pos_print(const pos_t *pos);
void pos_print_mask(const pos_t *pos, const bitboard_t mask);
void pos_print_raw(const pos_t *pos, const int type);
void pos_print_pieces(const pos_t *pos);
//void pos_check(position *pos);
#endif /* POSITION_H */

View File

@@ -1,6 +1,6 @@
/* search.c - search good moves.
/* search.c - perft + search.
*
* Copyright (C) 2023 Bruno Raoult ("br")
* Copyright (C) 2023-2024 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
@@ -11,14 +11,111 @@
*
*/
#include <stdio.h>
#include <br.h>
#include <list.h>
#include "debug.h"
#include <brlib.h>
#include "move.h"
#include "eval.h"
#include "position.h"
#include "move-gen.h"
#include "move-do.h"
#include "search.h"
#include "attack.h"
/**
* perft() - Perform perft on position
* @pos: &position to search
* @depth: Wanted depth.
* @ply: perft depth level.
*
* Run perft on a position. This function displays the available moves at @depth
* level for each possible first move, and the total of moves.
*
* This version uses the algorithm:
* if last depth
* return 1;
* gen pseudo-legal moves
* loop for each legal move
* do-move
* perft (depth -1)
* undo-move
*
* @return: total moves found at @depth level.
*/
u64 perft(pos_t *pos, int depth, int ply)
{
int subnodes, movetmp = 0;
u64 nodes = 0;
movelist_t pseudo;
move_t move;
state_t state;
if (depth == 0)
return 1;
pseudo.nmoves = 0;
pos->checkers = pos_checkers(pos, pos->turn);
pos_set_pinners_blockers(pos);
state = pos->state;
pos_gen_pseudomoves(pos, &pseudo);
while ((move = pos_next_legal(pos, &pseudo, &movetmp)) != MOVE_NONE) {
move_do(pos, move);
subnodes = perft(pos, depth - 1, ply + 1);
if (ply == 1) {
char movestr[8];
printf("%s: %d\n", move_str(movestr, move, 0), subnodes);
}
nodes += subnodes;
move_undo(pos, move);
pos->state = state;
}
if (ply == 1)
printf("Total: %lu\n", nodes);
return nodes;
}
/**
* perft_new_pinners() - Perform perft on position
* @pos: &position to search
* @depth: Wanted depth.
* @ply: perft depth level.
*
* Run perft on a position. This function displays the available moves at @depth
* level for each possible first move, and the total of moves.
*
* @return: total moves found at @depth level.
*/
u64 perft_new_pinners(pos_t *pos, int depth, int ply)
{
int subnodes, movetmp = 0;
u64 nodes = 0;
movelist_t pseudo;
move_t move;
state_t state;
if (depth == 0)
return 1;
pseudo.nmoves = 0;
pos_set_checkers_pinners_blockers(pos);
state = pos->state;
pos_gen_pseudomoves(pos, &pseudo);
while ((move = pos_next_legal(pos, &pseudo, &movetmp)) != MOVE_NONE) {
move_do(pos, move);
subnodes = perft_new_pinners(pos, depth - 1, ply + 1);
if (ply == 1) {
char movestr[8];
printf("%s: %d\n", move_str(movestr, move, 0), subnodes);
}
nodes += subnodes;
move_undo(pos, move);
pos->state = state;
}
if (ply == 1)
printf("Total: %lu\n", nodes);
return nodes;
}
/**
* negamax() - search position negamax.
@@ -31,32 +128,34 @@
*
* @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;
}
/*
* 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;
* }
*/
/**
@@ -74,74 +173,76 @@ eval_t negamax(pos_t *pos, int depth, int color)
*
* @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;
}
/*
* 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 )

View File

@@ -1,6 +1,6 @@
/* search.h - search for perfect move.
*
* Copyright (C) 2021 Bruno Raoult ("br")
* Copyright (C) 2021-2024 Bruno Raoult ("br")
* Licensed under the GNU General Public License v3.0 or later.
* Some rights reserved. See COPYING.
*
@@ -16,7 +16,11 @@
#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);
//eval_t negamax(pos_t *pos, int depth, int color);
//eval_t pvs(pos_t *pos, int depth, int alpha, int beta, int color);
u64 perft(pos_t *pos, int depth, int ply);
u64 perft2(pos_t *pos, int depth, int ply);
u64 perft_new_pinners(pos_t *pos, int depth, int ply);
#endif /* SEARCH_H */

65
test/attack-test.c Normal file
View File

@@ -0,0 +1,65 @@
/* attack-test.c - basic square attack tests.
*
* 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 <unistd.h>
#include "chessdefs.h"
#include "fen.h"
#include "position.h"
#include "move-gen.h"
#include "attack.h"
#include "common-test.h"
int main(int __unused ac, __unused char**av)
{
int i = 0;
char *fen;
pos_t *pos;//, *fishpos = pos_new();
bitboard_t checkers, pinners, blockers;
setlinebuf(stdout); /* line-buffered stdout */
bitboard_init();
hyperbola_init();
while ((fen = next_fen(ATTACK))) {
//printf(">>>>> %s\n", test[i]);
printf("original fen %d: [%p][%s]\n", i, fen, fen);
if (!(pos = fen2pos(NULL, fen))) {
printf("wrong fen %d: [%s]\n", i, fen);
continue;
}
pos->checkers = pos_checkers(pos, pos->turn);
pos_set_pinners_blockers(pos);
pos_print(pos);
checkers = pos->checkers;
pinners = pos->pinners;
blockers = pos->blockers;
pos_set_checkers_pinners_blockers(pos);
printf("******* %s\n", cur_comment());
bb_print_multi("checkers", 2, checkers, pos->checkers);
bb_print_multi("pinners", 2, pinners, pos->pinners);
bb_print_multi("blockers", 2, blockers, pos->blockers);
pos_del(pos);
i++;
}
return 0;
}

View File

@@ -1,13 +1,24 @@
//#include "debug.h"
//#include "pool.h"
/* bitboard-test.c - basic bitboard/hyperbola tests.
*
* 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 <string.h>
#include "../src/position.h"
#include "../src/piece.h"
#include "../src/bitboard.h"
#include "../src/hyperbola-quintessence.h"
#include "bug.h"
#include "chessdefs.h"
#include "bitboard.h"
#include "hyperbola-quintessence.h"
int main(int __unused ac, __unused char**av)
{
@@ -19,20 +30,40 @@ int main(int __unused ac, __unused char**av)
"sliding", "diagonal", "antidiagonal", "file", "rank", "knight",
"king"
);
bitboard_print_multi(str, 7,
bb_file[i] | bb_rank[i] |
bb_diagonal[i] | bb_antidiagonal[i],
bb_diagonal[i], bb_antidiagonal[i],
bb_file[i], bb_rank[i],
bb_print_multi(str, 7,
bb_sqfile[i] | bb_sqrank[i] |
bb_sqdiag[i] | bb_sqanti[i],
bb_sqdiag[i], bb_sqanti[i],
bb_sqfile[i], bb_sqrank[i],
bb_knight[i], bb_king[i]);
}
/*
* for (square_t sq = 0; sq < 64; ++sq) {
* sprintf(str, "%2d %#lx %#lx knight", sq, bb_sq[sq], bb_knight[sq]);
* bitboard_print(str, bb_knight[sq]);
* sprintf(str, "%2d %#lx %#lx knight", sq, bb_sq[sq], bb_king[sq]);
* bitboard_print(str, bb_king[sq]);
* }
*/
sprintf(str, "between: %-22s%-22s%-22s%-22s%-22s%-22s",
"a1-a8", "a1-h8", "a1-h1", "a2-a7", "a2-g7", "a2-g2");
bb_print_multi(str, 6,
bb_between[A1][A8], bb_between[A1][H8],
bb_between[A1][H1], bb_between[A2][A7],
bb_between[A2][G7], bb_between[A2][G2]);
sprintf(str, "between: %-22s%-22s%-22s%-22s%-22s%-22s%-22s%-22s",
"c3-c6", "c3-f6", "c3-f3", "c3-e1", "c3-c1", "c3-a1", "c3-a3", "c3-a5");
bb_print_multi(str, 8,
bb_between[C3][C6], bb_between[C3][F6],
bb_between[C3][F3], bb_between[C3][E1],
bb_between[C3][C1], bb_between[C3][A1],
bb_between[C3][A3], bb_between[C3][A5]);
sprintf(str, "between: %-22s%-22s%-22s%-22s%-22s%-22s%-22s%-22s",
"c4-c6", "c4-f6", "c4-f3", "c4-e1", "c4-c1", "c4-a1", "c4-a3", "c4-a5");
bb_print_multi(str, 8,
bb_between[C4][C6], bb_between[C4][F6],
bb_between[C4][F3], bb_between[C4][E1],
bb_between[C4][C1], bb_between[C4][A1],
bb_between[C4][A3], bb_between[C4][A5]);
sprintf(str, "Pwn att: %-22s%-22s%-22s%-22s%-22s%-22s%-22s%-22s",
"White a2", "Black a2", "White h7", "Black h7",
"White c3", "Black c3", "White e5", "Black e5");
bb_print_multi(str, 8,
bb_pawn_attacks[WHITE][A2], bb_pawn_attacks[BLACK][A2],
bb_pawn_attacks[WHITE][H7], bb_pawn_attacks[BLACK][H7],
bb_pawn_attacks[WHITE][C3], bb_pawn_attacks[BLACK][C3],
bb_pawn_attacks[WHITE][E5], bb_pawn_attacks[BLACK][E5]);
return 0;
}

434
test/common-test.h Normal file
View File

@@ -0,0 +1,434 @@
/* common-test.h - common static vars/funcs test
*
* 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 "chessdefs.h"
/* when below FENs are in a struct with selection per test */
#define NOTEST 0
#define FEN 1
#define BITBOARD 2
#define MOVEGEN 4
#define ATTACK 8
#define MOVEDO 16
#define PERFT 32
struct fentest {
int line;
uint modules;
char *comment;
char *fen;
} fentest[] = {
/*
{ __LINE__.
ATTACK,
"checkers: ",
""
},
*/
/* ***************** TEMP TESTS ABOVE ************************** */
{ __LINE__, MOVEGEN | MOVEDO | PERFT,
"illegal white e.p.",
"3k4/8/5K2/3pP3/8/2b5/8/8 w - d6 0 1",
},
{ __LINE__, PERFT,
"only K, pawn push and ep moves",
"3k4/8/8/3pPK2/8/8/8/8 w - d6 0 1"
},
{ __LINE__, MOVEGEN | MOVEDO | PERFT,
"illegal white e.p.",
"3k4/8/8/2qpPK2/8/8/8/8 w - d6 0 1",
},
{ __LINE__, MOVEGEN | MOVEDO | PERFT,
"illegal black e.p.",
"8/8/8/8/2QPpk2/8/8/3K4 b - d3 0 1",
},
{ __LINE__, MOVEGEN | MOVEDO | PERFT,
"illegal black e.p.",
"8/8/2B5/8/3Pp3/5k2/8/3K4 b - d3 0 1",
},
{ __LINE__, MOVEGEN | MOVEDO | PERFT,
"legal white e.p.",
"1K1k4/8/8/3pP3/8/6b1/8/8 w - d6 0 1",
},
{ __LINE__, MOVEGEN | MOVEDO | PERFT,
"legal black e.p.",
"8/8/6B1/8/3Pp3/8/8/1k1K4 b - d3 0 1",
},
{ __LINE__, MOVEGEN | MOVEDO | PERFT,
"illegal e.p.",
"1nbqkbn1/ppp1pppp/8/r1rpP1K1/8/8/PPPP1PPP/RNBQ1BNR w - d6 0 1",
},
{ __LINE__, MOVEGEN | MOVEDO | PERFT,
"illegal e.p. bug perft at depth 4",
"1nbqkbn1/ppp2ppp/4p3/r1rpP3/6K1/P7/1PPP1PPP/RNBQ1BNR b - - 1 2"
},
/*
* { __LINE__, MOVEGEN | MOVEDO | PERFT,
* "illegal e.p. bug perft depth 3",
* "1nbqkbn1/ppp2ppp/4p3/2rpP3/r5K1/P7/1PPP1PPP/RNBQ1BNR w - - 2 3"
* },
* { __LINE__, MOVEGEN | MOVEDO | PERFT,
* "illegal e.p. bug perft depth 2",
* "1nbqkbn1/ppp2ppp/4p3/2rpP3/r4PK1/P7/1PPP2PP/RNBQ1BNR b - - 0 3"
* },
* { __LINE__, MOVEGEN | MOVEDO | PERFT | PERFT,
* "illegal e.p. bug perft depth 1 - fixed",
* "1nb1kbn1/ppp2ppp/4p3/2rpP1q1/r4PK1/P7/1PPP2PP/RNBQ1BNR w - - 1 4"
* },
*/
{ __LINE__, ATTACK,
"only 3 K moves (but impossible situation)",
"1k6/8/8/8/8/8/8/r2K3r w - - 0 1"
},
{ __LINE__, ATTACK,
"checkers: a8 h8",
"R2k3R/8/8/8/8/8/8/1K6 b - - 0 1"
},
{ __LINE__, ATTACK,
"checkers: b3 g3",
"1k6/8/8/8/8/1r1K2r1/8/8 w - - 0 1"
},
{ __LINE__, ATTACK,
"checkers: b6 g6",
"8/8/1R1k2R1/8/8/8/8/1K6 b - - 0 1"
},
{ __LINE__, ATTACK,
"checkers: g2 g7",
"8/k5r1/8/8/6K1/8/6r1/8 w - - 0 1"
},
{ __LINE__, ATTACK,
"checkers: g2 g7",
"8/6R1/8/6k1/8/8/K5R1/8 b - - 0 1"
},
{ __LINE__, ATTACK,
"checkers: d5 e3, pinners: none (2 pieces between attacker & K)",
"3k4/8/8/3r3b/b7/1N2nn2/2n1B3/rNBK1Rbr w - - 0 1"
},
{ __LINE__, ATTACK,
"checkers: d4 e6 pinners: h4 a5 a8 h8",
"Rn1k1r1R/4b3/1n2N3/B7/3R3B/8/8/3K4 b - - 0 1"
},
{ __LINE__, ATTACK,
"checkers: d5 e3, pinners: a1 h1 a4 h5",
"3k4/8/8/3r3b/b7/1N2n3/4B3/rN1K1R1r w - - 0 1"
},
{ __LINE__, MOVEGEN | MOVEDO | PERFT,
"only pawn captures",
"4k3/8/2p1p3/2PpP3/8/pp4pp/PP4PP/4K3 w - d6 0 1"
},
{ __LINE__, FEN | ATTACK,
"checker: h4",
"4k3/8/8/8/7b/8/8/4K3 w - - 0 1"
},
// First game moves
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"startpos",
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
},
//{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
// "1.e3 - perft bug",
// "rnbqkbnr/pppppppp/8/8/8/4P3/PPPP1PPP/RNBQKBNR b KQkq - 0 1"
//},
//{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT | PERFT,
// "1.e3 Nc6 - perft bug",
// "r1bqkbnr/pppppppp/2n5/8/8/4P3/PPPP1PPP/RNBQKBNR w KQkq - 1 2"
//},
//{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT | PERFT,
// "1.e3 Nc6 2.Ke2 - perft bug",
// "r1bqkbnr/pppppppp/2n5/8/8/4P3/PPPPKPPP/RNBQ1BNR b kq - 2 2"
//},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"1.e3 Nc6 2.Ke2 Nd4+ - perft bug",
"r1bqkbnr/pppppppp/8/8/3n4/4P3/PPPPKPPP/RNBQ1BNR w kq - 3 3"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"1.e4",
"rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"1.Nh3",
"rnbqkbnr/pppppppp/8/8/8/7N/PPPPPPPP/RNBQKB1R b KQkq - 1 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"1.e4 e5 2.Nf3 Nc6",
"r1bqkbnr/pp1ppppp/2n5/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 0 1"
},
// castling test
// both can castle queen only
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"no Q castling",
"r3k2r/8/3B4/8/8/3b4/8/R3K2R w KQkq - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"no castling, 2 mates in 1",
"r3k2r/8/3BB3/8/8/3bb3/8/R3K2R w KQkq - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"r2bkb1r/8/8/8/8/3bb3/8/R2BKB1R w KQkq - 0 1"
},
//
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"4 castle possible, only K+R",
"r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1"
},
//
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"only kings on A1/A8, white to play",
"k7/8/8/8/8/8/8/K7 w - - 0 1"
},
//
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"only one move possible (Pf2xBg3)",
"k7/8/8/1p1p4/pPpPp3/P1PpPpb1/NBNP1P2/KBB1B3 w - - 0 1"
},
//
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"only 2 moves possible (Ph5xg6 e.p., Ph5-h6)",
"k7/8/8/1p1p2pP/pPpPp3/P1PpPp2/NBNP1P2/KBB1B3 w - g6 0 1"
},
//
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"2 Kings, W/B/ pawns on 7th for promotion",
"k4n2/4P3/8/8/8/8/4p3/K4N2 w - - 0 1"
},
// white castled, and can e.p. on c6 black can castle
// white is a pawn down
// white has 36 moves: P=11 + 1 e.p. N=6+3 B=5+5 R=1 Q=3 K=1 + 1 e.p.
// black has 33 moves: P=11 N=2+7 B=5 R=3 Q=3 K=1 + castle
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"rnbqk2r/pp1pbpp1/7p/2pPp3/4n3/3B1N2/PPP2PPP/RNBQ1RK1 w kq c6 0 7"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"4k3/4p3/8/b7/1BR1p2p/1Q3P2/5N2/4K3 w - - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"r1bq1rk1/pppp1ppp/2n2n2/4p3/2B1P3/3PPN2/PPP3PP/RN1QK2R b KQ - 1 7"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"6k1/6pp/R2p4/p1p5/8/1P1r3P/6P1/6K1 b - - 3 3"
},
// some of tests below are from:
// - Rodent IV
// - https://www.chessprogramming.net/perfect-perft/
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"8/2p5/3p4/Kp5r/1R3p1k/8/4P1P1/8 w - - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"4rrk1/pp1n3p/3q2pQ/2p1pb2/2PP4/2P3N1/P2B2PP/4RRK1 b - - 7 19"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"rq3rk1/ppp2ppp/1bnpb3/3N2B1/3NP3/7P/PPPQ1PP1/2KR3R w - - 7 14"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"r1bq1r1k/1pp1n1pp/1p1p4/4p2Q/4Pp2/1BNP4/PPP2PPP/3R1RK1 w - - 2 14"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"r3r1k1/2p2ppp/p1p1bn2/8/1q2P3/2NPQN2/PPP3PP/R4RK1 b - - 2 15"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"1rbqk1nr/p3ppbp/2np2p1/2p5/1p2PP2/3PB1P1/PPPQ2BP/R2NK1NR b KQk - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"r1bqk2r/pp1p1ppp/2n1pn2/2p5/1bPP4/2NBP3/PP2NPPP/R1BQK2R b KQkq - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"rnb1kb1r/ppp2ppp/1q2p3/4P3/2P1Q3/5N2/PP1P1PPP/R1B1KB1R b KQkq - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"r1b2rk1/pp2nppp/1b2p3/3p4/3N1P2/2P2NP1/PP3PBP/R3R1K1 b - - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"n1q1r1k1/3b3n/p2p1bp1/P1pPp2p/2P1P3/2NBB2P/3Q1PK1/1R4N1 b - - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"r1bq1r1k/b1p1npp1/p2p3p/1p6/3PP3/1B2NN2/PP3PPP/R2Q1RK1 w - - 1 16"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"3r1rk1/p5pp/bpp1pp2/8/q1PP1P2/b3P3/P2NQRPP/1R2B1K1 b - - 6 22"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"r1q2rk1/2p1bppp/2Pp4/p6b/Q1PNp3/4B3/PP1R1PPP/2K4R w - - 2 18"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"4k2r/1pb2ppp/1p2p3/1R1p4/3P4/2r1PN2/P4PPP/1R4K1 b - - 3 22"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"3q2k1/pb3p1p/4pbp1/2r5/PpN2N2/1P2P2P/5PP1/Q2R2K1 b - - 4 26"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"2r5/8/1n6/1P1p1pkp/p2P4/R1P1PKP1/8/1R6 w - - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"r2q1rk1/1b1nbppp/4p3/3pP3/p1pP4/PpP2N1P/1P3PP1/R1BQRNK1 b - - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"6k1/5pp1/7p/p1p2n1P/P4N2/6P1/1P3P1K/8 w - - 0 35"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"r4rk1/1pp1q1pp/p2p4/3Pn3/1PP1Pp2/P7/3QB1PP/2R2RK1 b - - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"",
"1k6/1b6/8/8/7R/8/8/4K2R b K - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"Illegal ep move #1",
"3k4/3p4/8/K1P4r/8/8/8/8 b - - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"Illegal ep move #2",
"8/8/4k3/8/2p5/8/B2P2K1/8 w - - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"EP Capture Checks Opponent",
"8/8/1k6/2b5/2pP4/8/5K2/8 b - d3 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"Short Castling Gives Check",
"5k2/8/8/8/8/8/8/4K2R w K - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"Long Castling Gives Check",
"3k4/8/8/8/8/8/8/R3K3 w Q - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"Castle Rights",
"r3k2r/1b4bq/8/8/8/8/7B/R3K2R w KQkq - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"Castling Prevented",
"r3k2r/8/3Q4/8/8/5q2/8/R3K2R b KQkq - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"Promote out of Check",
"2K2r2/4P3/8/8/8/8/8/3k4 w - - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"Discovered Check",
"8/8/1P2K3/8/2n5/1q6/8/5k2 b - - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"Promote to give check",
"4k3/1P6/8/8/8/8/K7/8 w - - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"Under Promote to give check",
"8/P1k5/K7/8/8/8/8/8 w - - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"Self Stalemate",
"K1k5/8/P7/8/8/8/8/8 w - - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"Stalemate & Checkmate",
"8/k1P5/8/1K6/8/8/8/8 w - - 0 1"
},
{ __LINE__, FEN | MOVEGEN | MOVEDO | PERFT,
"Stalemate & Checkmate",
"8/8/2k5/5q2/5n2/8/5K2/8 b - - 0 1"
},
{ __LINE__, MOVEDO | PERFT,
"simple movedo/undo: only 2 W knights",
"8/1k6/8/8/8/8/6K1/1NN5 w - - 0 1"
},
{ __LINE__, MOVEDO | PERFT,
"simple movedo/undo: only 2 W knights",
"5n2/1k6/8/8/5K2/8/P7/1N6 w - - 0 1"
},
{ __LINE__, FEN,
"illegal EP and castle flags, fix-able by fen parser, SF crash",
"4k3/8/8/8/7B/8/8/4K3 w KQkq e6 0 1"
},
{ __LINE__, FEN,
"illegal, SF crash",
"4k3/8/8/8/7b/8/8/4K3 b - - 0 1"
},
{ __LINE__, FEN,
"illegal, SF crash",
"2r1k3/3B4/8/8/8/8/8/4K3 w - - 0 1"
},
{ __LINE__, FEN,
"illegal, SF crash",
"2r1k3/3P4/8/8/8/8/8/4K3 w - - 0 1"
},
{ __LINE__, 0, NULL, NULL }
};
static int cur = -1;
static char *next_fen(uint module)
{
cur++;
while (fentest[cur].fen && !(fentest[cur].modules & module))
cur++;
return fentest[cur].fen;
}
static __unused char* cur_comment()
{
return fentest[cur].comment;
}
static __unused int cur_line()
{
return fentest[cur].line;
}

View File

@@ -1,30 +1,51 @@
#include "debug.h"
#include "pool.h"
/* fen-test.c - basic fen tests.
*
* 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 "../src/position.h"
#include "../src/fen.h"
#include <stdio.h>
int main(int ac, char**av)
#include "chessdefs.h"
#include "bitboard.h"
#include "position.h"
#include "fen.h"
#include "common-test.h"
int main(__unused int ac, __unused char**av)
{
pos_t *pos;
const char *fen;
char revfen[128];
int comp;
//debug_init(5, stderr, true);
//pos_pool_init();
pos = pos_new();
if (ac == 1) {
fen = startfen;
startpos(pos);
} else {
fen = av[1];
fen2pos(pos, fen);
setlinebuf(stdout); /* line-buffered stdout */
bitboard_init();
while ((fen = next_fen(FEN))) {
printf("***** [%s] ", fen);
fflush(stdout);
if (!(pos = fen2pos(NULL, fen))) {
printf("**INVALID\n");
} else {
//pos_print(pos);
pos2fen(pos, revfen);
if (!strcmp(fen, revfen)) {
printf("OK\n");
} else {
//printf("fen = [%s]\nrev = [%s]", fen, revfen);
printf("-> [%s] **FIXED\n",revfen);
pos_print_raw(pos, 1);
}
pos_del(pos);
}
}
pos_print(pos);
pos2fen(pos, revfen);
//printf("reverse fen=[%s]\n", pos2fen(pos, NULL));
comp = strcmp(fen, revfen);
printf("compare=%d - %s\n", comp, comp? "NOK": "OK");
}

93
test/movedo-test.c Normal file
View File

@@ -0,0 +1,93 @@
/* movedo-test.c - basic movedo/undo tests.
*
* 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 <unistd.h>
#include "chessdefs.h"
#include "fen.h"
#include "position.h"
#include "move.h"
#include "move-do.h"
#include "move-gen.h"
#include "common-test.h"
int main(int __unused ac, __unused char**av)
{
int i = 0, test_line;
char *fen, movebuf[8];;
pos_t *pos, *savepos;
movelist_t pseudo;
move_t move;
setlinebuf(stdout); /* line-buffered stdout */
bitboard_init();
hyperbola_init();
while ((fen = next_fen(MOVEDO))) {
test_line = cur_line();
if (!(pos = fen2pos(NULL, fen))) {
printf("wrong fen %d: [%s]\n", i, fen);
continue;
}
pos->checkers = pos_checkers(pos, pos->turn);
pos_set_pinners_blockers(pos);
pos_gen_pseudomoves(pos, &pseudo);
savepos = pos_dup(pos);
state_t state = pos->state;
int tmp = 0, j = 0;
while ((move = pos_next_legal(pos, &pseudo, &tmp)) != MOVE_NONE) {
//pos_print(pos);
//printf("i=%d j=%d turn=%d move=[%s]\n", i, j, pos->turn,
// move_str(movebuf, move, 0));
//move_p
move_do(pos, move);
//pos_print(pos);
//fflush(stdout);
if (!pos_ok(pos, false)) {
printf("*** fen %d move %d [%s] invalid position after move_do\n",
test_line, j, movebuf);
exit(0);
}
//printf("%d/%d move_do check ok\n", i, j);
move_undo(pos, move);
pos->state = state;
if (!pos_ok(pos, false)) {
printf("*** fen %d move %d [%s] invalid position after move_undo\n",
test_line, j, movebuf);
exit(0);
}
if (pos_cmp(pos, savepos) != true) {
printf("*** fen %d move %d [%s] position differ after move_{do,undo}\n",
test_line, j, movebuf);
exit(0);
}
//fflush(stdout);
//pos_check(pos, true);
//printf("%d/%d move_undo check ok\n", i, j);
j++;
}
printf("fen %d line=%d [%s] %d move_{do,undo} OK\n", i, test_line, fen, j);
pos_del(savepos);
pos_del(pos);
i++;
}
return 0;
}

288
test/movegen-test.c Normal file
View File

@@ -0,0 +1,288 @@
/* movegen-test.c - basic movegen tests.
*
* 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 <unistd.h>
#include "chessdefs.h"
#include "fen.h"
#include "move-gen.h"
#include "position.h"
#include "common-test.h"
#define RD 0
#define WR 1
/**
* return write pipd fd
*/
static FILE *open_stockfish()
{
int rpipe[2], wpipe[2];
FILE *out_desc;
pid_t pid;
if ((pipe(rpipe) < 0) || (pipe(wpipe) < 0)) {
perror("pipe");
return NULL;
}
if ((pid = fork()) < 0) {
perror("fork");
return NULL;
}
if (!pid) { /* stockfish */
setvbuf(stdin, NULL, _IOLBF, 0);
setvbuf(stdout, NULL, _IOLBF, 0);
setvbuf(stderr, NULL, _IOLBF, 0);
dup2(wpipe[RD], STDIN_FILENO);
dup2(rpipe[WR], STDOUT_FILENO);
dup2(rpipe[WR], STDERR_FILENO);
close(wpipe[RD]);
close(wpipe[WR]);
close(rpipe[RD]);
close(rpipe[WR]);
if (execlp("stockfish", "stockfish", NULL) == -1) {
perror("execlp");
return NULL;
}
return 0; /* not reached */
}
/* us */
dup2(rpipe[RD], STDIN_FILENO);
setvbuf(stdin, NULL, _IOLBF, 0);
close(wpipe[RD]);
close(rpipe[RD]);
close(rpipe[WR]);
out_desc = fdopen(wpipe[WR], "w");
setvbuf(out_desc, NULL, _IOLBF, 0);
return out_desc;
}
static void send_stockfish_fen(FILE *desc, pos_t *pos, movelist_t *movelist, char *fen)
{
char *buf = NULL;
int count, __unused mycount = 0, fishcount;
size_t alloc = 0;
ssize_t buflen;
pos_clear(pos);
move_t *moves = movelist->move;
int *nmoves = &movelist->nmoves;
*nmoves = 0;
//char nodescount[] = "Nodes searched";
//printf("nmoves = %d\n", nmoves);
fflush(stdout);
//sprintf(str, "stockfish \"position fen %s\ngo perft depth\n\"", fen);
fprintf(desc, "position fen %s\ngo perft 1\n", fen);
//fflush(desc);
while ((buflen = getline(&buf, &alloc, stdin)) > 0) {
buf[--buflen] = 0;
if (buflen == 0)
continue;
if (sscanf(buf, "Nodes searched: %d", &fishcount) == 1) {
break;
}
//printf("%d: %s\n", line++, buf);
if (sscanf(buf, "%*4s: %d", &count) == 1) {
square_t from = sq_from_string(buf);
square_t to = sq_from_string(buf + 2);
mycount += count;
//printf("move found: %c%c->%c%c %s->%s count=%d\n",
// buf[0], buf[1], buf[2], buf[3],
// sq_to_string(from), sq_to_string(to),
// count);
moves[(*nmoves)++] = move_make(from, to);
} else if (sscanf(buf, "%*5s: %d", &count) == 1) {
square_t from = sq_from_string(buf);
square_t to = sq_from_string(buf + 2);
piece_type_t promoted = piece_t_from_char(*(buf + 4));
mycount += count;
//printf("move found: %c%c->%c%c %s->%s count=%d\n",
// buf[0], buf[1], buf[2], buf[3],
// sq_to_string(from), sq_to_string(to),
// count);
moves[(*nmoves)++] = move_make_promote(from, to, promoted);
}
}
//pos->moves.nmoves = nmoves;
// printf("fishcount=%d mycount=%d\n", fishcount, mycount);
free(buf);
}
static __unused bool movelists_equal(movelist_t *fish, movelist_t *me)
{
move_t *m1 = fish->move, *m2 = me->move;
int n1 = fish->nmoves, n2 = me->nmoves;
int mask = 077777;
if (n1 != n2)
return false;
for (int cur = 0; cur < n1; ++cur) {
if ((m1[cur] & mask) != (m2[cur] & mask))
return false;
}
return true;
}
static __unused void compare_moves(movelist_t *fish, movelist_t *me)
{
char str1[1024] = {0}, str2[1024] = {0}, tmpstr[1024];
char *skip = " ";
move_t *m1 = fish->move;
move_t *m2 = me->move;
int n1 = fish->nmoves;
int n2 = me->nmoves;
#define f(c) move_from(c)
#define t(c) move_to(c)
for (move_t *c1 = m1, *c2 = m2; (c1 - m1 < n1) || (c2 - m2 < n2);) {
// square_t f1 = move_from(*c1); square_t t1 = move_to(*c1);
// square_t f2 = move_from(*c2); square_t t2 = move_to(*c2);
/* no more move in c2 */
if (c2 - m2 >= n2) {
while (c1 - m1 < n1) {
sprintf(tmpstr, " %s-%s", sq_to_string(f(*c1)), sq_to_string(t(*c1)));
strcat (str1, tmpstr);
c1++;
}
break;
}
if (c1 - m1 >= n1) {
while (c2 - m2 < n2) {
sprintf(tmpstr, " %s-%s", sq_to_string(f(*c2)), sq_to_string(t(*c2)));
strcat (str2, tmpstr);
c2++;
}
break;
}
/* missing move in c2 */
if (f(*c1) < f(*c2) ||
(f(*c1) == f(*c2) && t(*c1) < t(*c2))) {
strcat(str2, skip);
sprintf(tmpstr, " %s-%s", sq_to_string(f(*c1)), sq_to_string(t(*c1)));
strcat (str1, tmpstr);
while ((c1 - m1 < n1) && (f(*c1) < f(*c2) ||
(f(*c1) == f(*c2) && t(*c1) < t(*c2)))) {
c1++;
}
continue;
}
/* missing move in c1 */
if (f(*c1) > f(*c2) ||
(f(*c1) == f(*c2) && t(*c1) > t(*c2))) {
strcat(str1, skip);
sprintf(tmpstr, " %s-%s", sq_to_string(f(*c2)), sq_to_string(t(*c2)));
strcat (str2, tmpstr);
while ((c2 - m2 < n2) && (f(*c1) > f(*c2) ||
(f(*c1) == f(*c2) && t(*c1) > t(*c2)))) {
c2++;
}
continue;
}
sprintf(tmpstr, " %s-%s", sq_to_string(f(*c1)), sq_to_string(t(*c1)));
strcat(str1, tmpstr);
strcat(str2, tmpstr);
c1++, c2++;
}
printf("F(%2d): %s\nM(%2d): %s\n", n1, str1, n2, str2);
}
int main(int __unused ac, __unused char**av)
{
int i = 0;
FILE *outfd;
char *fen;
pos_t *pos, *fishpos = pos_new();
movelist_t pseudo, legal, fishmoves;
//bitboard_t wrong = 0x5088000040, tmp, loop;
//bit_for_each64(loop, tmp, )
//printf("fishpos 1=%p\n", fishpos);
setlinebuf(stdout); /* line-buffered stdout */
bitboard_init();
hyperbola_init();
outfd = open_stockfish();
while ((fen = next_fen(MOVEGEN))) {
//printf(">>>>> %s\n", test[i]);
//printf("fishpos 2=%p\n", fishpos);
//printf("original fen %d: [%p][%s]\n", i, fen, fen);
if (!(pos = fen2pos(NULL, fen))) {
printf("wrong fen %d: [%s]\n", i, fen);
continue;
}
/* print movelists */
send_stockfish_fen(outfd, fishpos, &fishmoves, fen);
pos_set_checkers_pinners_blockers(pos);
pos_gen_pseudomoves(pos, &pseudo);
//moves_print(&pseudo, 0);
pos_all_legal(pos, &pseudo, &legal);
//moves_print(&legal, 0);
//printf("Fu ");
//moves_print(fishpos, 0);
//fflush(stdout);
//printf("Mu ");
//moves_print(pos, 0);
//fflush(stdout);
/* sort and print movelists */
move_sort_by_sq(&fishmoves);
move_sort_by_sq(&legal);
// printf("\nFs ");
// moves_print(fishpos, 0);
// fflush(stdout);
// printf("Ms ");
// moves_print(pos, 0);
// fflush(stdout);
/* compare movelists */
if (!movelists_equal(&fishmoves, &legal)) {
pos_print(pos);
printf("F: ");
moves_print(&fishmoves, 0);
printf("M: ");
moves_print(&legal, 0);
} else {
printf("[%s]: OK (%d Moves)\n", fen, legal.nmoves);
//moves_print(&fishpos->moves, 0);
}
//compare_moves(&fishpos->moves, &legal);
//} else {
//printf("fen %d: [%s] - OK (%d moves)\n", i, fen, legal.nmoves);
//}
//pos_print_board_raw(pos, 1);
//printf("%s\n", pos2fen(pos, str));
//get_stockfish_moves(test[i]);
//exit(0);
pos_del(pos);
i++;
}
fclose(outfd);
return 0;
}

310
test/perft-test.c Normal file
View File

@@ -0,0 +1,310 @@
/* perft-test.c - perft test.
*
* 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 <unistd.h>
#include <time.h>
#include <locale.h>
#include "chessdefs.h"
#include "fen.h"
#include "position.h"
#include "move.h"
#include "move-do.h"
#include "move-gen.h"
#include "search.h"
#include "common-test.h"
#define RD 0
#define WR 1
typedef struct {
move_t move;
int count;
} ddperft;
/**
* return write pipd fd
*/
static FILE *open_stockfish()
{
int rpipe[2], wpipe[2];
FILE *out_desc;
pid_t pid;
if ((pipe(rpipe) < 0) || (pipe(wpipe) < 0)) {
perror("pipe");
return NULL;
}
if ((pid = fork()) < 0) {
perror("fork");
return NULL;
}
if (!pid) { /* stockfish */
setvbuf(stdin, NULL, _IOLBF, 0);
setvbuf(stdout, NULL, _IOLBF, 0);
setvbuf(stderr, NULL, _IOLBF, 0);
dup2(wpipe[RD], STDIN_FILENO);
dup2(rpipe[WR], STDOUT_FILENO);
dup2(rpipe[WR], STDERR_FILENO);
close(wpipe[RD]);
close(wpipe[WR]);
close(rpipe[RD]);
close(rpipe[WR]);
if (execlp("stockfish", "stockfish", NULL) == -1) {
perror("execlp");
return NULL;
}
return 0; /* not reached */
}
/* us */
dup2(rpipe[RD], STDIN_FILENO);
setvbuf(stdin, NULL, _IOLBF, 0);
close(wpipe[RD]);
close(rpipe[RD]);
close(rpipe[WR]);
out_desc = fdopen(wpipe[WR], "w");
setvbuf(out_desc, NULL, _IOLBF, 0);
return out_desc;
}
static u64 send_stockfish_fen(FILE *desc, pos_t *pos, movelist_t *movelist,
char *fen, int depth)
{
char *buf = NULL;
u64 count, mycount = 0, fishcount;
size_t alloc = 0;
ssize_t buflen;
pos_clear(pos);
move_t *moves = movelist->move;
int *nmoves = &movelist->nmoves;
*nmoves = 0;
//char nodescount[] = "Nodes searched";
//printf("nmoves = %d\n", nmoves);
fflush(stdout);
//sprintf(str, "stockfish \"position fen %s\ngo perft depth\n\"", fen);
fprintf(desc, "position fen %s\ngo perft %d\n", fen, depth);
//fflush(desc);
while ((buflen = getline(&buf, &alloc, stdin)) > 0) {
buf[--buflen] = 0;
if (buflen == 0)
continue;
if (sscanf(buf, "Nodes searched: %lu", &fishcount) == 1) {
break;
}
//printf("%d: %s\n", line++, buf);
if (sscanf(buf, "%*4s: %lu", &count) == 1) {
square_t from = sq_from_string(buf);
square_t to = sq_from_string(buf + 2);
mycount += count;
//printf("move found: %c%c->%c%c %s->%s count=%d\n",
// buf[0], buf[1], buf[2], buf[3],
// sq_to_string(from), sq_to_string(to),
// count);
moves[(*nmoves)++] = move_make(from, to);
} else if (sscanf(buf, "%*5s: %lu", &count) == 1) {
square_t from = sq_from_string(buf);
square_t to = sq_from_string(buf + 2);
piece_type_t promoted = piece_t_from_char(*(buf + 4));
mycount += count;
//printf("move found: %c%c->%c%c %s->%s count=%d\n",
// buf[0], buf[1], buf[2], buf[3],
// sq_to_string(from), sq_to_string(to),
// count);
moves[(*nmoves)++] = move_make_promote(from, to, promoted);
}
}
//pos->moves.nmoves = nmoves;
// printf("fishcount=%d mycount=%d\n", fishcount, mycount);
free(buf);
return mycount;
}
static __unused bool movelists_equal(movelist_t *fish, movelist_t *me)
{
move_t *m1 = fish->move, *m2 = me->move;
int n1 = fish->nmoves, n2 = me->nmoves;
int mask = 077777;
if (n1 != n2)
return false;
for (int cur = 0; cur < n1; ++cur) {
if ((m1[cur] & mask) != (m2[cur] & mask))
return false;
}
return true;
}
static __unused void compare_moves(movelist_t *fish, movelist_t *me)
{
char str1[1024] = {0}, str2[1024] = {0}, tmpstr[1024];
char *skip = " ";
move_t *m1 = fish->move;
move_t *m2 = me->move;
int n1 = fish->nmoves;
int n2 = me->nmoves;
#define f(c) move_from(c)
#define t(c) move_to(c)
for (move_t *c1 = m1, *c2 = m2; (c1 - m1 < n1) || (c2 - m2 < n2);) {
// square_t f1 = move_from(*c1); square_t t1 = move_to(*c1);
// square_t f2 = move_from(*c2); square_t t2 = move_to(*c2);
/* no more move in c2 */
if (c2 - m2 >= n2) {
while (c1 - m1 < n1) {
sprintf(tmpstr, " %s-%s", sq_to_string(f(*c1)), sq_to_string(t(*c1)));
strcat (str1, tmpstr);
c1++;
}
break;
}
if (c1 - m1 >= n1) {
while (c2 - m2 < n2) {
sprintf(tmpstr, " %s-%s", sq_to_string(f(*c2)), sq_to_string(t(*c2)));
strcat (str2, tmpstr);
c2++;
}
break;
}
/* missing move in c2 */
if (f(*c1) < f(*c2) ||
(f(*c1) == f(*c2) && t(*c1) < t(*c2))) {
strcat(str2, skip);
sprintf(tmpstr, " %s-%s", sq_to_string(f(*c1)), sq_to_string(t(*c1)));
strcat (str1, tmpstr);
while ((c1 - m1 < n1) && (f(*c1) < f(*c2) ||
(f(*c1) == f(*c2) && t(*c1) < t(*c2)))) {
c1++;
}
continue;
}
/* missing move in c1 */
if (f(*c1) > f(*c2) ||
(f(*c1) == f(*c2) && t(*c1) > t(*c2))) {
strcat(str1, skip);
sprintf(tmpstr, " %s-%s", sq_to_string(f(*c2)), sq_to_string(t(*c2)));
strcat (str2, tmpstr);
while ((c2 - m2 < n2) && (f(*c1) > f(*c2) ||
(f(*c1) == f(*c2) && t(*c1) > t(*c2)))) {
c2++;
}
continue;
}
sprintf(tmpstr, " %s-%s", sq_to_string(f(*c1)), sq_to_string(t(*c1)));
strcat(str1, tmpstr);
strcat(str2, tmpstr);
c1++, c2++;
}
printf("F(%2d): %s\nM(%2d): %s\n", n1, str1, n2, str2);
}
int main(int __unused ac, __unused char**av)
{
int i = 0, test_line;
u64 sf_count, my_count;
char *fen;
pos_t *pos, *savepos, *fishpos = pos_new();
movelist_t fishmoves;
//move_t move;
FILE *outfd;
s64 ms1 = 0, ms1_total = 0;
s64 ms2 = 0, ms2_total = 0;
int depth = 6, run = 3;
if (ac > 1)
depth = atoi(av[1]);
if (ac > 2)
run = atoi(av[2]) & 3;
printf("depth = %d run=%d\n", depth, run);
if (!run)
exit(0);
setlocale(LC_NUMERIC, "");
setlinebuf(stdout); /* line-buffered stdout */
outfd = open_stockfish();
bitboard_init();
hyperbola_init();
CLOCK_DEFINE(clock, CLOCK_PROCESS);
while ((fen = next_fen(PERFT | MOVEDO))) {
test_line = cur_line();
if (!(pos = fen2pos(NULL, fen))) {
printf("wrong fen %d: [%s]\n", i, fen);
continue;
}
sf_count = send_stockfish_fen(outfd, fishpos, &fishmoves, fen, depth);
savepos = pos_dup(pos);
if (run & 1) {
clock_start(&clock);
my_count = perft(pos, depth, 1);
ms1 = clock_elapsed_ms(&clock);
ms1_total += ms1;
if (sf_count == my_count) {
printf("pt1 OK : line=%3d perft=%'lu %'ldms lps=%'lu \"%s\"\n",
test_line, my_count, ms1,
ms1? my_count*1000l/ms1: 0,
fen);
} else {
printf("pt1 ERR: line=%3d sf=%'lu me=%'lu \"%s\"\n",
test_line, sf_count, my_count, fen);
}
}
if (run & 2) {
clock_start(&clock);
my_count = perft_new_pinners(pos, depth, 1);
ms2 = clock_elapsed_ms(&clock);
ms2_total += ms2;
if (sf_count == my_count) {
printf("pt2 OK : line=%3d perft=%'lu %'ldms lps=%'lu \"%s\"\n",
test_line, my_count, ms2,
ms2? my_count*1000l/ms2: 0,
fen);
} else {
printf("pt2 ERR: line=%3d sf=%'lu me=%'lu \"%s\"\n",
test_line, sf_count, my_count, fen);
}
}
printf("\n");
pos_del(savepos);
pos_del(pos);
i++;
/* to run first test only */
// exit(0);
}
if (run & 1)
printf("total perft %'ldms\n", ms1_total);
if (run & 2)
printf("total perft2 %'ldms\n", ms2_total);
return 0;
}

View File

@@ -1,55 +1,20 @@
#include <stdio.h>
#include "debug.h"
#include "brlib.h"
#include "../src/fen.h"
#include "../src/position.h"
#include "../src/bitboard.h"
#include "piece.h"
int main(int ac, char**av)
int main(__unused int ac, __unused char**av)
{
pos_t *pos;
printf("zobi\n");fflush(stdout);
debug_init(6, stderr, true);
log_f(5, "kfsjdhg\n");
pos_pool_init();
pos = pos_get();
piece_pool_init();
if (ac == 1) {
printf("zoba\n");fflush(stdout);
pos_startpos(pos);
} else {
fen2pos(pos, av[1]);
piece_t p;
char *test="PNBRQKpnbrqk";
for (u64 i = 0; i < sizeof(test); ++i) {
char c1 = test[i], *c2;
p = piece_from_fen(c1);
c2 = piece_to_fen(p);
printf("c1=%c c2=%c\n", c1, *c2);
}
pos_print(pos);
pos_pieces_print(pos);
printf("0x1c = 11100 = C1-E1:\n");
bitboard_print(0x1c);
printf("0x70 = 111 = A1-C1\n");
bitboard_print(0x70);
printf("0x0e = 1110 = B1-D1\n");
bitboard_print(0x0e);
printf("0x60 = 1100000 = F1-G1\n");
bitboard_print(0x60);
printf("A1:\n");
bitboard_print(A1);
printf("1:\n");
bitboard_print(1L);
printf("H1:\n");
bitboard_print(H1);
printf("C1:\n");
bitboard_print(C1);
printf("D1:\n");
bitboard_print(D1);
printf("C1|D1:\n");
bitboard_print(C1|D1);
printf("H8:\n");
bitboard_print(H8);
return 0;
}

0
util.c
View File