~macaptain/lkdo-chess

ref: 21e5e0dc3de477df4b250673eb89c4e94aa00c2d lkdo-chess/src/board.zig -rw-r--r-- 2.0 KiB
21e5e0dcMichael Captain Add knight attacks with tests 1 year, 3 months ago
                                                                                
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
const std = @import("std");

pub const Side = enum(u1) {
    White,
    Black,
};

// zig fmt: off
pub const Square = packed enum(u6) {
    a8, b8, c8, d8, e8, f8, g8, h8,
    a7, b7, c7, d7, e7, f7, g7, h7,
    a6, b6, c6, d6, e6, f6, g6, h6,
    a5, b5, c5, d5, e5, f5, g5, h5,
    a4, b4, c4, d4, e4, f4, g4, h4,
    a3, b3, c3, d3, e3, f3, g3, h3,
    a2, b2, c2, d2, e2, f2, g2, h2,
    a1, b1, c1, d1, e1, f1, g1, h1,
};
// zig fmt: on

const Board = struct {
    wP: u64,
    wN: u64,
    wB: u64,
    wR: u64,
    wQ: u64,
    wK: u64,
    bP: u64,
    bN: u64,
    bB: u64,
    bR: u64,
    bQ: u64,
    bK: u64,
    wCastlePerm: bool,
    bCastlePerm: bool,
    movesSinceCapture: u16,
    whiteToMove: bool,
};

pub fn printBitboard(bitboard: u64) void {
    var rank: u6 = 0;
    while (rank < 8) : (rank += 1) {
        var file: u6 = 0;
        while (file < 8) : (file += 1) {
            const square = 8 * rank + file;
            const occupied: u8 = if (getBit(bitboard, square)) 1 else 0;
            std.debug.print(" {d} ", .{occupied});
        }
        std.debug.print("\n", .{});
    }
    std.debug.print("bitboard: {x}\n", .{bitboard});
}

fn getBit(bitboard: u64, square: u6) bool {
    const mask = @as(u64, 1) << square;
    return bitboard & mask != 0;
}

fn setBit(bitboard: u64, square: Square) u64 {
    const mask = @as(u64, 1) << @enumToInt(square);
    return bitboard | mask;
}

fn setBits(bitboard: u64, squares: []const Square) u64 {
    var new_bitboard = bitboard;
    for (squares) |square| {
        new_bitboard = setBit(new_bitboard, square);
    }
    return new_bitboard;
}

pub fn bitboardFromSquare(square: Square) u64 {
    return setBit(@as(u64, 0), square);
}

pub fn bitboardFromSquares(squares: []const Square) u64 {
    return setBits(@as(u64, 0), squares);
}

pub fn resetBit(bitboard: u64, square: Square) u64 {
    const mask = @as(u64, 1) << @enumToInt(square);
    return if (getBit(bitboard, @enumToInt(square)))
        bitboard ^ mask
    else
        bitboard;
}