forked from notnil/chess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpgn.go
234 lines (212 loc) · 4.97 KB
/
pgn.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
package chess
import (
"bufio"
"fmt"
"io"
"log"
"regexp"
"strings"
)
// GamesFromPGN returns all PGN decoding games from the
// reader. It is designed to be used decoding multiple PGNs
// in the same file. An error is returned if there is an
// issue parsing the PGNs.
func GamesFromPgnNoError(r io.Reader) ([]*Game, error) {
games := []*Game{}
current := ""
count := 0
totalCount := 0
br := bufio.NewReader(r)
for {
line, err := br.ReadString('\n')
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
if strings.TrimSpace(line) == "" {
count++
} else {
current += line
}
if count == 2 {
game, err := decodePGN(current)
if err != nil {
// Ignore error games.
continue
//return nil, err
}
games = append(games, game)
count = 0
current = ""
totalCount++
log.Println("Processed game", totalCount)
}
}
return games, nil
}
// GamesFromPGN returns all PGN decoding games from the
// reader. It is designed to be used decoding multiple PGNs
// in the same file. An error is returned if there is an
// issue parsing the PGNs.
func GamesFromPGN(r io.Reader) ([]*Game, error) {
games := []*Game{}
current := ""
count := 0
totalCount := 0
br := bufio.NewReader(r)
for {
line, err := br.ReadString('\n')
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
if strings.TrimSpace(line) == "" {
count++
} else {
current += line
}
if count == 2 {
game, err := decodePGN(current)
if err != nil {
return nil, err
}
games = append(games, game)
count = 0
current = ""
totalCount++
log.Println("Processed game", totalCount)
}
}
return games, nil
}
func decodePGN(pgn string) (*Game, error) {
tagPairs := getTagPairs(pgn)
moveStrs, outcome := moveList(pgn)
g := NewGame(TagPairs(tagPairs))
g.ignoreAutomaticDraws = true
var notation Notation = AlgebraicNotation{}
if len(moveStrs) > 0 {
_, err := LongAlgebraicNotation{}.Decode(g.Position(), moveStrs[0])
if err == nil {
notation = LongAlgebraicNotation{}
}
}
var prevMove *Move
isComment := false
commentStrs := []string{}
for _, alg := range moveStrs {
if strings.Contains(alg, "{") {
isComment = true
commentStrs = append(commentStrs, alg)
continue
}
if isComment {
if !strings.Contains(alg, "}") {
commentStrs = append(commentStrs, alg)
continue
}
// end of the comment
commentStrs = append(commentStrs, alg)
comment := strings.Join(commentStrs, " ")
isComment = false
if prevMove == nil {
return nil, fmt.Errorf("chess: pgn decode error %s malformed comment")
}
prevMove.Comment = comment
commentStrs = []string{}
continue
}
m, err := notation.Decode(g.Position(), alg)
if err != nil {
return nil, fmt.Errorf("chess: pgn decode error %s on move %d", err.Error(), g.Position().moveCount)
}
if err := g.Move(m); err != nil {
return nil, fmt.Errorf("chess: pgn invalid move error %s on move %d", err.Error(), g.Position().moveCount)
}
prevMove = m
}
g.outcome = outcome
return g, nil
}
func encodePGN(g *Game) string {
s := ""
for _, tag := range g.tagPairs {
s += fmt.Sprintf("[%s \"%s\"]\n", tag.Key, tag.Value)
}
s += "\n"
for i, move := range g.moves {
pos := g.positions[i]
txt := g.notation.Encode(pos, move)
if i%2 == 0 {
s += fmt.Sprintf("%d.%s", (i/2)+1, txt)
} else {
s += fmt.Sprintf(" %s ", txt)
}
}
s += " " + string(g.outcome)
return s
}
var (
tagPairRegex = regexp.MustCompile(`\[(.*)\s\"(.*)\"\]`)
)
func getTagPairs(pgn string) []*TagPair {
tagPairs := []*TagPair{}
matches := tagPairRegex.FindAllString(pgn, -1)
for _, m := range matches {
results := tagPairRegex.FindStringSubmatch(m)
if len(results) == 3 {
pair := &TagPair{
Key: results[1],
Value: results[2],
}
tagPairs = append(tagPairs, pair)
}
}
return tagPairs
}
var (
moveNumRegex = regexp.MustCompile(`(?:\d+\.+)?(.*)`)
)
func moveList(pgn string) ([]string, Outcome) {
// keep comments
//text := removeSection("{", "}", pgn)
// remove variations
text := removeSection(`\(`, `\)`, pgn)
// remove tag pairs
text = removeTagPairs(text)
// remove line breaks
text = strings.Replace(text, "\n", " ", -1)
list := strings.Split(text, " ")
filtered := []string{}
var outcome Outcome
for _, move := range list {
move = strings.TrimSpace(move)
switch move {
case string(NoOutcome), string(WhiteWon), string(BlackWon), string(Draw):
outcome = Outcome(move)
case "":
default:
results := moveNumRegex.FindStringSubmatch(move)
if len(results) == 2 && results[1] != "" {
filtered = append(filtered, results[1])
}
}
}
return filtered, outcome
}
func removeTagPairs(s string) string {
r := regexp.MustCompile("(?m)^\\[.*?\\]$")
return r.ReplaceAllString(s, "")
}
func removeSection(leftChar, rightChar, s string) string {
r := regexp.MustCompile(leftChar + ".*?" + rightChar)
for {
i := r.FindStringIndex(s)
if i == nil {
return s
}
s = s[0:i[0]] + s[i[1]:len(s)]
}
}