forked from notnil/chess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
san_decode.go
325 lines (309 loc) · 8.72 KB
/
san_decode.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
package chess
import (
"errors"
"fmt"
"math/bits"
"strings"
"unicode"
)
func pieceFromChar(c rune) Piece {
v, ok := fenPieceMap[string(c)]
if !ok {
return NoPiece
}
return v
}
func parseSAN(s string, pos *Position) (Move, error) {
if s == "--" {
return 0, nil
}
s = strings.TrimSpace(s)
var (
typ PieceType
fileHint int = -1
rankHint int = -1
toSq Square
move Move
err error
)
if len(s) < 2 {
return 0, errors.New("parseSAN: invalid move")
}
// Handle castling
if strings.HasPrefix(s, "O-O-O") || strings.HasPrefix(s, "0-0-0") {
move = move.addTag(QueenSideCastle)
if pos.turn == White {
move = move.setPiece(WhiteKing)
move = move.setS1(E1)
move = move.setS2(C1)
} else {
move = move.setPiece(BlackKing)
move = move.setS1(E8)
move = move.setS2(C8)
}
return parseSANTail(move, s[5:])
}
if strings.HasPrefix(s, "O-O") || strings.HasPrefix(s, "0-0") {
move = move.addTag(KingSideCastle)
if pos.turn == White {
move = move.setPiece(WhiteKing)
move = move.setS1(E1)
move = move.setS2(G1)
} else {
move = move.setPiece(BlackKing)
move = move.setS1(E8)
move = move.setS2(G8)
}
return parseSANTail(move, s[3:])
}
originalMove := s
// Find the index of the last number.
lastNum := -1
for i, c := range s {
if unicode.IsNumber(c) {
lastNum = i
}
}
if lastNum == -1 || lastNum < 1 {
// We didn't find any numbers, this isn't valid.
return 0, fmt.Errorf("parseSAN: couldn't find a square number in `%s`", s)
}
// Split the parts of the move
head := s[:lastNum-1]
// Every SAN move contains the full destination square
toSquareStr := s[lastNum-1 : lastNum+1]
toSq = strToSquareMap[strings.ToLower(toSquareStr)]
// These are the extra info parsed at the end
tail := s[lastNum+1:]
if strings.Contains(head, "x") {
// Double check
if toSq == pos.enPassantSquare {
move = move.addTag(EnPassant)
} else {
move = move.addTag(Capture)
}
head = strings.ReplaceAll(head, "x", "")
}
switch len(head) {
case 0:
typ = Pawn
case 1:
// Either a piece move/capture or a pawn capture.
// Capitalization is important here; consider the conflation of
// "bxc5" or "Bxc5"
if head[0] < 0x60 {
typ = fenPieceMap[head[0:1]].Type()
} else {
typ = Pawn
fileHint = int(head[0] - 0x61)
if fileHint > 7 {
// We're assuming a pawn, but thanks to the capitilization rule, this
// is just incorrect (eg, "nf3")
return 0, fmt.Errorf("parseSAN: invalid capitalization `%s` for move `%s`", head, originalMove)
}
}
case 2:
// A disambiguated move. Must contain a piece at the front.
typ = fenPieceMap[head[0:1]].Type()
if head[1] > 0x30 && head[1] < 0x3A {
// It's a number disambiguator.
rankHint = int(head[1]) - 0x31
} else {
// It's a rank disambiguator
if head[1] < 0x60 {
// It's uppercase for some reason -- but we can deal.
fileHint = int(head[1] - 0x41)
} else {
fileHint = int(head[1] - 0x61)
}
}
case 3:
// A fully disambiguated move. Contains all the info.
typ = fenPieceMap[head[0:1]].Type()
fromSq := strToSquareMap[strings.ToLower(head[1:])]
rankHint = int(fromSq.Rank())
fileHint = int(fromSq.File())
}
if typ == NoPieceType {
return 0, fmt.Errorf("parseSAN: Couldn't deduce a piece type for `%s`", originalMove)
}
thisPiece := GetPiece(typ, pos.Turn())
move = move.setPiece(thisPiece)
if p := pos.board.pieceAt(toSq); p != NoPiece {
if p.Color() != pos.turn.Other() {
if p.Type() == Rook && typ == King {
// This may be a castle by other means.
if p.Color() == White && pos.board.whiteKingSq == E1 && (toSq == A1 || toSq == H1) {
move = move.setS1(E1)
if toSq == A1 {
move = move.addTag(QueenSideCastle)
move = move.setS2(C1)
} else {
move = move.addTag(KingSideCastle)
move = move.setS2(G1)
}
return parseSANTail(move, tail)
} else if p.Color() == Black && pos.board.blackKingSq == E8 && (toSq == A8 || toSq == H8) {
move = move.setS1(E8)
if toSq == A8 {
move = move.addTag(QueenSideCastle)
move = move.setS2(C8)
} else {
move = move.addTag(KingSideCastle)
move = move.setS2(G8)
}
return parseSANTail(move, tail)
}
}
return 0, fmt.Errorf("parseSAN: `%s` apparently trying to capture own piece?", originalMove)
}
if !move.HasTag(Capture) {
return 0, fmt.Errorf("parseSAN: `%s` appears to not capture but is moving onto a piece", originalMove)
}
}
move = move.setS2(toSq)
move, err = findAndValidateFromSquare(thisPiece, move, fileHint, rankHint, pos)
if err != nil {
return 0, fmt.Errorf("parseSAN: for move `%s`, fAVS err: %s", originalMove, err)
}
return parseSANTail(move, tail)
}
func parseSANQuality(s string) string {
// TODO(barakmich): Perhaps add move comments about the quality of the move.
// But for now, drop it.
s = strings.ReplaceAll(s, "!", "")
s = strings.ReplaceAll(s, "?", "")
return s
}
func parseSANTail(move Move, s string) (Move, error) {
if s == "" {
return move, nil
}
s = parseSANQuality(s)
if s == "" {
return move, nil
}
if strings.Contains(s, "ep") {
move = move.addTag(EnPassant)
s = strings.ReplaceAll(s, "ep", "")
}
if strings.Contains(s, "e.p.") {
move = move.addTag(EnPassant)
s = strings.ReplaceAll(s, "e.p.", "")
}
if strings.Contains(s, "+") {
move = move.addTag(Check)
s = strings.ReplaceAll(s, "+", "")
}
if strings.Contains(s, "#") {
move = move.addTag(Check)
s = strings.ReplaceAll(s, "#", "")
// TODO(barakmich): Validate checkmate iff we see this symbol
}
if idx := strings.Index(s, "="); idx != -1 {
switch s[idx : idx+2] {
case "=Q", "=q":
move = move.setPromo(PromoQueen)
case "=R", "=r":
move = move.setPromo(PromoRook)
case "=B", "=b":
move = move.setPromo(PromoBishop)
case "=N", "=n":
move = move.setPromo(PromoKnight)
default:
return 0, fmt.Errorf("parseSANTail: detected promotion but can't parse `%s`", s)
}
s = s[:idx] + s[idx+2:]
}
if s != "" {
return 0, fmt.Errorf("parseSANTail: Remaining tail characters: `%s`", s)
}
return move, nil
}
func findAndValidateFromSquare(p Piece, move Move, fileHint, rankHint int, pos *Position) (Move, error) {
if p.Type() == Pawn {
// Pawns can't move backwards, we have to know more.
return findAndValidatePawnSquare(p, move, fileHint, pos)
}
currentPieces := pos.board.bbForPiece(p)
if fileHint != -1 {
currentPieces = currentPieces & bbFiles[fileHint]
}
if rankHint != -1 {
currentPieces = currentPieces & bbRanks[rankHint]
}
if bits.OnesCount64(uint64(currentPieces)) == 1 {
return validateFromBB(currentPieces, move)
}
occupied := pos.board.occupied()
thisSq := bbForSquare(move.S2())
possibilities := make([]bitboard, 0, 2)
for {
off := bits.TrailingZeros64(uint64(currentPieces))
if off == 64 {
break
}
bb := bbForSquare(Square(off))
currentPieces = currentPieces ^ bb
moves := bbForPossiblePieceMoves(occupied, p.Type(), Square(off))
if thisSq&moves != 0 {
possibilities = append(possibilities, bb)
}
}
if len(possibilities) == 1 {
return validateFromBB(possibilities[0], move)
}
// Okay, the reason we have no disambiguator, and have more than one possible move,
// is that moving one of these causes check to ourselves.
// Return the first that is possible (the other can't be)
for _, bb := range possibilities {
test := move.setS1(bbGetFirstSquare(bb))
board := pos.tempCopyBoard()
board.update(test)
if !isInCheck(board, p.Color()) {
return validateFromBB(bb, move)
}
}
return 0, errors.New("Can't find a potential piece to move")
}
func validateFromBB(fromSquareBB bitboard, move Move) (Move, error) {
if fromSquareBB == 0 {
return 0, fmt.Errorf("validateFromBB: couldn't find any potential pieces to move to %s", move)
}
if bits.OnesCount64(uint64(fromSquareBB)) != 1 {
return 0, fmt.Errorf("validateFromBB: More than one apparent potential from piece moving to %s", move)
}
return move.setS1(bbGetFirstSquare(fromSquareBB)), nil
}
func findAndValidatePawnSquare(p Piece, move Move, fileHint int, pos *Position) (Move, error) {
currentPawns := pos.board.bbForPiece(p)
var file File
toSq := move.S2()
if fileHint == -1 {
// This can't be a capture, according to SAN. So the file must be obvious.
file = toSq.File()
} else {
file = File(fileHint)
}
var pawnBB bitboard
if file > 7 {
return 0, errors.New("How?")
}
filePawns := currentPawns & bbFiles[file]
if pos.Turn() == White {
pawnBB = filePawns & bbRanks[toSq.Rank()-1]
if pawnBB == 0 && toSq.Rank() == Rank4 {
pawnBB = filePawns & bbRank2
}
} else {
pawnBB = filePawns & bbRanks[toSq.Rank()+1]
if pawnBB == 0 && toSq.Rank() == Rank5 {
pawnBB = filePawns & bbRank7
}
}
return validateFromBB(pawnBB, move)
}
func drawBb(bb bitboard) string {
fmt.Println(bb.Draw())
return bb.Draw()
}