bitstackchess 0.1.1

A bitboard‐based chess game engine with 10 × u128 move history
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! MoveGenerator: generate all pseudo‐legal Move10s (ignoring checks) for a given side.
//!
//! Sliding attacks (rooks, bishops, queens), knights, pawns, and king moves (including castling).
//! Does not test for moving into check—that is handled elsewhere.

use crate::core::Move10;
use crate::board::{PieceMapping, Occupied};
use crate::rules::castling::CastlingLogic;

/// All eight knight‐move offsets (as signed (rank, file) pairs).
const KNIGHT_OFFSETS: &[(i8, i8)] = &[
    ( 2,  1), ( 2, -1), (-2,  1), (-2, -1),
    ( 1,  2), ( 1, -2), (-1,  2), (-1, -2),
];

/// All eight king‐adjacent offsets.
const KING_OFFSETS: &[(i8, i8)] = &[
    ( 1,  0), ( 1,  1), ( 0,  1), (-1,  1),
    (-1,  0), (-1, -1), ( 0, -1), ( 1, -1),
];

/// Directions for sliding pieces: (rank_delta, file_delta).
const ORTHO_DIRS: &[(i8, i8)] = &[( 1,  0), (-1,  0), ( 0,  1), ( 0, -1)];
const DIAG_DIRS:  &[(i8, i8)] = &[( 1,  1), ( 1, -1), (-1,  1), (-1, -1)];

/// Return (rank, file) from a 0..63 square index.
#[inline]
fn sq_to_coords(sq: u8) -> (i8, i8) {
    ((sq >> 3) as i8, (sq & 7) as i8)
}

/// Return 0..63 index from (rank, file). Assumes valid 0..7.
#[inline]
fn coords_to_sq(rank: i8, file: i8) -> u8 {
    ((rank as u8) << 3) | (file as u8)
}

/// Return true if (rank, file) is on board.
#[inline]
fn on_board(rank: i8, file: i8) -> bool {
    (0..8).contains(&rank) && (0..8).contains(&file)
}

/// Given a piece PID (0..31), return its “piece‐type code”:
///   0..7  = White pawn group
///   8..9  = White rooks
///   10..11= White knights
///   12..13= White bishops
///   14    = White queen
///   15    = White king
///   16..23= Black pawns
///   24..25= Black rooks
///   26..27= Black knights
///   28..29= Black bishops
///   30    = Black queen
///   31    = Black king
#[inline]
fn piece_type(pid: u8) -> u8 {
    pid
}

/// Return true if a given PID is a “pawn” type.
#[inline]
fn is_pawn(pid: u8) -> bool {
    (0..8).contains(&pid) || (16..24).contains(&pid)
}

/// Return true if a given PID is White (0..15) or Black (16..31).
#[inline]
fn color_of(pid: u8) -> u8 {
    if pid < 16 { 0 } else { 1 }
}

/// Return side’s starting pawn rank: White=1, Black=6.
#[inline]
fn pawn_home_rank(color: u8) -> i8 {
    if color == 0 { 1 } else { 6 }
}

/// Return the forward direction for pawns: White=+1, Black=−1.
#[inline]
fn pawn_dir(color: u8) -> i8 {
    if color == 0 { 1 } else { -1 }
}

/// Return true if the given dest square is exactly the en-passant target.
#[inline]
fn is_ep_target(dest: u8, ep_target: Option<u8>) -> bool {
    if let Some(t) = ep_target {
        t == dest
    } else {
        false
    }
}

/// Primary generator struct (all methods are static).
pub struct MoveGenerator;

