-
Notifications
You must be signed in to change notification settings - Fork 1
Knight move generation
This page contains descriptions of the general logic behind finding possible moves for knights. This page will go into much less detail than the Pawn move generation page so it is recommended to read that first.
- Understanding Bit-shifting - https://www.interviewcake.com/concept/java/bit-shift
- Understanding bitwise operations
- Understanding bitboards and the board representation used in this project - See board representation wiki
A knight can move in 8 different directions
2 3
1 4
N
8 5
7 6
A knight can move in any of these directions as long as there is non of its own pieces on that square already.
Calculating each move is fairly simple and requires only 6 bitboards
| White knight bitboard (Current) | Own pieces bitboard | not-A-file | not-AB-file | not-H-file | not-HG-file |
|---|---|---|---|---|---|
|
|
|
|
|
|
Calculating the moves of knights share the same problems as with pawns and kings. Moving outside the board is a real possibility and since the knight can move two squares in either direction, it can now occur on the H G A, and B files. To avoid moving outside of the board we utilize some helper bitboards not-H-file, not-HG-file, not-AB-file, and not-AB-file. If the knight is on A, we don't want to calculate positions to the left and if the knight is on H we do not want to calculate positions to the right (Since they will be off the board).
See the directions page to get an overview of the number of bitshifts to calculate a move in a specific direction.
This is how each single move is calculated:
- ((knight bitboard & not-AB-file) << 10)
- ((knight bitboard & not-A-file) << 17)
- ((knight bitboard & not-H-file) << 15)
- ((knight bitboard & not-HG-file) << 6)
- knight-so-e-e ((knight bitboard & not-HG-file) >>> 10)
- knight-so-so-e ((knight bitboard & not-H-file) >>> 17)
- knight-so-so-w ((knight bitboard & not-A-file) >>> 15)
- knight-so-w-w ((knight bitboard & not-AB-file) >>> 6)
Last but not least we need to make sure that there is not one of our own pieces on those squares. The way we can do that is by taking the inverse of Own pieces bitboard using the bitwise NOT operator '~' (~Own pieces bitboard)
Then we can use the bitwise and operator '&' to remove all moves where our own pieces already are located
| Knight moves all directions | ~Own pieces bitboard | Knight moves | ||
|---|---|---|---|---|
|
& |
|
= |
|