Files
Eleanor/source/board.cpp
T

1043 lines
30 KiB
C++

#include <bit>
#include "board.h"
#include "accumulator.h"
#include "movegen.h"
#include "nnue.h"
#include "tt.h"
#include <iostream>
#include <ranges>
#include <string_view>
#include <cassert>
#include "types.h"
#include "utils.h"
void Board::Reset() {
castlingRights = 0;
enPassantTarget = noEPTarget;
halfMoves = 0;
fullMoves = 1;
sideToMove = White;
occupied = 0ULL;
checkers = 0ULL;
mailbox = std::array<int, 64>();
mailbox.fill(nullPieceType);
pinned = std::array<Bitboard, 2>();
pieces = std::array<Bitboard, 6>();
colors = std::array<Bitboard, 2>();
accUpdate.setRefresh();
mirroredWhite = false;
mirroredBlack = false;
pieceThreats = std::array<Bitboard, 6>();
colorThreats = std::array<Bitboard, 2>();
moveList = std::array<Move, MAX_MOVES>();
positionIndex = 0;
currentMoveIndex = 0;
hashKey = 0ULL;
pawnKey = 0ULL;
nonPawnKey = 0ULL;
majorKey = 0ULL;
checkZones = std::array<Bitboard, 4>();
}
void Board::SetByFen(std::string_view fen) {
Reset();
int currSquare = a8;
std::vector<std::string> tokens = UTILS::split(fen, ' ');
std::vector<std::string> pieceTokens = UTILS::split(tokens[0], '/');
constexpr std::string_view pieceTypes = "pnbrqk";
for (std::string_view rank : pieceTokens) {
for (const char piece : rank) {
if (std::isdigit(piece)) {
currSquare += piece - '0';
continue;
}
bool side = std::islower(piece);
int pieceType = pieceTypes.find(std::tolower(piece));
SetPiece(pieceType, currSquare, side);
currSquare++;
}
currSquare -= 16;
}
sideToMove = tokens[1] == "b";
for (const char piece : tokens[2]) {
if (piece == 'K') castlingRights |= whiteKingRight;
else if (piece == 'Q') castlingRights |= whiteQueenRight;
else if (piece == 'k') castlingRights |= blackKingRight;
else if (piece == 'q') castlingRights |= blackQueenRight;
}
if (tokens[3] != "-") enPassantTarget = UTILS::parseSquare(tokens[3]);
if (tokens.size() > 4) {
halfMoves = std::stoi(tokens[4]);
fullMoves = std::stoi(tokens[5]);
}
pawnKey = 0ULL;
nonPawnKey = 0ULL;
majorKey = 0ULL;
occupied = colors[White] | colors[Black];
hashKey = UTILS::GetHashKey(*this);
checkers = CalcCheckers();
pinned = {CalcPinned(White), CalcPinned(Black)};
CalcCheckers();
MOVEGEN::GenThreatMaps(*this);
MOVEGEN::GenerateMoves<All>(*this, true);
int whiteKingFile = (pieces[King] & colors[White]).getLS1BIndex() % 8;
int blackKingFile = (pieces[King] & colors[Black]).getLS1BIndex() % 8;
if (whiteKingFile > 3) {
mirroredWhite = true;
}
if (blackKingFile > 3) {
mirroredBlack = true;
}
accUpdate.setRefresh();
}
std::string Board::GetFen() {
std::ostringstream fen;
for (int rank = 7; rank >= 0; --rank) {
int emptyCount = 0;
for (int file = 0; file < 8; ++file) {
int square = rank * 8 + file;
const uint64_t squareBit = 1ULL << square;
if (!(occupied & squareBit)) {
++emptyCount;
continue;
}
if (emptyCount > 0) {
fen << emptyCount;
emptyCount = 0;
}
static constexpr std::array<char, 6> pieceChars = {'p', 'n', 'b', 'r', 'q', 'k'};
char pieceChar = '?';
for (size_t pieceType = 0; pieceType < pieceChars.size(); ++pieceType) {
if (pieces[pieceType] & squareBit) {
pieceChar = pieceChars[pieceType];
break;
}
}
fen << (colors[White] & squareBit ? static_cast<char>(std::toupper(pieceChar)) : pieceChar);
}
if (emptyCount > 0) {
fen << emptyCount;
}
if (rank > 0) {
fen << '/';
}
}
fen << ' ' << (sideToMove ? 'b' : 'w');
fen << ' ';
bool hasCastlingRights = false;
const std::array<std::pair<uint8_t, char>, 4> castlingOptions = {
{{whiteKingRight, 'K'}, {whiteQueenRight, 'Q'}, {blackKingRight, 'k'}, {blackQueenRight, 'q'}}
};
for (const auto& [right, symbol] : castlingOptions) {
if (castlingRights & right) {
fen << symbol;
hasCastlingRights = true;
}
}
if (!hasCastlingRights) {
fen << '-';
}
fen << ' ';
if (enPassantTarget == noEPTarget) {
fen << '-';
} else {
const int file = enPassantTarget % 8;
const int rank = enPassantTarget / 8;
fen << static_cast<char>('a' + file) << (rank + 1);
}
fen << ' ' << halfMoves;
fen << ' ' << fullMoves;
return fen.str();
}
void Board::PrintBoard() {
for (int rank = 7; rank >= 0; rank--) {
std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
std::cout << "| ";
for (int file = 0; file < 8; file++) {
int square = rank * 8 + file;
bool pieceSet = false;
for (int i = Pawn; i <= King; i++) {
if ((colors[White] & pieces[i]).IsSet(square)) {
std::cout << PIECE_LETTERS[i * 2 + White] << " | ";
pieceSet = true;
} else if ((colors[Black] & pieces[i]).IsSet(square)) {
std::cout << PIECE_LETTERS[i * 2 + Black] << " | ";
pieceSet = true;
}
}
if (!pieceSet) {
std::cout << " | ";
}
}
std::cout << ' ' << rank + 1 << std::endl;
}
std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
std::cout << " a b c d e f g h" << std::endl << std::endl;
std::cout << " Side to move: ";
if (!sideToMove) {
std::cout << "White" << std::endl;
} else {
std::cout << "Black" << std::endl;
}
if (enPassantTarget != noEPTarget) {
std::cout << " En Passant square: " << squareCoords[enPassantTarget] << std::endl;
} else {
std::cout << " En Passant square: None" << std::endl;
}
std::cout << " Castling rights: ";
if (castlingRights & whiteKingRight) std::cout << "K"; else std::cout << "-";
if (castlingRights & whiteQueenRight) std::cout << "Q"; else std::cout << "-";
if (castlingRights & blackKingRight) std::cout << "k"; else std::cout << "-";
if (castlingRights & blackQueenRight) std::cout << "q"; else std::cout << "-";
std::cout << std::endl << std::endl;
std::cout << " Hashkey: 0x" << std::hex << hashKey << std::dec << std::endl;
std::cout << " Fen: " << GetFen() << std::endl;
}
void Board::PrintNNUE() {
std::cout << "Final eval: " << NNUE::net.Evaluate(*this) << std::endl;
}
void Board::AddMove(Move move) {
moveList[currentMoveIndex] = move;
currentMoveIndex++;
}
void Board::ResetMoves() {
currentMoveIndex = 0;
}
void Board::ListMoves() {
int moveCount = 1;
for (int i = 0; i < currentMoveIndex; i++) {
if (!IsLegal(moveList[i])) continue;
Board copy = *this;
copy.MakeMove(moveList[i]);
std::cout << moveCount << ". ";
moveList[i].PrintMove();
std::cout << "( " << moveTypes[moveList[i].GetFlags()] << " )";
std::cout << std::endl;
moveCount++;
}
}
int Board::GetPieceType(int square) {
return mailbox[square];
}
int Board::GetPieceColor(int square) {
return (colors[Black].IsSet(square));
}
bool Board::InCheck() {
Bitboard myKingSquare = colors[sideToMove] & pieces[King];
return colorThreats[!sideToMove] & myKingSquare;
}
void Board::SetPiece(int piece, int square, bool color) {
pieces[piece].SetBit(square);
colors[color].SetBit(square);
occupied.SetBit(square);
mailbox[square] = piece;
hashKey ^= UTILS::zKeys[color][piece][square];
if (piece == Pawn) {
pawnKey ^= UTILS::zKeys[color][Pawn][square];
} else {
nonPawnKey ^= UTILS::zKeys[color][piece][square];
if (piece == King || piece == Rook || piece == Queen) {
majorKey ^= UTILS::zKeys[color][piece][square];
}
}
}
void Board::RemovePiece(int piece, int square, bool color) {
pieces[piece].PopBit(square);
colors[color].PopBit(square);
occupied.PopBit(square);
mailbox[square] = nullPieceType;
hashKey ^= UTILS::zKeys[color][piece][square];
if (piece == Pawn) {
pawnKey ^= UTILS::zKeys[color][Pawn][square];
} else {
nonPawnKey ^= UTILS::zKeys[color][piece][square];
if (piece == King || piece == Rook || piece == Queen) {
majorKey ^= UTILS::zKeys[color][piece][square];
}
}
}
static void UpdateCastlingRights(Board &board, int square, int type, int color) {
if (type == Rook) {
board.hashKey ^= UTILS::zCastle[board.castlingRights];
int queenSideRook = color ? a8 : a1;
int kingSideRook = color ? h8 : h1;
if (square == queenSideRook) {
board.castlingRights &= color ? ~blackQueenRight : ~whiteQueenRight;
} else if (square == kingSideRook) {
board.castlingRights &= color ? ~blackKingRight : ~whiteKingRight;
}
board.hashKey ^= UTILS::zCastle[board.castlingRights];
} else if (type == King) {
board.hashKey ^= UTILS::zCastle[board.castlingRights];
board.castlingRights &= color ? ~blackKingRight : ~whiteKingRight;
board.castlingRights &= color ? ~blackQueenRight : ~whiteQueenRight;
board.hashKey ^= UTILS::zCastle[board.castlingRights];
}
}
void Board::Promote(int square, int pieceType, int color, bool isCapture) {
if (isCapture) {
int targetType = GetPieceType(square);
RemovePiece(targetType, square, !color);
UpdateCastlingRights(*this, square, targetType, !color);
}
SetPiece(pieceType, square, color);
}
void Board::MakeMove(Move move) {
const bool accParentClean = accUpdate.type == ACC::UpdateType::None;
accUpdate = ACC::Update();
if (!move) {
if (accParentClean) accUpdate.type = ACC::UpdateType::Copy;
else accUpdate.setRefresh();
int newEpTarget = noEPTarget;
sideToMove = !sideToMove;
hashKey ^= UTILS::zSide;
if (enPassantTarget != noEPTarget) {
hashKey ^= UTILS::zEnPassant[enPassantTarget % 8];
}
enPassantTarget = newEpTarget;
return;
}
int newEpTarget = noEPTarget;
int attackerPiece = GetPieceType(move.MoveFrom());
int attackerColor = GetPieceColor(move.MoveFrom());
int targetPiece = GetPieceType(move.MoveTo());
int direction = attackerColor ? south : north;
int endPiece = attackerPiece;
uint8_t refreshMask = 0;
if (attackerPiece == King) {
const int toFile = move.MoveTo() % 8;
if (attackerColor == White) {
if ((toFile > 3) != mirroredWhite) {
mirroredWhite = !mirroredWhite;
refreshMask |= 1 << White;
}
} else {
if ((toFile > 3) != mirroredBlack) {
mirroredBlack = !mirroredBlack;
refreshMask |= 1 << Black;
}
}
if (NNUE::kingBuckets[attackerColor][move.MoveFrom()] != NNUE::kingBuckets[attackerColor][move.MoveTo()]) {
refreshMask |= 1 << attackerColor;
}
}
RemovePiece(attackerPiece, move.MoveFrom(), attackerColor);
if (move.IsPromo()) {
endPiece = move.GetPromoPiece();
if (move.IsCapture()) {
Promote(move.MoveTo(), endPiece, sideToMove, true);
} else {
Promote(move.MoveTo(), endPiece, sideToMove, false);
}
}
{
if (move.IsCapture()) {
if (move.GetFlags() != epCapture) {
accUpdate.setAddSubSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece, move.MoveTo(), targetPiece);
} else {
accUpdate.setAddSubSub(sideToMove, enPassantTarget, endPiece, move.MoveFrom(), attackerPiece, move.MoveTo() - direction, Pawn);
}
} else {
if (move.GetFlags() != kingCastle && move.GetFlags() != queenCastle) {
accUpdate.setAddSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece);
}
}
}
switch (move.GetFlags())
{
case quiet:
SetPiece(attackerPiece, move.MoveTo(), attackerColor);
break;
case doublePawnPush:
SetPiece(attackerPiece, move.MoveTo(), attackerColor);
newEpTarget = move.MoveFrom() + direction;
break;
case capture:
RemovePiece(targetPiece, move.MoveTo(), !attackerColor);
SetPiece(attackerPiece, move.MoveTo(), attackerColor);
UpdateCastlingRights(*this, move.MoveTo(), targetPiece, !attackerColor);
break;
case epCapture:
RemovePiece(Pawn, move.MoveTo() - direction, !attackerColor);
SetPiece(attackerPiece, move.MoveTo(), attackerColor);
break;
case kingCastle:
{
int rookSquare = attackerColor ? h8 : h1;
RemovePiece(Rook, rookSquare, attackerColor);
SetPiece(Rook, rookSquare - 2, attackerColor);
SetPiece(attackerPiece, move.MoveTo(), attackerColor);
{
accUpdate.setAddAddSubSub(sideToMove, move.MoveTo(), King, rookSquare - 2, Rook, move.MoveFrom(), King, rookSquare, Rook);
}
break;
}
case queenCastle:
{
int rookSquare = attackerColor ? a8 : a1;
RemovePiece(Rook, rookSquare, attackerColor);
SetPiece(Rook, rookSquare + 3, attackerColor);
SetPiece(attackerPiece, move.MoveTo(), attackerColor);
{
accUpdate.setAddAddSubSub(sideToMove, move.MoveTo(), King, rookSquare + 3, Rook, move.MoveFrom(), King, rookSquare, Rook);
}
break;
}
default:
break;
}
if (!accParentClean || accUpdate.type == ACC::UpdateType::None) {
accUpdate.setRefresh();
} else {
accUpdate.refreshMask = refreshMask;
}
UpdateCastlingRights(*this, move.MoveFrom(), attackerPiece, attackerColor);
sideToMove = !attackerColor;
hashKey ^= UTILS::zSide;
if (enPassantTarget != noEPTarget) {
hashKey ^= UTILS::zEnPassant[enPassantTarget % 8];
}
if (newEpTarget != noEPTarget) {
hashKey ^= UTILS::zEnPassant[newEpTarget % 8];
}
enPassantTarget = newEpTarget;
MOVEGEN::GenThreatMaps(*this);
pinned = {CalcPinned(White), CalcPinned(Black)};
checkers = CalcCheckers();
CalcCheckZones();
if (attackerColor == Black) fullMoves++;
if (attackerPiece == Pawn || move.IsCapture()) {
halfMoves = 0;
} else {
halfMoves++;
}
positionIndex++;
}
bool Board::InPossibleZug() {
Bitboard toCheck;
for (int piece = Knight; piece <= Queen; piece++) {
toCheck |= (pieces[piece] & colors[sideToMove]);
}
return !toCheck;
}
ACC::BucketPair Board::GetBuckets() {
int wKingSq = (pieces[King] & colors[White]).getLS1BIndex();
int bKingSq = (pieces[King] & colors[Black]).getLS1BIndex();
return {NNUE::kingBuckets[White][wKingSq],NNUE::kingBuckets[Black][bKingSq]};
}
void Board::RefreshAccumulator(ACC::AccumulatorPair& out) const {
const int wKingSq = (pieces[King] & colors[White]).getLS1BIndex();
const int bKingSq = (pieces[King] & colors[Black]).getLS1BIndex();
const ACC::BucketPair bucketPair = {NNUE::kingBuckets[White][wKingSq], NNUE::kingBuckets[Black][bKingSq]};
out.white = NNUE::net.accumulator_biases;
out.black = NNUE::net.accumulator_biases;
for (int color = White; color <= Black; color++) {
Bitboard bb = colors[color];
while (bb) {
int square = bb.getLS1BIndex();
int wInput = ACC::CalculateIndex(White, color, mailbox[square], square, mirroredWhite);
int bInput = ACC::CalculateIndex(Black, color, mailbox[square], square, mirroredBlack);
ACC::AddRow(out.white, &NNUE::net.accumulator_weights[bucketPair.white][wInput * NNUE::HL_SIZE]);
ACC::AddRow(out.black, &NNUE::net.accumulator_weights[bucketPair.black][bInput * NNUE::HL_SIZE]);
bb.PopBit(square);
}
}
}
void Board::RefreshPerspective(ACC::FinnyTable& finny, bool perspective, ACC::Accumulator& out) const {
const bool mirrored = perspective == White ? mirroredWhite : mirroredBlack;
const int kingSq = (pieces[King] & colors[perspective]).getLS1BIndex();
const int bucket = NNUE::kingBuckets[perspective][kingSq];
ACC::FinnyEntry& entry = finny.entries[perspective][mirrored][bucket];
const int16_t* adds[32];
const int16_t* subs[32];
int nAdds = 0;
int nSubs = 0;
for (int color = White; color <= Black; color++) {
for (int pt = Pawn; pt <= King; pt++) {
Bitboard tmp = pieces[pt] & colors[color];
const uint64_t now = tmp;
const uint64_t old = entry.bb[color][pt];
uint64_t added = now & ~old;
uint64_t removed = old & ~now;
while (added) {
const int square = std::countr_zero(added);
added &= added - 1;
adds[nAdds++] = ACC::Row(bucket, ACC::CalculateIndex(perspective, color, pt, square, mirrored));
}
while (removed) {
const int square = std::countr_zero(removed);
removed &= removed - 1;
subs[nSubs++] = ACC::Row(bucket, ACC::CalculateIndex(perspective, color, pt, square, mirrored));
}
entry.bb[color][pt] = now;
}
}
ACC::ApplyInPlace(entry.acc, adds, nAdds, subs, nSubs);
out = entry.acc;
}
void Board::ApplyDeltaPerspective(bool perspective, ACC::Accumulator& dst, const ACC::Accumulator& src) const {
const bool mirrored = perspective == White ? mirroredWhite : mirroredBlack;
const int kingSq = (pieces[King] & colors[perspective]).getLS1BIndex();
const int bucket = NNUE::kingBuckets[perspective][kingSq];
const bool stm = accUpdate.stm;
const int16_t* a1 = ACC::Row(bucket, ACC::CalculateIndex(perspective, stm, accUpdate.addPT1, accUpdate.add1, mirrored));
const int16_t* a2 = nullptr;
const int16_t* s1 = ACC::Row(bucket, ACC::CalculateIndex(perspective, stm, accUpdate.subPT1, accUpdate.sub1, mirrored));
const int16_t* s2 = nullptr;
if (accUpdate.nAdd == 2)
a2 = ACC::Row(bucket, ACC::CalculateIndex(perspective, stm, accUpdate.addPT2, accUpdate.add2, mirrored));
if (accUpdate.nSub == 2)
s2 = ACC::Row(bucket, ACC::CalculateIndex(perspective, accUpdate.sub2Opp ? !stm : stm, accUpdate.subPT2, accUpdate.sub2, mirrored));
ACC::Apply(dst, src, a1, a2, s1, s2);
}
void Board::UpdateAccumulator(ACC::AccStack& stack, int ply) {
using ACC::UpdateType;
if (accUpdate.type == UpdateType::None) return;
if (accUpdate.type == UpdateType::Copy && ply > 0) {
stack.cur[ply] = stack.cur[ply - 1];
accUpdate.type = UpdateType::None;
return;
}
ACC::AccumulatorPair& dst = stack.slots[ply];
if (ply == 0 || accUpdate.type != UpdateType::Delta) {
RefreshPerspective(stack.finny, White, dst.white);
RefreshPerspective(stack.finny, Black, dst.black);
} else {
const ACC::AccumulatorPair& prev = *stack.cur[ply - 1];
for (int perspective = White; perspective <= Black; perspective++) {
if (accUpdate.refreshMask & (1 << perspective))
RefreshPerspective(stack.finny, perspective, dst.get(perspective));
else
ApplyDeltaPerspective(perspective, dst.get(perspective), prev.get(perspective));
}
}
stack.cur[ply] = &dst;
accUpdate.type = UpdateType::None;
}
Bitboard Board::AttacksTo(int square, Bitboard occupancy) {
Bitboard attacks;
attacks |= (MOVEGEN::pawnAttacks[sideToMove][square] & colors[!sideToMove] & pieces[Pawn]);
attacks |= (MOVEGEN::pawnAttacks[!sideToMove][square] & colors[sideToMove] & pieces[Pawn]);
attacks |= (MOVEGEN::knightAttacks[square] & pieces[Knight]);
attacks |= (MOVEGEN::kingAttacks[square] & pieces[King]);
Bitboard bishopAttacks = MOVEGEN::getBishopAttack(square, occupancy);
Bitboard rookAttacks = MOVEGEN::getRookAttack(square, occupancy);
attacks |= (rookAttacks & (pieces[Rook] | pieces[Queen]));
attacks |= (bishopAttacks & (pieces[Bishop] | pieces[Queen]));
return attacks;
}
static Bitboard rayBetween(int sq1, int sq2) {
if (sq1 == sq2) return 0ULL;
int f1 = sq1 % 8, r1 = sq1 / 8;
int f2 = sq2 % 8, r2 = sq2 / 8;
int df = (f2 > f1) - (f2 < f1);
int dr = (r2 > r1) - (r2 < r1);
if (df != 0 && dr != 0 && std::abs(f2 - f1) != std::abs(r2 - r1))
return 0ULL;
Bitboard ray = 0ULL;
int f = f1 + df;
int r = r1 + dr;
while (f != f2 || r != r2) {
ray |= 1ULL << (r * 8 + f);
f += df;
r += dr;
}
ray &= ~((1ULL << sq1) | (1ULL << sq2));
return ray;
}
static Bitboard fullRay(int from, int to) {
int df = (to % 8) - (from % 8);
int dr = (to / 8) - (from / 8);
if (df != 0) df /= std::abs(df);
if (dr != 0) dr /= std::abs(dr);
Bitboard ray = 0ULL;
int f = from % 8 + df;
int r = from / 8 + dr;
while (f >= 0 && f < 8 && r >= 0 && r < 8) {
ray |= 1ULL << (r * 8 + f);
f += df;
r += dr;
}
f = from % 8 - df;
r = from / 8 - dr;
while (f >= 0 && f < 8 && r >= 0 && r < 8) {
ray |= 1ULL << (r * 8 + f);
f -= df;
r -= dr;
}
ray |= 1ULL << from;
return ray;
}
bool Board::IsSquareThreatened(bool side, int square) {
return colorThreats[!side].IsSet(square);
}
Bitboard Board::CalcCheckers() {
return AttacksTo((colors[sideToMove] & pieces[King]).getLS1BIndex(), occupied) & colors[!sideToMove];
}
Bitboard Board::CalcPinned(bool color) {
Bitboard pinned;
int kingSquare = (pieces[King] & colors[color]).getLS1BIndex();
assert(kingSquare != -1);
Bitboard oppQueens = pieces[Queen] & colors[!color];
Bitboard potentialAttackers = MOVEGEN::getBishopAttack(kingSquare, colors[!color]) & (oppQueens | (pieces[Bishop] & colors[!color]))
| MOVEGEN::getRookAttack(kingSquare, colors[!color]) & (oppQueens | (pieces[Rook] & colors[!color]));
while (potentialAttackers) {
int attackerSquare = potentialAttackers.getLS1BIndex();
Bitboard isPinned = colors[color] & rayBetween(attackerSquare, kingSquare);
if (isPinned.PopCount() == 1)
pinned |= isPinned;
potentialAttackers.PopBit(attackerSquare);
}
return pinned;
}
bool Board::IsLegal(Move &move) {
assert(move != 0);
int us = sideToMove;
int them = !us;
int from = move.MoveFrom();
int to = move.MoveTo();
Bitboard king = pieces[King] & colors[us];
int kingSquare = king.getLS1BIndex();
int moveType = move.GetFlags();
if (moveType == epCapture) {
int epCapturedSquare = to + (us == White ? -8 : 8);
Bitboard occAfterEP = occupied ^ Bitboard::GetSquare(from) ^ Bitboard::GetSquare(to)
^ Bitboard::GetSquare(epCapturedSquare);
Bitboard theirQueens = pieces[Queen] & colors[them];
return (MOVEGEN::getBishopAttack(kingSquare, occAfterEP) & (theirQueens | (pieces[Bishop] & colors[them]))).PopCount() < 1
&& (MOVEGEN::getRookAttack(kingSquare, occAfterEP) & (theirQueens | (pieces[Rook] & colors[them]))).PopCount() < 1;
}
int movingPiece = GetPieceType(from);
if (movingPiece == King) {
Bitboard kinglessOcc = occupied ^ king;
Bitboard theirQueens = pieces[Queen] & colors[them];
return !colorThreats[them].IsSet(to)
&& (MOVEGEN::getBishopAttack(to, kinglessOcc) & (theirQueens | (pieces[Bishop] & colors[them]))).PopCount() == 0
&& (MOVEGEN::getRookAttack(to, kinglessOcc) & (theirQueens | (pieces[Rook] & colors[them]))).PopCount() == 0;
}
if (checkers.PopCount() > 1) {
return false;
}
if (pinned[us].IsSet(from) && !fullRay(kingSquare, from).IsSet(to))
return false;
if (checkers.PopCount() < 1)
return true;
int checkerSquare = checkers.getLS1BIndex();
return (rayBetween(kingSquare, checkerSquare) | checkers).IsSet(to);
}
bool Board::IsPseudoLegal(Move &move) {
if (!move) return true;
const int from = move.MoveFrom();
const int to = move.MoveTo();
const int flag = move.GetFlags();
if ((unsigned)from >= 64u || (unsigned)to >= 64u) return false;
const int us = sideToMove;
const int them = !sideToMove;
const int movingPiece = GetPieceType(from);
if (movingPiece == nullPieceType) return false;
if (!colors[us].IsSet(from)) return false;
if (colors[us].IsSet(to)) return false;
const bool isCapture = move.IsCapture();
const int targetPiece = GetPieceType(to);
if (flag == capture) {
if (targetPiece == nullPieceType) return false;
if (!colors[them].IsSet(to)) return false;
} else if (isCapture && flag != epCapture) {
if (targetPiece == nullPieceType) return false;
if (!colors[them].IsSet(to)) return false;
} else if (!isCapture) {
if (occupied.IsSet(to)) {
if (flag != kingCastle && flag != queenCastle) return false;
}
}
const int fromFile = from & 7;
const int toFile = to & 7;
const int fromRank = from >> 3;
const int toRank = to >> 3;
const int dir = us ? south : north;
auto isOneStepPawnPush = [&] {
return to == from + dir && !occupied.IsSet(to);
};
auto isPawnCaptureTo = [&] {
return (to == from + dir - 1 && toFile == fromFile - 1)
|| (to == from + dir + 1 && toFile == fromFile + 1);
};
switch (flag) {
case quiet:
case capture:
break;
case doublePawnPush: {
if (movingPiece != Pawn) return false;
if (!us) {
if (fromRank != 1) return false;
} else {
if (fromRank != 6) return false;
}
const int mid = from + dir;
if (to != from + 2 * dir) return false;
if (occupied.IsSet(mid) || occupied.IsSet(to)) return false;
return true;
}
case epCapture: {
if (movingPiece != Pawn) return false;
if (enPassantTarget == noEPTarget) return false;
if (to != enPassantTarget) return false;
if (!isPawnCaptureTo()) return false;
const int capSq = to - dir;
if (!colors[them].IsSet(capSq)) return false;
if (GetPieceType(capSq) != Pawn) return false;
if (occupied.IsSet(to)) return false;
return true;
}
case kingCastle:
case queenCastle: {
if (movingPiece != King) return false;
const int kingSquare = (colors[us] & pieces[King]).getLS1BIndex();
if (from != kingSquare) return false;
const int kingRight = us ? blackKingRight : whiteKingRight;
const int queenRight = us ? blackQueenRight : whiteQueenRight;
if (flag == kingCastle) {
if (!(castlingRights & kingRight)) return false;
const U64 KingSide = us ? 0xf000000000000000ULL : 0xf0ULL;
const U64 mask = us ? 0x7000000000000000ULL : 0x70ULL;
const int targetSq = us ? g8 : g1;
if (to != targetSq) return false;
if ((Bitboard(KingSide) & occupied).PopCount() != 2) return false;
if (mask & colorThreats[them]) return false;
return true;
} else {
if (!(castlingRights & queenRight)) return false;
const U64 QueenSide = us ? 0x1f00000000000000ULL : 0x1fULL;
const U64 mask = us ? 0x1c00000000000000ULL : 0x1cULL;
const int targetSq = us ? c8 : c1;
if (to != targetSq) return false;
if ((Bitboard(QueenSide) & occupied).PopCount() != 2) return false;
if (mask & colorThreats[them]) return false;
return true;
}
}
default:
if (!move.IsPromo()) return false;
if (movingPiece != Pawn) return false;
if (!us) {
if (toRank != 7) return false;
} else {
if (toRank != 0) return false;
}
if (move.IsCapture()) {
if (!isPawnCaptureTo()) return false;
if (!colors[them].IsSet(to)) return false;
} else {
if (!isOneStepPawnPush()) return false;
}
return true;
}
switch (movingPiece) {
case Pawn: {
if (!us) { if (toRank == 7) return false; }
else { if (toRank == 0) return false; }
if (move.IsCapture()) {
if (!isPawnCaptureTo()) return false;
return true;
} else {
return isOneStepPawnPush();
}
}
case Knight:
return (MOVEGEN::knightAttacks[from] & Bitboard::GetSquare(to)) != 0;
case Bishop: {
Bitboard att = MOVEGEN::getBishopAttack(from, occupied);
return (att & Bitboard::GetSquare(to)) != 0;
}
case Rook: {
Bitboard att = MOVEGEN::getRookAttack(from, occupied);
return (att & Bitboard::GetSquare(to)) != 0;
}
case Queen: {
Bitboard att = MOVEGEN::getBishopAttack(from, occupied) | MOVEGEN::getRookAttack(from, occupied);
return (att & Bitboard::GetSquare(to)) != 0;
}
case King:
return (MOVEGEN::kingAttacks[from] & Bitboard::GetSquare(to)) != 0;
default:
return false;
}
}
void Board::CalcCheckZones() {
int oppKingSquare = (colors[!sideToMove] & pieces[King]).getLS1BIndex();
checkZones[0] = MOVEGEN::pawnAttacks[!sideToMove][oppKingSquare];
checkZones[1] = MOVEGEN::knightAttacks[oppKingSquare];
checkZones[2] = MOVEGEN::getBishopAttack(oppKingSquare, occupied);
checkZones[3] = MOVEGEN::getRookAttack(oppKingSquare, occupied);
}
bool Board::GivesDirectCheck(Move &move) {
int attackerType = nullPieceType;
if (move.IsPromo()) {
attackerType = move.GetPromoPiece();
} else {
attackerType = GetPieceType(move.MoveFrom());
}
if (attackerType == King)
return false;
Bitboard checkZone = 0ULL;
if (attackerType == Queen) {
checkZone = checkZones[Bishop] | checkZones[Rook];
} else {
checkZone = checkZones[attackerType];
}
return checkZone.IsSet(move.MoveTo());
}