-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathnotation.go
More file actions
518 lines (444 loc) · 12.3 KB
/
notation.go
File metadata and controls
518 lines (444 loc) · 12.3 KB
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
package chess
import (
"fmt"
"regexp"
"strings"
"sync"
)
// moveComponents represents the parsed components of an algebraic notation move.
type moveComponents struct {
piece string
originFile string
originRank string
capture string
file string
rank string
promotes string
castles string
}
// emptyComponents is an empty moveComponents struct
//
//nolint:gochecknoglobals // false positive.
var emptyComponents = moveComponents{}
// pgnRegex is a regular expression to parse PGN strings
//
//nolint:gochecknoglobals // false positive.
var pgnRegex = regexp.MustCompile(`^(?:([RNBQKP]?)([abcdefgh]?)(\d?)(x?)([abcdefgh])(\d)(=[QRBN])?|(O-O(?:-O)?))([+#!?]|e\.p\.)*$`)
const piecesPoolCapacity = 4
// Use string pools for common strings to reduce allocations.
var (
//nolint:gochecknoglobals // false positive
stringPool = sync.Pool{
New: func() interface{} {
return new(strings.Builder)
},
}
// Pre-allocate slices for options to avoid allocations in hot path
//nolint:gochecknoglobals // false positive
pieceOptionsPool = sync.Pool{
New: func() interface{} {
s := make([]string, 0, piecesPoolCapacity)
return &s // Return pointer to slice
},
}
)
// Constants for common strings to avoid allocations.
const (
kingStr = "K"
queenStr = "Q"
rookStr = "R"
bishopStr = "B"
knightStr = "N"
castleKS = "O-O"
castleQS = "O-O-O"
equalStr = "="
checkStr = "+"
mateStr = "#"
captureStr = "x"
)
// Pre-allocate piece type maps for faster lookups.
var pieceTypeToChar = map[PieceType]string{
King: kingStr,
Queen: queenStr,
Rook: rookStr,
Bishop: bishopStr,
Knight: knightStr,
}
// Encoder is the interface implemented by objects that can
// encode a move into a string given the position. It is not
// the encoders responsibility to validate the move.
type Encoder interface {
Encode(pos *Position, m *Move) string
}
// Decoder is the interface implemented by objects that can
// decode a string into a move given the position. It is not
// the decoders responsibility to validate the move. An error
// is returned if the string could not be decoded.
type Decoder interface {
Decode(pos *Position, s string) (*Move, error)
}
// Notation is the interface implemented by objects that can
// encode and decode moves.
type Notation interface {
Encoder
Decoder
}
// UCINotation is a more computer friendly alternative to algebraic
// notation. This notation uses the same format as the UCI (Universal Chess
// Interface). Examples: e2e4, e7e5, e1g1 (white short castling), e7e8q (for promotion).
type UCINotation struct{}
// String implements the fmt.Stringer interface and returns
// the notation's name.
func (UCINotation) String() string {
return "UCI Notation"
}
// Encode implements the Encoder interface.
func (UCINotation) Encode(_ *Position, m *Move) string {
const maxLen = 5
// Get a string builder from the pool
sb, _ := stringPool.Get().(*strings.Builder)
sb.Reset()
defer stringPool.Put(sb)
// Exact size needed: 4 chars for squares + up to 1 for promotion
sb.Grow(maxLen)
sb.Write(m.S1().Bytes())
sb.Write(m.S2().Bytes())
if m.Promo() != NoPieceType {
sb.Write(m.Promo().Bytes())
}
return sb.String()
}
// Decode implements the Decoder interface.
func (UCINotation) Decode(pos *Position, s string) (*Move, error) {
const promoLen = 5
l := len(s)
if l < 4 || l > 5 {
return nil, fmt.Errorf("chess: invalid UCI notation length %d in %q", l, s)
}
for idx := 0; idx < 2; idx += 2 {
if s[idx+0] < 'a' || s[idx+0] > 'h' {
return nil, fmt.Errorf("chess: invalid UCI notation sq:%v file:%v",
idx/2, s[0])
}
if s[idx+1] < '1' || s[idx+1] > '8' {
return nil, fmt.Errorf("chess: invalid UCI notation sq:%v rank:%v",
idx/2, s[0])
}
}
// Convert directly instead of using map lookups
s1 := Square((s[0] - 'a') + (s[1]-'1')*8)
s2 := Square((s[2] - 'a') + (s[3]-'1')*8)
if s1 < A1 || s1 > H8 || s2 < A1 || s2 > H8 {
return nil, fmt.Errorf("chess: invalid squares in UCI notation %q", s)
}
m := Move{s1: s1, s2: s2}
// Promotion (Use a precomputed lookup)
if l == promoLen {
promoMap := [256]PieceType{
'n': Knight, 'b': Bishop, 'r': Rook, 'q': Queen,
}
promo := promoMap[s[4]]
if promo == NoPieceType {
return nil, fmt.Errorf("chess: invalid promotion piece in UCI notation %q", s)
}
m.promo = promo
}
if pos == nil {
return &m, nil
}
addTags(&m, pos)
m.position = pos.Update(&m)
return &m, nil
}
// AlgebraicNotation (or Standard Algebraic Notation) is the
// official chess notation used by FIDE. Examples: e4, e5,
// O-O (short castling), e8=Q (promotion).
type AlgebraicNotation struct{}
// String implements the fmt.Stringer interface and returns
// the notation's name.
func (AlgebraicNotation) String() string {
return "Algebraic Notation"
}
// Encode implements the Encoder interface.
func (AlgebraicNotation) Encode(pos *Position, m *Move) string {
// Handle castling without builder
checkChar := getCheckChar(pos, m)
if m.HasTag(KingSideCastle) {
return castleKS + checkChar
}
if m.HasTag(QueenSideCastle) {
return castleQS + checkChar
}
// Get a string builder from the pool
sb, _ := stringPool.Get().(*strings.Builder)
sb.Reset()
defer stringPool.Put(sb)
p := pos.Board().Piece(m.S1())
if pChar := pieceTypeToChar[p.Type()]; pChar != "" {
sb.WriteString(pChar)
}
if s1Str := formS1(pos, m); s1Str != "" {
sb.WriteString(s1Str)
}
if m.HasTag(Capture) || m.HasTag(EnPassant) {
if p.Type() == Pawn && sb.Len() == 0 {
sb.WriteString(m.s1.File().String())
}
sb.WriteString(captureStr)
}
sb.WriteString(m.s2.String())
if m.promo != NoPieceType {
sb.WriteString(equalStr)
sb.WriteString(pieceTypeToChar[m.promo])
}
sb.WriteString(getCheckChar(pos, m))
return sb.String()
}
// algebraicNotationParts parses a move string into its components.
func algebraicNotationParts(s string) (moveComponents, error) {
submatches := pgnRegex.FindStringSubmatch(s)
if len(submatches) == 0 {
return emptyComponents, fmt.Errorf("chess: invalid algebraic notation %s", s)
}
// Return struct instead of multiple returns
return moveComponents{
piece: submatches[1],
originFile: submatches[2],
originRank: submatches[3],
capture: submatches[4],
file: submatches[5],
rank: submatches[6],
promotes: submatches[7],
castles: submatches[8],
}, nil
}
// cleanMove creates a standardized string from move components.
func (mc moveComponents) clean() string {
// Get a string builder from pool
sb, _ := stringPool.Get().(*strings.Builder)
sb.Reset()
defer stringPool.Put(sb)
sb.WriteString(mc.piece)
sb.WriteString(mc.originFile)
sb.WriteString(mc.originRank)
sb.WriteString(mc.capture)
sb.WriteString(mc.file)
sb.WriteString(mc.rank)
sb.WriteString(mc.promotes)
sb.WriteString(mc.castles)
return sb.String()
}
// generateMoveOptions creates possible alternative notations for a move.
func (mc moveComponents) generateOptions() []string {
// Get pre-allocated slice from pool
options := pieceOptionsPool.Get().(*[]string)
*options = (*options)[:0] // Clear but keep capacity
defer pieceOptionsPool.Put(options) // Now passing pointer
// Build move options using string builder for efficiency
sb, _ := stringPool.Get().(*strings.Builder)
defer stringPool.Put(sb)
if mc.piece != "" {
// Option 1: no origin coordinates
sb.Reset()
sb.WriteString(mc.piece)
sb.WriteString(mc.capture)
sb.WriteString(mc.file)
sb.WriteString(mc.rank)
sb.WriteString(mc.promotes)
sb.WriteString(mc.castles)
*options = append(*options, sb.String())
// Option 2: with rank, no file
sb.Reset()
sb.WriteString(mc.piece)
sb.WriteString(mc.originRank)
sb.WriteString(mc.capture)
sb.WriteString(mc.file)
sb.WriteString(mc.rank)
sb.WriteString(mc.promotes)
sb.WriteString(mc.castles)
*options = append(*options, sb.String())
// Option 3: with file, no rank
sb.Reset()
sb.WriteString(mc.piece)
sb.WriteString(mc.originFile)
sb.WriteString(mc.capture)
sb.WriteString(mc.file)
sb.WriteString(mc.rank)
sb.WriteString(mc.promotes)
sb.WriteString(mc.castles)
*options = append(*options, sb.String())
} else {
if mc.capture != "" {
// Pawn capture without rank
sb.Reset()
sb.WriteString(mc.originFile)
sb.WriteString(mc.capture)
sb.WriteString(mc.file)
sb.WriteString(mc.rank)
sb.WriteString(mc.promotes)
*options = append(*options, sb.String())
}
if mc.originFile != "" && mc.originRank != "" {
// Full coordinates version
sb.Reset()
sb.WriteString(mc.capture)
sb.WriteString(mc.file)
sb.WriteString(mc.rank)
sb.WriteString(mc.promotes)
*options = append(*options, sb.String())
}
}
return *options
}
// Decode implements the Decoder interface.
func (AlgebraicNotation) Decode(pos *Position, s string) (*Move, error) {
// Parse move components
components, err := algebraicNotationParts(s)
if err != nil {
return nil, err
}
// Get cleaned input move
cleanedInput := components.clean()
// Try matching against valid moves
for _, m := range pos.ValidMoves() {
// Encode current move
moveStr := AlgebraicNotation{}.Encode(pos, &m)
// Parse and clean encoded move
notationParts, algebraicNotationError := algebraicNotationParts(moveStr)
if algebraicNotationError != nil {
continue // Skip invalid moves
}
// Compare cleaned versions
if cleanedInput == notationParts.clean() {
return &m, nil
}
// Try alternative notations
for _, opt := range components.generateOptions() {
if opt == notationParts.clean() {
return &m, nil
}
}
}
return nil, fmt.Errorf("chess: move %s is not valid", s)
}
// LongAlgebraicNotation is a fully expanded version of
// algebraic notation in which the starting and ending
// squares are specified.
// Examples: e2e4, Rd3xd7, O-O (short castling), e7e8=Q (promotion).
type LongAlgebraicNotation struct{}
// String implements the fmt.Stringer interface and returns
// the notation's name.
func (LongAlgebraicNotation) String() string {
return "Long Algebraic Notation"
}
// Encode implements the Encoder interface.
func (LongAlgebraicNotation) Encode(pos *Position, m *Move) string {
checkChar := getCheckChar(pos, m)
if m.HasTag(KingSideCastle) {
return "O-O" + checkChar
} else if m.HasTag(QueenSideCastle) {
return "O-O-O" + checkChar
}
p := pos.Board().Piece(m.S1())
pChar := charFromPieceType(p.Type())
s1Str := m.s1.String()
capChar := ""
if m.HasTag(Capture) || m.HasTag(EnPassant) {
capChar = "x"
if p.Type() == Pawn && s1Str == "" {
capChar = m.s1.File().String() + "x"
}
}
promoText := charForPromo(m.promo)
return pChar + s1Str + capChar + m.s2.String() + promoText + checkChar
}
// Decode implements the Decoder interface.
func (LongAlgebraicNotation) Decode(pos *Position, s string) (*Move, error) {
return AlgebraicNotation{}.Decode(pos, s)
}
func getCheckChar(pos *Position, move *Move) string {
if !move.HasTag(Check) {
return ""
}
nextPos := pos.Update(move)
if nextPos.Status() == Checkmate {
return "#"
}
return "+"
}
// getCheckBytes returns the check or mate bytes for a move
//
//nolint:unused // I don't care about this
func getCheckBytes(pos *Position, move *Move) []byte {
if !move.HasTag(Check) {
return []byte{}
}
if pos.Update(move).Status() == Checkmate {
return []byte(mateStr)
}
return []byte(checkStr)
}
func formS1(pos *Position, m *Move) string {
p := pos.board.Piece(m.s1)
if p.Type() == Pawn {
return ""
}
var req, fileReq, rankReq bool
// Use a string builder from the pool
sb, _ := stringPool.Get().(*strings.Builder)
sb.Reset()
defer stringPool.Put(sb)
for _, mv := range pos.ValidMoves() {
if mv.s1 != m.s1 && mv.s2 == m.s2 && p == pos.board.Piece(mv.s1) {
req = true
if mv.s1.File() == m.s1.File() {
rankReq = true
}
if mv.s1.Rank() == m.s1.Rank() {
fileReq = true
}
}
}
if fileReq || !rankReq && req {
sb.WriteByte(m.s1.File().Byte())
}
if rankReq {
sb.WriteByte(m.s1.Rank().Byte())
}
return sb.String()
}
func charForPromo(p PieceType) string {
c := charFromPieceType(p)
if c != "" {
c = "=" + c
}
return c
}
func charFromPieceType(p PieceType) string {
switch p {
case King:
return "K"
case Queen:
return "Q"
case Rook:
return "R"
case Bishop:
return "B"
case Knight:
return "N"
}
return ""
}
func pieceTypeFromChar(c string) PieceType {
switch c {
case "q":
return Queen
case "r":
return Rook
case "b":
return Bishop
case "n":
return Knight
}
return NoPieceType
}