-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine.go
66 lines (59 loc) · 1.29 KB
/
engine.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
package main
import (
"bufio"
"fmt"
"io"
"os/exec"
"strings"
)
type Engine struct {
cmd *exec.Cmd
in io.WriteCloser
out io.ReadCloser
}
func NewEngine(str string) Engine {
return Engine{
cmd: exec.Command(str),
}
}
func (engine *Engine) Init() {
engine.out, _ = engine.cmd.StdoutPipe()
engine.in, _ = engine.cmd.StdinPipe()
engine.cmd.Start()
}
func (engine *Engine) WaitForReady() {
io.WriteString(engine.in, "isready\n")
scanner := bufio.NewScanner(engine.out)
for scanner.Scan() {
if strings.Contains(scanner.Text(), "readyok") {
return
}
}
}
func (engine *Engine) NewGame() {
engine.WaitForReady()
io.WriteString(engine.in, "ucinewgame\n")
}
func (engine *Engine) BestMove(fen string, moves string, wtime int, btime int) string {
engine.WaitForReady()
var str string
if fen == "startpos" {
str = "position startpos"
} else {
str = "position fen " + fen
}
if len(moves) > 0 {
str = str + " moves " + moves
}
io.WriteString(engine.in, str+"\n")
engine.WaitForReady()
str = fmt.Sprintf("go wtime %d btime %d", wtime, btime)
io.WriteString(engine.in, str+"\n")
scanner := bufio.NewScanner(engine.out)
for scanner.Scan() {
if strings.Contains(scanner.Text(), "bestmove") {
return strings.TrimSpace(strings.Split(scanner.Text(), " ")[1])
}
}
return ""
}