CPG/Chess/nimfish/nimfishpkg/movegen.nim

350 lines
14 KiB
Nim

# Copyright 2023 Mattia Giambirtone & All Contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import std/strformat
import bitboards
import board
import magics
import pieces
import moves
import position
import rays
import misc
export bitboards, magics, pieces, moves, position, rays, misc, board
proc generatePawnMoves(self: Chessboard, moves: var MoveList, mask: Bitboard) =
let
sideToMove = self.position.sideToMove
pawns = self.getBitboard(Pawn, sideToMove)
occupancy = self.getOccupancy()
# We can only capture enemy pieces (except the king)
enemyPieces = self.getOccupancyFor(sideToMove.opposite())
# We can only capture diagonally and forward
rightMovement = pawns.forwardRightRelativeTo(sideToMove)
leftMovement = pawns.forwardLeftRelativeTo(sideToMove)
epTarget = self.position.enPassantSquare
checkers = self.position.checkers
diagonalPins = self.position.diagonalPins
orthogonalPins = self.position.orthogonalPins
promotionRank = if sideToMove == White: getRankMask(0) else: getRankMask(7)
# The rank where each color's side starts
# TODO: Give names to ranks and files so we don't have to assume a
# specific board layout when calling get(Rank|File)Mask
startingRank = if sideToMove == White: getRankMask(6) else: getRankMask(1)
var epBitboard = if epTarget != nullSquare(): epTarget.toBitboard() else: Bitboard(0)
let epPawn = if epBitboard == 0: Bitboard(0) else: epBitboard.forwardRelativeTo(sideToMove)
# If we are in check, en passant is only possible if we'd capture the (only)
# checking pawn with it
if epBitboard != 0 and self.inCheck() and (epPawn and checkers).countSquares() == 0:
epBitboard = Bitboard(0)
# Single and double pushes
let
# If a pawn is pinned diagonally, it cannot move
pushablePawns = pawns and not diagonalPins
# Neither can it move if it's pinned orthogonally
singlePushes = pushablePawns.forwardRelativeTo(sideToMove) and not occupancy and not orthogonalPins
# Only pawns on their starting rank can double push
doublePushes = (pushablePawns and startingRank).doubleForwardRelativeTo(sideToMove) and not occupancy and orthogonalPins
proc generateRookMoves(self: Chessboard, moves: var MoveList, mask: Bitboard) =
## Helper of generateSlidingMoves to generate rook moves
let
sideToMove = self.position.sideToMove
occupancy = self.getOccupancy()
enemyPieces = self.getOccupancyFor(sideToMove.opposite())
rooks = self.getBitboard(Rook, sideToMove)
queens = self.getBitboard(Queen, sideToMove)
movableRooks = not self.position.diagonalPins and (queens or rooks)
pinMask = self.position.orthogonalPins
pinnedRooks = movableRooks and pinMask
unpinnedRooks = movableRooks and not pinnedRooks
for square in pinnedRooks:
let
blockers = occupancy and Rook.getRelevantBlockers(square)
moveset = getRookMoves(square, blockers)
for target in moveset and not occupancy and pinMask and mask:
moves.add(createMove(square, target))
for target in moveset and enemyPieces and pinMask and mask:
moves.add(createMove(square, target, Capture))
for square in unpinnedRooks:
let
blockers = occupancy and Rook.getRelevantBlockers(square)
moveset = getRookMoves(square, blockers)
for target in moveset and not occupancy and mask:
moves.add(createMove(square, target))
for target in moveset and enemyPieces and mask:
moves.add(createMove(square, target, Capture))
proc generateBishopMoves(self: Chessboard, moves: var MoveList, mask: Bitboard) =
## Helper of generateSlidingMoves to generate bishop moves
let
sideToMove = self.position.sideToMove
occupancy = self.getOccupancy()
enemyPieces = self.getOccupancyFor(sideToMove.opposite())
bishops = self.getBitboard(Bishop, sideToMove)
queens = self.getBitboard(Queen, sideToMove)
movableBishops = not self.position.orthogonalPins and (queens or bishops)
pinMask = self.position.diagonalPins
pinnedBishops = movableBishops and pinMask
unpinnedBishops = movableBishops and not pinnedBishops
for square in pinnedBishops:
let
blockers = occupancy and Bishop.getRelevantBlockers(square)
moveset = getBishopMoves(square, blockers)
for target in moveset and pinMask and mask:
moves.add(createMove(square, target))
for target in moveset and enemyPieces and pinMask and mask:
moves.add(createMove(square, target, Capture))
for square in unpinnedBishops:
let
blockers = occupancy and Bishop.getRelevantBlockers(square)
moveset = getBishopMoves(square, blockers)
for target in moveset and mask:
moves.add(createMove(square, target))
for target in moveset and enemyPieces and mask:
moves.add(createMove(square, target, Capture))
proc generateKingMoves(self: Chessboard, moves: var MoveList) =
## Generates all legal king moves for the side to move
let
sideToMove = self.position.sideToMove
king = self.getBitboard(King, sideToMove)
occupancy = self.getOccupancy()
nonSideToMove = sideToMove.opposite()
enemyPieces = self.getOccupancyFor(nonSideToMove) and not self.getBitboard(King, nonSideToMove)
bitboard = getKingAttacks(king.toSquare())
noKingOccupancy = occupancy and not king
for square in bitboard and not occupancy:
if not self.isOccupancyAttacked(square, noKingOccupancy):
moves.add(createMove(king, square))
for square in bitboard and enemyPieces:
if not self.isOccupancyAttacked(square, noKingOccupancy):
moves.add(createMove(king, square, Capture))
proc generateKnightMoves(self: Chessboard, moves: var MoveList, mask: Bitboard) =
## Generates all the legal knight moves for the side to move
let
sideToMove = self.position.sideToMove
knights = self.getBitboard(Knight, sideToMove)
nonSideToMove = sideToMove.opposite()
pinned = self.position.diagonalPins or self.position.orthogonalPins
unpinnedKnights = knights and not pinned
enemyPieces = self.getOccupancyFor(nonSideToMove) and not self.getBitboard(King, nonSideToMove)
for square in unpinnedKnights:
let bitboard = getKnightAttacks(square)
for target in bitboard and mask:
moves.add(createMove(square, target))
for target in bitboard and enemyPieces:
moves.add(createMove(square, target, Capture))
proc generateMoves*(self: Chessboard, moves: var MoveList) =
## Generates the list of all possible legal moves
## in the current position
if self.position.halfMoveClock >= 100:
# Draw by 50-move rule
return
let sideToMove = self.position.sideToMove
# TODO: Check for draw by insufficient material
# TODO: Check for repetitions (requires zobrist hashing + table)
self.generateKingMoves(moves)
if self.position.checkers.countSquares() > 1:
# King is in double check: no need to generate any more
# moves
return
if not self.inCheck():
# TODO: Castling
discard
# We pass a mask to our move generators to remove stuff
# like our friendly pieces from the set of possible
# target squares, as well as to ensure checks are not
# ignored
var mask: Bitboard
if not self.inCheck():
# Not in check: cannot move over friendly pieces
mask = not self.getOccupancyFor(sideToMove)
else:
# We *are* in check (from a single piece, because the two checks
# case was handled above already). If the piece is a slider, we'll
# extract the ray from it to our king and add the checking piece to
# it, meaning the only legal moves are those that either block the
# check or capture the checking piece. For other non-sliding pieces
# the ray will be empty so the only legal move will be to capture
# the checking piece
let checker = self.position.checkers.lowestSquare()
mask = getRayBetween(checker, self.getBitboard(King, sideToMove).toSquare()) or checker.toBitboard()
self.generatePawnMoves(moves, mask)
self.generateKnightMoves(moves, mask)
self.generateRookMoves(moves, mask)
self.generateBishopMoves(moves, mask)
# Queens are just handled rooks + bishops
proc removePieceFromBitboard(self: Chessboard, square: Square) =
## Removes a piece at the given square in the chessboard from
## its respective bitboard
let piece = self.grid[square]
self.position.pieces[piece.color][piece.kind][].clearBit(square)
proc addPieceToBitboard(self: Chessboard, square: Square, piece: Piece) =
## Adds the given piece at the given square in the chessboard to
## its respective bitboard
self.position.pieces[piece.color][piece.kind][].setBit(square)
proc spawnPiece(self: Chessboard, square: Square, piece: Piece) =
## Internal helper to "spawn" a given piece at the given
## square
when not defined(danger):
doAssert self.grid[square].kind == Empty
self.addPieceToBitboard(square, piece)
self.grid[square] = piece
proc removePiece(self: Chessboard, square: Square) =
## Removes a piece from the board, updating necessary
## metadata
var piece = self.grid[square]
when not defined(danger):
doAssert piece.kind != Empty and piece.color != None, self.toFEN()
self.removePieceFromBitboard(square)
self.grid[square] = nullPiece()
proc movePiece(self: Chessboard, move: Move) =
## Internal helper to move a piece from
## its current square to a target square
let piece = self.grid[move.startSquare]
when not defined(danger):
let targetSquare = self.getPiece(move.targetSquare)
if targetSquare.color != None:
raise newException(AccessViolationDefect, &"{piece} at {move.startSquare} attempted to overwrite {targetSquare} at {move.targetSquare}: {move}")
# Update positional metadata
self.removePiece(move.startSquare)
self.spawnPiece(move.targetSquare, piece)
proc doMove*(self: Chessboard, move: Move) =
## Internal function called by makeMove after
## performing legality checks. Can be used in
## performance-critical paths where a move is
## already known to be legal (i.e. during search)
# Record final position for future reference
self.positions.add(self.position)
# Final checks
let piece = self.grid[move.startSquare]
when not defined(danger):
doAssert piece.kind != Empty and piece.color != None, &"{move} {self.toFEN()}"
var
halfMoveClock = self.position.halfMoveClock
fullMoveCount = self.position.fullMoveCount
castlingRights = self.position.castlingRights
enPassantTarget = nullSquare()
# Needed to detect draw by the 50 move rule
if piece.kind == Pawn or move.isCapture() or move.isEnPassant():
# Number of half-moves since the last reversible half-move
halfMoveClock = 0
else:
inc(halfMoveClock)
if piece.color == Black:
inc(fullMoveCount)
if move.isDoublePush():
enPassantTarget = move.targetSquare.toBitboard().backwardRelativeTo(piece.color).toSquare()
# Create new position
self.position = Position(plyFromRoot: self.position.plyFromRoot + 1,
halfMoveClock: halfMoveClock,
fullMoveCount: fullMoveCount,
sideToMove: self.position.sideToMove.opposite(),
castlingRights: castlingRights,
enPassantSquare: enPassantTarget,
pieces: self.position.pieces
)
# Update position metadata
if move.isEnPassant():
# Make the en passant pawn disappear
self.removePiece(move.targetSquare.toBitboard().backwardRelativeTo(piece.color).toSquare())
if move.isCapture():
# Get rid of captured pieces
self.removePiece(move.targetSquare)
# Move the piece to its target square
self.movePiece(move)
# TODO: Castling!
if move.isPromotion():
# Move is a pawn promotion: get rid of the pawn
# and spawn a new piece
self.removePiece(move.targetSquare)
case move.getPromotionType():
of PromoteToBishop:
self.spawnPiece(move.targetSquare, Piece(kind: Bishop, color: piece.color))
of PromoteToKnight:
self.spawnPiece(move.targetSquare, Piece(kind: Knight, color: piece.color))
of PromoteToRook:
self.spawnPiece(move.targetSquare, Piece(kind: Rook, color: piece.color))
of PromoteToQueen:
self.spawnPiece(move.targetSquare, Piece(kind: Queen, color: piece.color))
else:
# Unreachable
discard
# Updates checks and pins for the side to move
self.updateChecksAndPins()
proc isLegal*(self: Chessboard, move: Move): bool {.inline.} =
## Returns whether the given move is legal
var moves = MoveList()
self.generateMoves(moves)
return move in moves
proc makeMove*(self: Chessboard, move: Move): Move {.discardable.} =
## Makes a move on the board
result = move
# Updates checks and pins for the side to move
self.updateChecksAndPins()
if not self.isLegal(move):
return nullMove()
self.doMove(move)
proc unmakeMove*(self: Chessboard) =
## Reverts to the previous board position,
## if one exists
self.position = self.positions.pop()
self.update()