/
shell.go
310 lines (272 loc) · 6.77 KB
/
shell.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package bot
import (
"errors"
"fmt"
"io"
"os"
"strconv"
"strings"
"syscall"
"github.com/chzyer/readline"
"github.com/nats-io/nats.go"
"github.com/rs/zerolog/log"
airunner "github.com/adject1/macondo/ai/runner"
"github.com/adject1/macondo/config"
pb "github.com/adject1/macondo/gen/api/proto/macondo"
"github.com/adject1/macondo/move"
"github.com/adject1/macondo/runner"
)
const (
SelfPlayer = 0
BotPlayer = 1
)
var (
errNoData = errors.New("no data in this line")
errWrongOptionSyntax = errors.New("wrong format; all options need arguments")
)
// Options to configure the interactve shell
type ShellOptions struct {
runner.GameOptions
lowercaseMoves bool
}
func NewShellOptions() *ShellOptions {
return &ShellOptions{
GameOptions: runner.GameOptions{
Lexicon: nil,
ChallengeRule: pb.ChallengeRule_DOUBLE,
},
lowercaseMoves: false,
}
}
func (opts *ShellOptions) Show(key string) (bool, string) {
switch key {
case "lexicon":
return true, opts.Lexicon.ToDisplayString()
case "lower":
return true, fmt.Sprintf("%v", opts.lowercaseMoves)
case "challenge":
rule := runner.ShowChallengeRule(opts.ChallengeRule)
return true, fmt.Sprintf("%v", rule)
default:
return false, "No such option: " + key
}
}
func (opts *ShellOptions) ToDisplayText() string {
keys := []string{"lexicon", "challenge", "lower"}
out := strings.Builder{}
out.WriteString("Settings:\n")
for _, key := range keys {
_, val := opts.Show(key)
out.WriteString(" " + key + ": ")
out.WriteString(val + "\n")
}
return out.String()
}
type Response struct {
message string
send bool
}
func Msg(message string) *Response {
return &Response{message: message, send: false}
}
// Keep Send in case we need bot debug messages, but for regular bot-to-play
// the shell now automatically sends a message.
func Send(message string) *Response {
return &Response{message: message, send: true}
}
type ShellController struct {
l *readline.Instance
config *config.Config
execPath string
options *ShellOptions
game *airunner.AIGameRunner
client Client
}
func filterInput(r rune) (rune, bool) {
switch r {
// block CtrlZ feature
case readline.CharCtrlZ:
return r, false
}
return r, true
}
func writeln(msg string, w io.Writer) {
io.WriteString(w, msg)
io.WriteString(w, "\n")
}
func (sc *ShellController) showMessage(msg string) {
writeln(msg, sc.l.Stderr())
}
func (sc *ShellController) showError(err error) {
sc.showMessage("Error: " + err.Error())
}
func NewShellController(cfg *config.Config, execPath string) *ShellController {
l, err := readline.NewEx(&readline.Config{
Prompt: "\033[31mmacondo>\033[0m ",
HistoryFile: "/tmp/readline.tmp",
EOFPrompt: "exit",
InterruptPrompt: "^C",
HistorySearchFold: true,
FuncFilterInputRune: filterInput,
})
if err != nil {
panic(err)
}
execPath = config.FindBasePath(execPath)
opts := NewShellOptions()
opts.SetDefaults(cfg)
return &ShellController{l: l, config: cfg, execPath: execPath, options: opts}
}
func (sc *ShellController) IsPlaying() bool {
return sc.game != nil && sc.game.IsPlaying()
}
func (sc *ShellController) IsBotOnTurn() bool {
return sc.game != nil && sc.game.PlayerOnTurn() == BotPlayer
}
func (sc *ShellController) getMove() error {
sc.showMessage("Requesting move from bot")
m, err := sc.client.RequestMove(&sc.game.GameRunner, sc.config)
if err != nil {
sc.showMessage("Bot returned error: " + err.Error())
return err
} else {
sc.showMessage("Bot returned move: " + m.ShortDescription())
}
err = sc.game.PlayMove(m, true, 0)
if err != nil {
return err
}
sc.showMessage(sc.game.ToDisplayText())
return nil
}
func (sc *ShellController) newGame() (*Response, error) {
players := []*pb.PlayerInfo{
{Nickname: "self", RealName: "Arthur Dent"},
{Nickname: "opponent", RealName: "Macondo Bot"},
}
opts := sc.options.GameOptions
g, err := airunner.NewAIGameRunner(sc.config, &opts, players, pb.BotRequest_HASTY_BOT)
if err != nil {
return nil, err
}
sc.game = g
if g.PlayerOnTurn() == SelfPlayer {
return Msg(sc.game.ToDisplayText()), nil
} else {
return Msg("Opponent goes first"), nil
}
}
func (sc *ShellController) show() (*Response, error) {
return Msg(sc.game.ToDisplayText()), nil
}
func (sc *ShellController) play(args []string) (*Response, error) {
if len(args) != 2 {
return nil, errors.New("play <coords> <word>")
}
coords, word := args[0], args[1]
m, err := sc.game.NewPlacementMove(SelfPlayer, coords, word)
if err != nil {
return nil, err
}
return sc.commit(m)
}
func (sc *ShellController) exchange(args []string) (*Response, error) {
tiles := args[0]
m, err := sc.game.NewExchangeMove(SelfPlayer, tiles)
if err != nil {
return nil, err
}
return sc.commit(m)
}
func (sc *ShellController) pass() (*Response, error) {
m, err := sc.game.NewPassMove(SelfPlayer)
if err != nil {
return nil, err
}
return sc.commit(m)
}
func (sc *ShellController) commit(m *move.Move) (*Response, error) {
sc.showMessage("Committing move: " + m.ShortDescription())
err := sc.game.PlayMove(m, true, 0)
if err != nil {
return nil, err
}
msg := sc.game.ToDisplayText()
return Msg(msg), nil
}
func (sc *ShellController) aiplay() (*Response, error) {
if !sc.IsPlaying() {
return nil, errors.New("game is over")
}
moves := sc.game.GenerateMoves(1)
m := moves[0]
return sc.commit(m)
}
func (sc *ShellController) handle(line string) (*Response, error) {
fields := strings.Fields(line)
cmd := fields[0]
args := fields[1:]
switch cmd {
case "new", "n":
return sc.newGame()
case "show", "s", "b":
return sc.show()
case "play", "pl", "p":
return sc.play(args)
case "exchange", "exch", "ex", "x":
return sc.exchange(args)
case "pass", "pa":
return sc.pass()
case "aiplay", "ai", "a":
return sc.aiplay()
default:
msg := fmt.Sprintf("command %v not found", strconv.Quote(cmd))
log.Info().Msg(msg)
return nil, errors.New(msg)
}
}
func (sc *ShellController) Loop(channel string, sig chan os.Signal) {
defer sc.l.Close()
// Initialize the NATS client
nc, err := nats.Connect(nats.DefaultURL)
if err != nil {
log.Fatal()
}
defer nc.Close()
sc.client = Client{nc: nc, channel: channel}
// Run the readline loop
for {
if sc.IsBotOnTurn() {
err = sc.getMove()
if err != nil {
sc.showError(err)
}
continue
}
line, err := sc.l.Readline()
if err == readline.ErrInterrupt {
if len(line) == 0 {
sig <- syscall.SIGINT
break
} else {
continue
}
} else if err == io.EOF {
sig <- syscall.SIGINT
break
}
line = strings.TrimSpace(line)
if line == "exit" {
sig <- syscall.SIGINT
break
} else {
resp, err := sc.handle(line)
if err != nil {
sc.showError(err)
} else if resp != nil {
sc.showMessage(resp.message)
}
}
}
log.Debug().Msgf("Exiting readline loop...")
}