-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstockfish.go
201 lines (177 loc) · 4.01 KB
/
stockfish.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
package stockfish
// doesnt do much on its own
import (
"bufio"
"fmt"
"io"
"os/exec"
"regexp"
"strconv"
"github.com/notnil/chess"
)
type matchRequest struct {
match regexp.Regexp
channel chan string
perma bool
}
type StockFish struct {
process exec.Cmd
scan bufio.Scanner
write bufio.Writer
hasPutIsReady bool
hasGotIsReady bool
matchRequests []*matchRequest
lastScoreWasMate bool
lastScore int
hasLastScore bool
whitesMove bool
}
const scoreRegex = "info depth \\d+ seldepth \\d+ multipv \\d+ score (?:(cp -?\\d+)|(mate -?\\d+)).*"
func (s *StockFish) Init() {
s.process = *exec.Command("./stockfish")
var err error
var stdout io.ReadCloser
var stdin io.WriteCloser
if stdout, err = s.process.StdoutPipe(); err != nil {
panic(err)
}
s.scan = *bufio.NewScanner(stdout)
if stdin, err = s.process.StdinPipe(); err != nil {
panic(err)
}
s.write = *bufio.NewWriter(stdin)
if err = s.process.Start(); err != nil {
panic(err)
}
go s.Loop()
ir := s.WaitForRaw(*regexp.MustCompile("readyok"), true)
infoscore := s.WaitForRaw(*regexp.MustCompile(scoreRegex), true)
go s.IBChannelWatch(ir, infoscore)
s.WriteRaw("uci")
<- s.WaitForRaw(*regexp.MustCompile("uciok"), false)
s.NewGame()
}
func trimLeftChars(s string, n int) string {
m := 0
for i := range s {
if m >= n {
return s[i:]
}
m++
}
return s[:0]
}
func (s *StockFish) IBChannelWatch(isready, score chan string) {
for {
select {
case <- isready:
s.hasGotIsReady = true
case match := <- score:
sm := regexp.MustCompile(scoreRegex).FindStringSubmatch(match)
if len(sm[1]) > 0 {
cpEval := trimLeftChars(sm[1], 3)
s.lastScoreWasMate = false
a, err := strconv.Atoi(cpEval)
if err == nil {
s.lastScore = a
s.hasLastScore = true
} else {
println(err)
}
}
if len(sm[2]) > 0 {
mateIn := trimLeftChars(sm[2], 5)
s.lastScoreWasMate = true
a, err := strconv.Atoi(mateIn)
if err == nil {
s.lastScore = a
s.hasLastScore = true
} else {
println(err)
}
}
}
}
}
func (s *StockFish) NewGame() {
s.WriteRaw("ucinewgame")
s.WaitReady()
s.whitesMove = true
}
func (s *StockFish) Load(game chess.Game) {
s.WriteRaw("position fen " + game.FEN())
s.whitesMove = game.Position().Turn() == chess.White
}
func (s *StockFish) Eval(depth int) (int, int, error) { // returns cp eval, mate in x, error
s.SetOption("Ponder", "value false")
s.SetOption("UCI_AnalyseMode", "value true")
s.WriteRaw("go depth " + fmt.Sprint(depth))
s.hasLastScore = false
<- s.WaitForRaw(*regexp.MustCompile("bestmove.*"), false)
if (!s.hasLastScore) {
return 0, 0, fmt.Errorf("Eval failed")
}
if !s.whitesMove {
s.lastScore = s.lastScore * -1
}
if s.lastScoreWasMate {
return 0, s.lastScore, nil
} else {
return s.lastScore, 0, nil
}
}
func (s *StockFish) SetOption(option string, after string) {
s.WriteRaw("setoption name " + option + " " + after)
}
func (s *StockFish) Loop() {
for {
s.scan.Scan()
txt := s.scan.Text()
i := 0
new := s.matchRequests[:0]
eachMR:
for _, mr := range s.matchRequests {
if mr.match.MatchString(txt) {
mr.channel <- txt
if !mr.perma {
close(mr.channel)
continue eachMR
}
}
new = append(new, mr)
i++
}
//println(txt)
s.matchRequests = new
}
}
func (s *StockFish) WriteRaw(cmd string) {
s.write.Write([]byte(cmd + "\n"))
s.write.Flush()
}
func (s *StockFish) WaitForRaw(matches regexp.Regexp, perma bool) chan string {
onFound := make(chan string)
mr := matchRequest {channel: onFound, match: matches, perma: perma}
s.matchRequests = append(s.matchRequests, &mr)
return onFound
}
func (s *StockFish) Close() {
s.process.Process.Kill()
}
func (s *StockFish) PutIsReady() {
s.write.Write([]byte("isready\n"))
s.write.Flush()
s.hasPutIsReady = true
}
func (s *StockFish) GetIsReady() bool {
if (s.hasGotIsReady) {
s.hasGotIsReady = false
s.hasPutIsReady = false
return true
}
return false
}
func (s *StockFish) WaitReady() {
s.PutIsReady()
for !s.GetIsReady() {}
}