Skip to content

Commit

Permalink
Look for the outermost rook for castling kingside
Browse files Browse the repository at this point in the history
In X-FEN notation, KQkq always refers to the respective
outermost rook. So, in kingside we need to look for the most right
rook on the board.
  • Loading branch information
lenguyenthanh committed Nov 5, 2023
1 parent 963c9e5 commit 6c0b135
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
14 changes: 13 additions & 1 deletion src/main/scala/bitboard/Bitboard.scala
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ object Bitboard:

def knightAttacks: Bitboard = KNIGHT_ATTACKS(s.value)

extension (l: Long) private def lsb: Square = Square.unsafe(java.lang.Long.numberOfTrailingZeros(l))
extension (l: Long)
private def lsb: Square = Square.unsafe(java.lang.Long.numberOfTrailingZeros(l))
private def msb: Square = Square.unsafe(63 - java.lang.Long.numberOfLeadingZeros(l))

extension (a: Bitboard)
inline def value: Long = a
Expand Down Expand Up @@ -136,6 +138,16 @@ object Bitboard:
b &= (b - 1L)
result

// tests
def findLast(f: Square => Boolean): Option[Square] =
var b = a
var result: Option[Square] = None
while b != 0L && result.isEmpty
do
if f(b.msb) then result = Some(b.msb)
b &= (b - 1L)
result

def fold[B](init: B)(f: (B, Square) => B): B =
var b = a
var result = init
Expand Down
3 changes: 2 additions & 1 deletion src/main/scala/format/FenReader.scala
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,13 @@ trait FenReader:
case ((c, r), ch) =>
val color = Color.fromWhite(ch.isUpper)
val backRank = Bitboard.rank(color.backRank)
// rooks that can be used for castling
val rooks = board.rooks & board(color) & backRank
{
for
kingSquare <- (board.kingOf(color) & backRank).first
rookSquare <- ch.toLower match
case 'k' => rooks.find(_ ?> kingSquare)
case 'k' => rooks.findLast(_ ?> kingSquare)
case 'q' => rooks.find(_ ?< kingSquare)
case file => rooks.find(_.file.char == file)
side <- Side.kingRookSide(kingSquare, rookSquare)
Expand Down

0 comments on commit 6c0b135

Please sign in to comment.