/
book.go
241 lines (194 loc) · 5.34 KB
/
book.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
package main
import (
"bufio"
"fmt"
"io"
"log"
"math/rand"
"os"
"strconv"
"strings"
)
func (game *gameState) bookLookup() string {
position := game.position()
game.println(fmt.Sprintf("bookLookup: position: [%s]", position))
if moves, found := book[position]; found {
return game.bookPick(position, moves)
}
return "" // not found
}
func (game *gameState) position() string {
history := game.history
if history[0].lastMove.isNull() {
history = history[1:]
}
var moves []string
for _, m := range history {
moves = append(moves, m.lastMove.String())
}
position := strings.Join(moves, " ")
return position
}
func (game *gameState) bookPick(position string, moves []bookMove) string {
if len(moves) < 1 {
game.println(fmt.Sprintf("bookLookup: position missing moves: [%s]", position))
return "" // not found
}
if len(moves) == 1 {
return moves[0].move // single move
}
// multiple moves
var sum int
for _, m := range moves {
w := m.getWeight(game, position)
sum += w
}
r := int(rand.Int31n(int32(sum))) // 0..sum-1
// 2 3 4
// 2 5 9
// sum = 9
// 0..8
// 0..1 -> 2
// 2..4 -> 3
// 5..8 -> 4
var rs int // running sum
for i, m := range moves {
w := m.getWeight(game, position)
rs += w
if rs > r {
game.println(fmt.Sprintf("bookPick: position=[%s] rand=%d runSum=%d index=%d move=%s", position, r, rs, i, m.move))
return m.move // found
}
}
game.println(fmt.Sprintf("bookPick: position=[%s] not reached - ugh", position))
return moves[0].move
}
type stringReader interface {
ReadString(delim byte) (string, error) // Example: bufio.Reader
}
func loadBookFromFile(filename string) {
fmt.Printf("loadBookFromFile: %s\n", filename)
input, errOpen := os.Open(filename)
if errOpen != nil {
fmt.Printf("loadBookFromFile: %s: %v\n", filename, errOpen)
return
}
defer input.Close()
loadBook(bufio.NewReader(input))
}
var book = map[string][]bookMove{}
type bookMove struct {
move string
weight int
}
func (m bookMove) getWeight(g *gameState, position string) int {
w := m.weight
if w < 1 {
g.println(fmt.Sprintf("bookLookup: bad weight=%d for move=%s position: [%s]", w, m.move, position))
w = 1
}
return w
}
func loadBook(reader stringReader) {
book = map[string][]bookMove{}
var lineCount int
LOOP:
for {
lineCount++
line, errRead := reader.ReadString('\n')
switch errRead {
case io.EOF:
// last line
loadLine(lineCount, line)
break LOOP
case nil:
if loadLine(lineCount, line) {
break LOOP
}
default:
fatal := loadLine(lineCount, line)
log.Printf("loadBook: read error at line=%d: %v", lineCount, errRead)
if fatal {
break LOOP
}
}
}
log.Printf("loadBook: lines=%d bookSize=%d", lineCount, len(book))
}
const errFatal = true
const errNonFatal = false
func loadLine(count int, line string) bool {
comment := strings.SplitN(line, "#", 2)
uncomment := strings.TrimSpace(comment[0])
if uncomment == "" {
return errNonFatal
}
entry := strings.SplitN(uncomment, ":", 2)
if len(entry) < 1 {
log.Printf("loadLine: missing position at line=%d: %s", count, line)
return errNonFatal
}
positionMoves := strings.Fields(entry[0])
position := strings.Join(positionMoves, " ")
tmpG := newGame()
tmp := &tmpG
tmp.loadFromString(builtinBoard)
var errTmp error
tmp, errTmp = tmp.validatePosition(position)
if errTmp != nil {
log.Printf("loadLine: line=%d: invalid position=[%s]: %v", count, position, errTmp)
return errFatal
}
if len(entry) == 1 {
return loadGame(count, positionMoves)
}
moves := strings.Split(strings.TrimSpace(entry[1]), ",")
for _, moveWeight := range moves {
w := 1 // default weight
mw := strings.SplitN(strings.TrimSpace(moveWeight), " ", 2)
moveStr := strings.TrimSpace(mw[0])
tmp, errTmp = tmp.validatePosition(moveStr)
if errTmp != nil {
log.Printf("loadLine: line=%d: invalid move position=[%s]: move=%s %v", count, position, moveStr, errTmp)
return errFatal
}
tmp.undo()
if len(mw) > 1 {
value, errConv := strconv.Atoi(strings.TrimSpace(mw[1]))
if errConv != nil {
log.Printf("loadLine: bad move weight at line=%d: %s: %v", count, line, errConv)
} else {
w = value
}
}
//log.Printf("loadLine: line=%d: position=[%s] move=%s weight=%d", count, position, moveStr, w)
//book[position] = append(book[position], bookMove{move: moveStr, weight: w})
loadPosition(position, bookMove{move: moveStr, weight: w}, count)
}
return errNonFatal
}
func loadPosition(position string, m bookMove, count int) {
log.Printf("loadPosition: line=%d: position=[%s] move=%s weight=%d FIXME PREVENT DUP MOVE", count, position, m.move, m.weight)
book[position] = append(book[position], m)
}
func loadGame(count int, positionMoves []string) bool {
//full := strings.Join(positionMoves, " ")
var moves []string
for _, m := range positionMoves {
position := strings.Join(moves, " ")
//log.Printf("loadGame: line=%d: position=[%s] p=[%s] move=%s", count, full, position, m)
//book[position] = append(book[position], bookMove{move: m, weight: 1})
loadPosition(position, bookMove{move: m, weight: 1}, count)
moves = append(moves, m)
}
return errNonFatal
}
func (game *gameState) validatePosition(position string) (*gameState, error) {
moves := strings.Fields(position)
for _, t := range moves {
if errPlay := game.play(t); errPlay != nil {
return game, errPlay // error
}
}
return game, nil // ok
}