forked from notnil/chess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
board.go
531 lines (495 loc) · 15.3 KB
/
board.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
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
package chess
import (
"bytes"
"encoding/binary"
"errors"
"strconv"
"strings"
"github.com/logrusorgru/aurora"
"github.com/olekukonko/tablewriter"
)
// A Board represents a chess board and its relationship between squares and pieces.
type Board struct {
bbWhiteKing bitboard
bbWhiteQueen bitboard
bbWhiteRook bitboard
bbWhiteBishop bitboard
bbWhiteKnight bitboard
bbWhitePawn bitboard
bbBlackKing bitboard
bbBlackQueen bitboard
bbBlackRook bitboard
bbBlackBishop bitboard
bbBlackKnight bitboard
bbBlackPawn bitboard
whiteSqs bitboard
blackSqs bitboard
emptySqs bitboard
whiteKingSq Square
blackKingSq Square
}
// NewBoard returns a board from a square to piece mapping.
func NewBoard(m map[Square]Piece) *Board {
b := &Board{}
for _, p1 := range allPieces {
bm := map[Square]bool{}
for sq, p2 := range m {
if p1 == p2 {
bm[sq] = true
}
}
bb := newBitboard(bm)
b.setBBForPiece(p1, bb)
}
b.calcConvienceBBs(nil)
return b
}
// SquareMap returns a mapping of squares to pieces. A square is only added to the map if it is occupied.
func (b *Board) SquareMap() map[Square]Piece {
m := map[Square]Piece{}
for sq := 0; sq < numOfSquaresInBoard; sq++ {
p := b.Piece(Square(sq))
if p != NoPiece {
m[Square(sq)] = p
}
}
return m
}
// Rotate rotates the board 90 degrees clockwise.
func (b *Board) Rotate() *Board {
return b.Flip(UpDown).Transpose()
}
// FlipDirection is the direction for the Board.Flip method
type FlipDirection int
const (
// UpDown flips the board's rank values
UpDown FlipDirection = iota
// LeftRight flips the board's file values
LeftRight
)
// Flip flips the board over the vertical or hoizontal
// center line.
func (b *Board) Flip(fd FlipDirection) *Board {
m := map[Square]Piece{}
for sq := 0; sq < numOfSquaresInBoard; sq++ {
var mv Square
switch fd {
case UpDown:
file := Square(sq).File()
rank := Rank(7 - Square(sq).Rank())
mv = getSquare(file, rank)
case LeftRight:
file := File(7 - Square(sq).File())
rank := Square(sq).Rank()
mv = getSquare(file, rank)
}
m[mv] = b.Piece(Square(sq))
}
return NewBoard(m)
}
// Transpose flips the board over the A8 to H1 diagonal.
func (b *Board) Transpose() *Board {
m := map[Square]Piece{}
for sq := 0; sq < numOfSquaresInBoard; sq++ {
file := File(7 - Square(sq).Rank())
rank := Rank(7 - Square(sq).File())
mv := getSquare(file, rank)
m[mv] = b.Piece(Square(sq))
}
return NewBoard(m)
}
var (
ConsoleUnicode = true // This console supports unicode printing.
ConsoleDark = false // This console has a dark background.
ConsoleColor = true // This console supports color printing.
)
// Draw returns visual representation of the board useful for debugging.
func (b *Board) Draw() string {
au := aurora.NewAurora(ConsoleColor)
tableBuf := new(bytes.Buffer)
table := tablewriter.NewWriter(tableBuf)
table.SetRowLine(true)
table.SetHeader([]string{"", "A", "B", "C", "D", "E", "F", "G", "H"})
if ConsoleUnicode { // Enhance tablewriter with unicode lines.
table.SetCenterSeparator(au.Gray(6, "┼").String())
table.SetColumnSeparator(au.Gray(6, "│").String())
table.SetRowSeparator(au.Gray(6, "─").String())
}
if ConsoleColor {
table.SetHeaderColor(
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
)
table.SetColumnColor(
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
tablewriter.Colors{tablewriter.Normal, tablewriter.Normal},
tablewriter.Colors{tablewriter.Normal, tablewriter.Normal},
tablewriter.Colors{tablewriter.Normal, tablewriter.Normal},
tablewriter.Colors{tablewriter.Normal, tablewriter.Normal},
tablewriter.Colors{tablewriter.Normal, tablewriter.Normal},
tablewriter.Colors{tablewriter.Normal, tablewriter.Normal},
tablewriter.Colors{tablewriter.Normal, tablewriter.Normal},
tablewriter.Colors{tablewriter.Normal, tablewriter.Normal},
)
}
s := make([]string, numOfSquaresInRow+1)
for r := 7; r >= 0; r-- {
s[0] = Rank(r).String()
for f := 0; f < numOfSquaresInRow; f++ {
p := b.Piece(getSquare(File(f), Rank(r)))
if p == NoPiece {
s[f+1] = ""
} else {
s[f+1] = p.String()
}
}
table.Append(s)
}
table.Render()
return tableBuf.String()
}
// Draw returns visual representation of the board for the black side.
func (b *Board) DrawForBlack() string {
au := aurora.NewAurora(ConsoleColor)
tableBuf := new(bytes.Buffer)
table := tablewriter.NewWriter(tableBuf)
table.SetRowLine(true)
table.SetHeader([]string{"", "H", "G", "F", "E", "D", "C", "B", "A"})
if ConsoleUnicode { // Enhance tablewriter with unicode lines.
table.SetCenterSeparator(au.Gray(6, "┼").String())
table.SetColumnSeparator(au.Gray(6, "│").String())
table.SetRowSeparator(au.Gray(6, "─").String())
}
if ConsoleColor {
table.SetHeaderColor(
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
)
table.SetColumnColor(
tablewriter.Colors{tablewriter.Normal, tablewriter.FgHiBlackColor},
tablewriter.Colors{tablewriter.Normal, tablewriter.Normal},
tablewriter.Colors{tablewriter.Normal, tablewriter.Normal},
tablewriter.Colors{tablewriter.Normal, tablewriter.Normal},
tablewriter.Colors{tablewriter.Normal, tablewriter.Normal},
tablewriter.Colors{tablewriter.Normal, tablewriter.Normal},
tablewriter.Colors{tablewriter.Normal, tablewriter.Normal},
tablewriter.Colors{tablewriter.Normal, tablewriter.Normal},
tablewriter.Colors{tablewriter.Normal, tablewriter.Normal},
)
}
bb := b.Rotate().Rotate() // Rotate to black side.
s := make([]string, numOfSquaresInRow+1)
i := 0 // Invert the file. We are on the black side.
for r := 7; r >= 0; r-- {
s[0] = Rank(i).String()
i++
for f := 0; f < numOfSquaresInRow; f++ {
p := bb.Piece(getSquare(File(f), Rank(r)))
if p == NoPiece {
s[f+1] = ""
} else {
s[f+1] = p.String()
}
}
table.Append(s)
}
table.Render()
return tableBuf.String()
}
// String implements the fmt.Stringer interface and returns
// a string in the FEN board format: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR
func (b *Board) String() string {
fen := ""
for r := 7; r >= 0; r-- {
for f := 0; f < numOfSquaresInRow; f++ {
sq := getSquare(File(f), Rank(r))
p := b.Piece(sq)
if p != NoPiece {
fen += p.getFENChar()
} else {
fen += "1"
}
}
if r != 0 {
fen += "/"
}
}
for i := 8; i > 1; i-- {
repeatStr := strings.Repeat("1", i)
countStr := strconv.Itoa(i)
fen = strings.Replace(fen, repeatStr, countStr, -1)
}
return fen
}
// Piece returns the piece for the given square.
func (b *Board) Piece(sq Square) Piece {
for _, p := range allPieces {
bb := b.bbForPiece(p)
if bb.Occupied(sq) {
return p
}
}
return NoPiece
}
// MarshalText implements the encoding.TextMarshaler interface and returns
// a string in the FEN board format: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR
func (b *Board) MarshalText() (text []byte, err error) {
return []byte(b.String()), nil
}
// UnmarshalText implements the encoding.TextUnarshaler interface and takes
// a string in the FEN board format: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR
func (b *Board) UnmarshalText(text []byte) error {
cp, err := fenBoard(string(text))
if err != nil {
return err
}
*b = *cp
return nil
}
// MarshalBinary implements the encoding.BinaryMarshaler interface and returns
// the bitboard representations as a array of bytes. Bitboads are encoded
// in the following order: WhiteKing, WhiteQueen, WhiteRook, WhiteBishop, WhiteKnight
// WhitePawn, BlackKing, BlackQueen, BlackRook, BlackBishop, BlackKnight, BlackPawn
func (b *Board) MarshalBinary() (data []byte, err error) {
bbs := []bitboard{b.bbWhiteKing, b.bbWhiteQueen, b.bbWhiteRook, b.bbWhiteBishop, b.bbWhiteKnight, b.bbWhitePawn,
b.bbBlackKing, b.bbBlackQueen, b.bbBlackRook, b.bbBlackBishop, b.bbBlackKnight, b.bbBlackPawn}
buf := new(bytes.Buffer)
err = binary.Write(buf, binary.BigEndian, bbs)
return buf.Bytes(), err
}
// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface and parses
// the bitboard representations as a array of bytes. Bitboads are decoded
// in the following order: WhiteKing, WhiteQueen, WhiteRook, WhiteBishop, WhiteKnight
// WhitePawn, BlackKing, BlackQueen, BlackRook, BlackBishop, BlackKnight, BlackPawn
func (b *Board) UnmarshalBinary(data []byte) error {
if len(data) != 96 {
return errors.New("chess: invalid number of bytes for board unmarshal binary")
}
b.bbWhiteKing = bitboard(binary.BigEndian.Uint64(data[:8]))
b.bbWhiteQueen = bitboard(binary.BigEndian.Uint64(data[8:16]))
b.bbWhiteRook = bitboard(binary.BigEndian.Uint64(data[16:24]))
b.bbWhiteBishop = bitboard(binary.BigEndian.Uint64(data[24:32]))
b.bbWhiteKnight = bitboard(binary.BigEndian.Uint64(data[32:40]))
b.bbWhitePawn = bitboard(binary.BigEndian.Uint64(data[40:48]))
b.bbBlackKing = bitboard(binary.BigEndian.Uint64(data[48:56]))
b.bbBlackQueen = bitboard(binary.BigEndian.Uint64(data[56:64]))
b.bbBlackRook = bitboard(binary.BigEndian.Uint64(data[64:72]))
b.bbBlackBishop = bitboard(binary.BigEndian.Uint64(data[72:80]))
b.bbBlackKnight = bitboard(binary.BigEndian.Uint64(data[80:88]))
b.bbBlackPawn = bitboard(binary.BigEndian.Uint64(data[88:96]))
b.calcConvienceBBs(nil)
return nil
}
func (b *Board) update(m *Move) {
p1 := b.Piece(m.s1)
s1BB := bbForSquare(m.s1)
s2BB := bbForSquare(m.s2)
// move s1 piece to s2
for _, p := range allPieces {
bb := b.bbForPiece(p)
// remove what was at s2
b.setBBForPiece(p, bb & ^s2BB)
// move what was at s1 to s2
if bb.Occupied(m.s1) {
bb = b.bbForPiece(p)
b.setBBForPiece(p, (bb & ^s1BB)|s2BB)
}
}
// check promotion
if m.promo != NoPieceType {
newPiece := getPiece(m.promo, p1.Color())
// remove pawn
bbPawn := b.bbForPiece(p1)
b.setBBForPiece(p1, bbPawn & ^s2BB)
// add promo piece
bbPromo := b.bbForPiece(newPiece)
b.setBBForPiece(newPiece, bbPromo|s2BB)
}
// remove captured en passant piece
if m.HasTag(EnPassant) {
if p1.Color() == White {
b.bbBlackPawn = ^(bbForSquare(m.s2) << 8) & b.bbBlackPawn
} else {
b.bbWhitePawn = ^(bbForSquare(m.s2) >> 8) & b.bbWhitePawn
}
}
// move rook for castle
if p1.Color() == White && m.HasTag(KingSideCastle) {
b.bbWhiteRook = (b.bbWhiteRook & ^bbForSquare(H1) | bbForSquare(F1))
} else if p1.Color() == White && m.HasTag(QueenSideCastle) {
b.bbWhiteRook = (b.bbWhiteRook & ^bbForSquare(A1)) | bbForSquare(D1)
} else if p1.Color() == Black && m.HasTag(KingSideCastle) {
b.bbBlackRook = (b.bbBlackRook & ^bbForSquare(H8) | bbForSquare(F8))
} else if p1.Color() == Black && m.HasTag(QueenSideCastle) {
b.bbBlackRook = (b.bbBlackRook & ^bbForSquare(A8)) | bbForSquare(D8)
}
b.calcConvienceBBs(m)
}
func (b *Board) calcConvienceBBs(m *Move) {
whiteSqs := b.bbWhiteKing | b.bbWhiteQueen | b.bbWhiteRook | b.bbWhiteBishop | b.bbWhiteKnight | b.bbWhitePawn
blackSqs := b.bbBlackKing | b.bbBlackQueen | b.bbBlackRook | b.bbBlackBishop | b.bbBlackKnight | b.bbBlackPawn
emptySqs := ^(whiteSqs | blackSqs)
b.whiteSqs = whiteSqs
b.blackSqs = blackSqs
b.emptySqs = emptySqs
if m == nil {
b.whiteKingSq = NoSquare
b.blackKingSq = NoSquare
for sq := 0; sq < numOfSquaresInBoard; sq++ {
sqr := Square(sq)
if b.bbWhiteKing.Occupied(sqr) {
b.whiteKingSq = sqr
} else if b.bbBlackKing.Occupied(sqr) {
b.blackKingSq = sqr
}
}
} else if m.s1 == b.whiteKingSq {
b.whiteKingSq = m.s2
} else if m.s1 == b.blackKingSq {
b.blackKingSq = m.s2
}
}
func (b *Board) copy() *Board {
return &Board{
whiteSqs: b.whiteSqs,
blackSqs: b.blackSqs,
emptySqs: b.emptySqs,
whiteKingSq: b.whiteKingSq,
blackKingSq: b.blackKingSq,
bbWhiteKing: b.bbWhiteKing,
bbWhiteQueen: b.bbWhiteQueen,
bbWhiteRook: b.bbWhiteRook,
bbWhiteBishop: b.bbWhiteBishop,
bbWhiteKnight: b.bbWhiteKnight,
bbWhitePawn: b.bbWhitePawn,
bbBlackKing: b.bbBlackKing,
bbBlackQueen: b.bbBlackQueen,
bbBlackRook: b.bbBlackRook,
bbBlackBishop: b.bbBlackBishop,
bbBlackKnight: b.bbBlackKnight,
bbBlackPawn: b.bbBlackPawn,
}
}
func (b *Board) isOccupied(sq Square) bool {
return !b.emptySqs.Occupied(sq)
}
func (b *Board) hasSufficientMaterial() bool {
// queen, rook, or pawn exist
if (b.bbWhiteQueen | b.bbWhiteRook | b.bbWhitePawn |
b.bbBlackQueen | b.bbBlackRook | b.bbBlackPawn) > 0 {
return true
}
// if king is missing then it is a test
if b.bbWhiteKing == 0 || b.bbBlackKing == 0 {
return true
}
count := map[PieceType]int{}
pieceMap := b.SquareMap()
for _, p := range pieceMap {
count[p.Type()]++
}
// king versus king
if count[Bishop] == 0 && count[Knight] == 0 {
return false
}
// king and bishop versus king
if count[Bishop] == 1 && count[Knight] == 0 {
return false
}
// king and knight versus king
if count[Bishop] == 0 && count[Knight] == 1 {
return false
}
// king and bishop(s) versus king and bishop(s) with the bishops on the same colour.
if count[Knight] == 0 {
whiteCount := 0
blackCount := 0
for sq, p := range pieceMap {
if p.Type() == Bishop {
switch sq.color() {
case White:
whiteCount++
case Black:
blackCount++
}
}
}
if whiteCount == 0 || blackCount == 0 {
return false
}
}
return true
}
func (b *Board) bbForPiece(p Piece) bitboard {
switch p {
case WhiteKing:
return b.bbWhiteKing
case WhiteQueen:
return b.bbWhiteQueen
case WhiteRook:
return b.bbWhiteRook
case WhiteBishop:
return b.bbWhiteBishop
case WhiteKnight:
return b.bbWhiteKnight
case WhitePawn:
return b.bbWhitePawn
case BlackKing:
return b.bbBlackKing
case BlackQueen:
return b.bbBlackQueen
case BlackRook:
return b.bbBlackRook
case BlackBishop:
return b.bbBlackBishop
case BlackKnight:
return b.bbBlackKnight
case BlackPawn:
return b.bbBlackPawn
}
return bitboard(0)
}
func (b *Board) setBBForPiece(p Piece, bb bitboard) {
switch p {
case WhiteKing:
b.bbWhiteKing = bb
case WhiteQueen:
b.bbWhiteQueen = bb
case WhiteRook:
b.bbWhiteRook = bb
case WhiteBishop:
b.bbWhiteBishop = bb
case WhiteKnight:
b.bbWhiteKnight = bb
case WhitePawn:
b.bbWhitePawn = bb
case BlackKing:
b.bbBlackKing = bb
case BlackQueen:
b.bbBlackQueen = bb
case BlackRook:
b.bbBlackRook = bb
case BlackBishop:
b.bbBlackBishop = bb
case BlackKnight:
b.bbBlackKnight = bb
case BlackPawn:
b.bbBlackPawn = bb
default:
panic("invalid piece")
}
}