impl MoveGenerator {
    /// Generate all pseudo-legal moves for `side` (0=White, 1=Black).
    pub fn generate(
        mapping: &PieceMapping,
        occupied: Occupied,
        captured_bits: u32,
        en_passant_target: Option<u8>,
        side: u8,
    ) -> Vec<Move10> {
        let mut moves = Vec::new();
        // For each PID in 0..31 of the given side:
        let start_pid = if side == 0 { 0 } else { 16 };
        let end_pid = start_pid + 16;
        for pid in start_pid..end_pid {
            if let Some(src_sq) = mapping.piece_square[pid as usize] {
                let sq = src_sq;
                let (r, f) = sq_to_coords(sq);
                let piece = piece_type(pid);
                match piece {
                    // Pawn group: 0..7 white, 16..23 black
                    p if is_pawn(p) => {
                        Self::pawn_moves(pid, r, f, mapping, occupied, en_passant_target, &mut moves);
                    }
                    // White/Black knight
                    10..=11 | 26..=27 => {
                        Self::knight_moves(pid, r, f, mapping, occupied, &mut moves);
                    }
                    // White/Black bishop
                    12..=13 | 28..=29 => {
                        Self::bishop_moves(pid, r, f, mapping, occupied, &mut moves);
                    }
                    // White/Black rook
                    8..=9   | 24..=25 => {
                        Self::rook_moves(pid, r, f, mapping, occupied, &mut moves);
                    }
                    // White/Black queen
                    14 | 30 => {
                        Self::rook_moves(pid, r, f, mapping, occupied, &mut moves);
                        Self::bishop_moves(pid, r, f, mapping, occupied, &mut moves);
                    }
                    // White/Black king
                    15 | 31 => {
                        Self::king_moves(pid, r, f, mapping, occupied, side, en_passant_target, &mut moves);
                    }
                    _ => { /* no other piece types */ }
                }
            }
        }
        moves
    }

    /// Generate pawn moves for PID at (r,f).
    fn pawn_moves(
        pid: u8,
        r: i8,
        f: i8,
        mapping: &PieceMapping,
        occupied: Occupied,
        ep_target: Option<u8>,
        moves: &mut Vec<Move10>,
    ) {
        let side = color_of(pid);
        let dir = pawn_dir(side);
        // 1) Single-step forward:
        let r1 = r + dir;
        let f1 = f;
        if on_board(r1, f1) {
            let sq1 = coords_to_sq(r1, f1);
            if (occupied >> sq1) & 1 == 0 {
                // Quiet move (push)
                let pid_within = pid % 16;
                moves.push(Move10::new(pid_within, sq1));
                // 2) Double-step from home rank:
                let home_rank = pawn_home_rank(side);
                if r == home_rank {
                    let r2 = r + 2 * dir;
                    if on_board(r2, f1) {
                        let sq2 = coords_to_sq(r2, f1);
                        if (occupied >> sq2) & 1 == 0 {
                            // Both intermediate and dest empty
                            let between = coords_to_sq(r + dir, f);
                            if (occupied >> between) & 1 == 0 {
                                moves.push(Move10::new(pid_within, sq2));
                            }
                        }
                    }
                }
            }
        }

        // 3) Captures & en-passant:
        for df in &[-1, 1] {
            let rf = r + dir;
            let ff = f + df;
            if on_board(rf, ff) {
                let dest_sq = coords_to_sq(rf, ff);
                let pid_within = pid % 16;
                // En-passant capture:
                if is_ep_target(dest_sq, ep_target) {
                    moves.push(Move10::new(pid_within, dest_sq));
                } else if let Some(opp_pid) = mapping.who_on_square(dest_sq) {
                    if color_of(opp_pid) != side {
                        moves.push(Move10::new(pid_within, dest_sq));
                    }
                }
            }
        }
    }

    /// Generate knight moves for PID at (r,f).
    fn knight_moves(
        pid: u8,
        r: i8,
        f: i8,
        mapping: &PieceMapping,
        occupied: Occupied,
        moves: &mut Vec<Move10>,
    ) {
        let side = color_of(pid);
        let pid_within = pid % 16;
        for &(dr, df) in KNIGHT_OFFSETS {
            let nr = r + dr;
            let nf = f + df;
            if on_board(nr, nf) {
                let nsq = coords_to_sq(nr, nf);
                if let Some(other) = mapping.who_on_square(nsq) {
                    if color_of(other) == side {
                        continue;
                    }
                }
                moves.push(Move10::new(pid_within, nsq));
            }
        }
    }

