-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgo-usi.go
116 lines (93 loc) · 1.91 KB
/
go-usi.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
package usi
import (
"bufio"
"context"
"errors"
"os"
"path/filepath"
"strings"
"github.com/kk-no/go-usi/usicmd"
)
type USI struct {
enginePath string
engineName string
status Status
process ReadWriteProcessor
result ResultManager
}
func New(enginePath string, options ...Option) (*USI, error) {
absPath, err := filepath.Abs(enginePath)
if err != nil {
return nil, err
}
i := strings.LastIndex(absPath, string(filepath.Separator))
usi := &USI{
enginePath: absPath[:i],
engineName: "." + absPath[i:],
status: Disconnected,
}
for _, o := range options {
o(usi)
}
return usi, nil
}
func (u *USI) SetStatus(to Status) {
u.status = to
}
func (u *USI) Connect(ctx context.Context) error {
u.SetStatus(WaitConnecting)
if err := os.Chdir(u.enginePath); err != nil {
return err
}
p, err := NewReadWriteProcessor(ctx, u.engineName)
if err != nil {
return err
}
u.process = p
u.result = NewResultManager()
u.process.Start(ctx)
u.SetStatus(Connected)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
in := scanner.Text()
if usicmd.IsCommand(in) {
if usicmd.IsQuit(in) {
return errors.New("quit inputted")
}
u.SendCommand(in)
}
}
return scanner.Err()
}
func (u *USI) Disconnect() error {
if err := u.process.Stop(); err != nil {
return err
}
u.process = nil
u.SetStatus(Disconnected)
return nil
}
func (u *USI) IsConnected() bool {
return u.process != nil
}
func (u *USI) SendCommand(command string) {
u.process.SendCommand(usicmd.Command(command))
}
func (u *USI) HandleMessage(message string) {
u.result.ReceiveMessage(message)
var token string
if index := strings.Index(message, " "); index == -1 {
token = message
} else {
token = message[0:index]
}
switch Response(token) {
case ReadyOK:
u.SetStatus(WaitCommand)
case BestMove:
u.result.HandleBestMove(message)
u.SetStatus(WaitCommand)
case Info:
u.result.HandleInfo(message)
}
}