~macaptain/lkdo-chess

4a145c47f8fbfa347527f38f5105792fa96cc9e7 — Michael Captain 7 months ago 21e5e0d
Add king attacks with tests
3 files changed, 56 insertions(+), 4 deletions(-)

M src/attack.zig
M src/main.zig
M test/attack.zig
M src/attack.zig => src/attack.zig +21 -1
@@ 68,7 68,27 @@ pub fn knightAttacks(knight: Square) u64 {
const king_attacks = initKingAttacks();

fn initKingAttacks() [64]u64 {
    return 0;
    comptime {
        var sq: u8 = 0;
        var attacks: [64]u64 = undefined;
        while (sq < 64) : (sq += 1) {
            attacks[sq] = maskKingAttacks(@intToEnum(Square, sq));
        }
        return attacks;
    }
}

fn maskKingAttacks(king: Square) u64 {
    const bitboard = bitboardFromSquare(king);
    var attacks = bitboard >> 8;
    attacks |= bitboard >> 7 & mask_not_a;
    attacks |= bitboard << 1 & mask_not_a;
    attacks |= bitboard << 9 & mask_not_a;
    attacks |= bitboard << 8;
    attacks |= bitboard << 7 & mask_not_h;
    attacks |= bitboard >> 1 & mask_not_h;
    attacks |= bitboard >> 9 & mask_not_h;
    return attacks;
}

pub fn kingAttacks(king: Square) u64 {

M src/main.zig => src/main.zig +1 -3
@@ 32,9 32,7 @@ fn bitboardBuilder() void {
        var file: u6 = 0;
        while (file < 8) : (file += 1) {
            const square = 8 * rank + file;
            if (file != 6 and file != 7) {
                bitboard |= @as(u64, 1) << square;
            }
            bitboard |= @as(u64, 1) << square;
        }
    }
    board.printBitboard(bitboard);

M test/attack.zig => test/attack.zig +34 -0
@@ 94,3 94,37 @@ test "knights in corners attack only 2 squares" {
    expectEqual(bitboardFromSquares(expected_h1[0..]), knightAttacks(knight_h1));
    expectEqual(bitboardFromSquares(expected_a1[0..]), knightAttacks(knight_a1));
}

test "king in center attacks all 8 squares" {
    const king = Square.d4;
    const expected_attacked_squares = [8]Square{
        Square.d5,
        Square.e5,
        Square.e4,
        Square.e3,
        Square.d3,
        Square.c3,
        Square.c4,
        Square.c5,
    };
    const expected = bitboardFromSquares(expected_attacked_squares[0..]);
    const actual = kingAttacks(king);
    expectEqual(expected, actual);
}

test "kings in corners attack only 3 squares" {
    const king_a8 = Square.a8;
    const king_h8 = Square.h8;
    const king_h1 = Square.h1;
    const king_a1 = Square.a1;

    const expected_a8 = [3]Square{ Square.b8, Square.b7, Square.a7 };
    const expected_h8 = [3]Square{ Square.h7, Square.g7, Square.g8 };
    const expected_h1 = [3]Square{ Square.g1, Square.g2, Square.h2 };
    const expected_a1 = [3]Square{ Square.a2, Square.b2, Square.b1 };

    expectEqual(bitboardFromSquares(expected_a8[0..]), kingAttacks(king_a8));
    expectEqual(bitboardFromSquares(expected_h8[0..]), kingAttacks(king_h8));
    expectEqual(bitboardFromSquares(expected_h1[0..]), kingAttacks(king_h1));
    expectEqual(bitboardFromSquares(expected_a1[0..]), kingAttacks(king_a1));
}