    /// Generate sliding bishop moves for PID at (r,f).
    fn bishop_moves(
        pid: u8,
        r: i8,
        f: i8,
        mapping: &PieceMapping,
        occupied: Occupied,
        moves: &mut Vec<Move10>,
    ) {
        let side = color_of(pid);
        let pid_within = pid % 16;
        for &(dr, df) in DIAG_DIRS {
            let mut nr = r + dr;
            let mut nf = f + df;
            while on_board(nr, nf) {
                let sq = coords_to_sq(nr, nf);
                if let Some(other) = mapping.who_on_square(sq) {
                    if color_of(other) != side {
                        moves.push(Move10::new(pid_within, sq));
                    }
                    break;
                } else {
                    moves.push(Move10::new(pid_within, sq));
                }
                nr += dr;
                nf += df;
            }
        }
    }

    /// Generate sliding rook moves for PID at (r,f).
    fn rook_moves(
        pid: u8,
        r: i8,
        f: i8,
        mapping: &PieceMapping,
        occupied: Occupied,
        moves: &mut Vec<Move10>,
    ) {
        let side = color_of(pid);
        let pid_within = pid % 16;
        for &(dr, df) in ORTHO_DIRS {
            let mut nr = r + dr;
            let mut nf = f + df;
            while on_board(nr, nf) {
                let sq = coords_to_sq(nr, nf);
                if let Some(other) = mapping.who_on_square(sq) {
                    if color_of(other) != side {
                        moves.push(Move10::new(pid_within, sq));
                    }
                    break;
                } else {
                    moves.push(Move10::new(pid_within, sq));
                }
                nr += dr;
                nf += df;
            }
        }
    }

