forked from notnil/chess
-
Notifications
You must be signed in to change notification settings - Fork 2
/
bitboard.go
61 lines (55 loc) · 1.28 KB
/
bitboard.go
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
package chess
import (
"strconv"
"strings"
)
// bitboard is a board representation encoded in an unsigned 64-bit integer. The
// 64 board positions begin with A1 as the most significant bit and H8 as the least.
type bitboard uint64
func newBitboard(m map[Square]bool) bitboard {
s := ""
for sq := 0; sq < numOfSquaresInBoard; sq++ {
if m[Square(sq)] {
s += "1"
} else {
s += "0"
}
}
bb, err := strconv.ParseUint(s, 2, 64)
if err != nil {
panic(err)
}
return bitboard(bb)
}
func (b bitboard) Mapping() map[Square]bool {
m := map[Square]bool{}
for sq := 0; sq < numOfSquaresInBoard; sq++ {
if b&bbForSquare(Square(sq)) > 0 {
m[Square(sq)] = true
}
}
return m
}
// String returns a 64 character string of 1s and 0s starting with the most significant bit.
func (b bitboard) String() string {
s := strconv.FormatUint(uint64(b), 2)
return strings.Repeat("0", numOfSquaresInBoard-len(s)) + s
}
// Draw returns visual representation of the bitboard useful for debugging.
func (b bitboard) Draw() string {
s := "\n A B C D E F G H\n"
for r := 7; r >= 0; r-- {
s += Rank(r).String()
for f := 0; f < numOfSquaresInRow; f++ {
sq := getSquare(File(f), Rank(r))
if b.Occupied(sq) {
s += "1"
} else {
s += "0"
}
s += " "
}
s += "\n"
}
return s
}