    /// Generate king moves for PID at (r,f), including castling.
    fn king_moves(
        pid: u8,
        r: i8,
        f: i8,
        mapping: &PieceMapping,
        occupied: Occupied,
        side: u8,
        ep_target: Option<u8>,
        moves: &mut Vec<Move10>,
    ) {
        let pid_within = pid % 16;
        // Normal adjacency moves:
        for &(dr, df) in KING_OFFSETS {
            let nr = r + dr;
            let nf = f + df;
            if on_board(nr, nf) {
                let sq = coords_to_sq(nr, nf);
                if let Some(other) = mapping.who_on_square(sq) {
                    if color_of(other) != side {
                        moves.push(Move10::new(pid_within, sq));
                    }
                } else {
                    moves.push(Move10::new(pid_within, sq));
                }
            }
        }

        // Castling:
        if side == 0 {
            // White king PID=15 at e1=4
            if r == 0 && f == 4 {
                // Kingside:
                if CastlingLogic::can_white_kingside(mapping, occupied) {
                    moves.push(Move10::new(pid_within, 6)); // g1
                }
                // Queenside:
                if CastlingLogic::can_white_queenside(mapping, occupied) {
                    moves.push(Move10::new(pid_within, 2)); // c1
                }
            }
        } else {
            // Black king PID=31 at e8=60
            if r == 7 && f == 4 {
                if CastlingLogic::can_black_kingside(mapping, occupied) {
                    moves.push(Move10::new(pid_within, 62)); // g8
                }
                if CastlingLogic::can_black_queenside(mapping, occupied) {
                    moves.push(Move10::new(pid_within, 58)); // c8
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::board::{encode_square, init_chess_positions, PieceMapping};

    #[test]
    fn simple_pawn_push_capture() {
        let mut mapping = PieceMapping::new_empty();
        let mut occupied: u64 = 0;

        // Place White pawn PID=0 on b2=encode_square(1,1)=9
        mapping.place_piece(0, encode_square(1, 1));
        occupied |= 1u64 << 9;
        // Place Black pawn PID=17 on c3=encode_square(2,2)=18
        mapping.place_piece(17, encode_square(2, 2));
        occupied |= 1u64 << 18;

        let moves = MoveGenerator::generate(&mapping, occupied, 0, None, 0);
        // Pawn at 9: should see push to 17 (b3) and capture to 18 (c3).
        let mut found = false;
        for mv in moves {
            if mv.piece_id() == 0 && mv.dest() == 17 {
                found = true;
            }
            if mv.piece_id() == 0 && mv.dest() == 18 {
                found = true;
            }
        }
        assert!(found);
    }

    #[test]
    fn knight_jumps_and_blocking() {
        let mut mapping = PieceMapping::new_empty();
        let mut occupied: u64 = 0;

        // Place White knight PID=10 on g1=6
        mapping.place_piece(10, encode_square(0, 6));
        occupied |= 1u64 << 6;
        // Block destination f3=encode_square(2,5)=21 with white pawn PID=5
        mapping.place_piece(5, encode_square(2, 5));
        occupied |= 1u64 << 21;
        // Enemy at e2=encode_square(1,4)=12 with black pawn PID=20
        mapping.place_piece(20, encode_square(1, 4));
        occupied |= 1u64 << 12;

        let moves = MoveGenerator::generate(&mapping, occupied, 0, None, 0);
        // Knight at 6: jumps to f3=21 is blocked by friendly, but capture at e2=12 is allowed.
        let mut found_capture = false;
        for mv in moves {
            if mv.piece_id() == 10 && mv.dest() == 12 {
                found_capture = true;
            }
        }
        assert!(found_capture);
    }

    #[test]
    fn sliding_rook_moves() {
        let mut mapping = PieceMapping::new_empty();
        let mut occupied: u64 = 0;

        // Place White rook PID=8 at d4=encode_square(3,3)=27
        mapping.place_piece(8, encode_square(3, 3));
        occupied |= 1u64 << 27;
        // Place friend at d6=encode_square(5,3)=43, enemy at d2=encode_square(1,3)=11
        mapping.place_piece(3, encode_square(5, 3));
        occupied |= 1u64 << 43;
        mapping.place_piece(19, encode_square(1, 3));
        occupied |= 1u64 << 11;

        let moves = MoveGenerator::generate(&mapping, occupied, 0, None, 0);
        // Rook at 27 can move up to d5=35, then hits friend at 43 (so no further). And can move down to d2=11 (capture).
        let mut saw_d5 = false;
        let mut saw_d2 = false;
        for mv in moves {
            if mv.piece_id() == 8 && mv.dest() == 35 {
                saw_d5 = true;
            }
            if mv.piece_id() == 8 && mv.dest() == 11 {
                saw_d2 = true;
            }
        }
        assert!(saw_d5 && saw_d2);
    }

    #[test]
    fn castling_generation() {
        // Starting position, castling squares should appear in MoveGenerator.
        let pos = init_chess_positions();
        let mut mapping = PieceMapping::new_empty();
        let mut occupied: u64 = 0;
        for &(pid, sq) in &pos {
            mapping.place_piece(pid, sq);
            occupied |= 1u64 << (sq as u64);
        }

        // Remove pieces blocking f1=5 (PID=13) and g1=6 (PID=11) so castling is possible
        mapping.remove_piece(13);
        mapping.remove_piece(11);
        occupied &= !(1u64 << encode_square(0, 5)); // f1
        occupied &= !(1u64 << encode_square(0, 6)); // g1

        let moves_wh = MoveGenerator::generate(&mapping, occupied, 0, None, 0);
        // At modified starting pos (f1/g1 empty), White can castle kingside (king at e1=4, rook at h1=7).
        let mut found_ck = false;
        for mv in moves_wh {
            if mv.piece_id() == 15 && mv.dest() == 6 {
                found_ck = true;
            }
        }
        assert!(found_ck);
    }
}