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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
|
package game
import (
"bufio"
"fmt"
"io"
"log"
"regexp"
)
type PlayerNotificationType int
const (
InvalidNotification PlayerNotificationType = iota
DeclaredActionNotification
ResolvedActionNotification
PriorityNotification
TargetSelectionPrompt
DeclareTriggeredActionsPrompt
DraftPickPrompt
JoinedPlayerNotification
ReadyPlayerNotification
)
func (n PlayerNotificationType) String() string {
switch n {
case InvalidNotification:
return "InvalidNotification"
case DeclaredActionNotification:
return "DeclaredActionNotification"
case ResolvedActionNotification:
return "ResolvedActionNotification"
case PriorityNotification:
return "PriorityNotification"
case TargetSelectionPrompt:
return "TargetSelectionPrompt"
case DeclareTriggeredActionsPrompt:
return "DeclareTriggeredActionsPrompt"
case DraftPickPrompt:
return "DraftPickPrompt"
case JoinedPlayerNotification:
return "JoinedPlayerNotification"
case ReadyPlayerNotification:
return "ReadyPlayerNotification"
default:
log.Panicf("Unhandled notification %d", n)
return ""
}
}
func (n PlayerNotification) IsPriorityNotification() bool {
return n.Notification == PriorityNotification
}
type PlayerNotification struct {
Notification PlayerNotificationType
Context any
Error error
}
func (n PlayerNotification) String() string {
if n.Error != nil {
return fmt.Sprintf("error %v: %v", n.Notification, n.Error)
}
return fmt.Sprintf("%v: %v", n.Notification, n.Context)
}
func (n PlayerNotification) Valid() bool {
return n.Notification != InvalidNotification
}
type TargetSelectionCtx struct {
Action Action
Prompt string
}
func newPriorityNotification() PlayerNotification {
return PlayerNotification{PriorityNotification, nil, nil}
}
func newDeclaredActionNotification(a Action, err error) PlayerNotification {
return PlayerNotification{DeclaredActionNotification, a, err}
}
func newResolvedActionNotification(a Action, err error) PlayerNotification {
return PlayerNotification{ResolvedActionNotification, a, err}
}
func newTargetSelectionPrompt(a Action, desc string) PlayerNotification {
return PlayerNotification{TargetSelectionPrompt, TargetSelectionCtx{a, desc}, nil}
}
func newUpkeepPrompt(p *Player) PlayerNotification {
a := newUpkeepAction(p)
return newTargetSelectionPrompt(a, "Select units to disband")
}
func newBuyPrompt(p *Player) PlayerNotification {
a := newBuyAction(p)
prompt := newTargetSelectionPrompt(a, "Select a card to buy")
return prompt
}
func newHandCardSelectionPrompt(p *Player, min, max int) PlayerNotification {
a := newHandCardSelection(p, min, max)
desc := fmt.Sprintf("Select between %d and %d hand cards", min, max)
return newTargetSelectionPrompt(a, desc)
}
func newDeclareTriggeredActionsPrompt(triggeredActions []*TriggeredAction) PlayerNotification {
return PlayerNotification{DeclareTriggeredActionsPrompt, triggeredActions, nil}
}
func newDraftPickPrompt(pack PileOfCards) PlayerNotification {
return PlayerNotification{DraftPickPrompt, pack, nil}
}
// Create a notification about a joined new player.
// The notification only contains the name since a full `game.Player` may not be
// reconstructable for clients without a game state (e.g. draft client).
func NewJoinedPlayerNotification(p *Player) PlayerNotification {
return PlayerNotification{JoinedPlayerNotification, p.Name, nil}
}
// Create a notification about a player's readiness.
// The notification only contains the name since a full `game.Player` may not be
// reconstructable for clients without a game state (e.g. draft client).
func NewReadyPlayerNotification(p *Player) PlayerNotification {
return PlayerNotification{ReadyPlayerNotification, p.Name, nil}
}
// Marshal marshals a PlayerNotification to plain text.
//
// The marshaled PlayerNotification has the form `!TYPE{CONTEXT}`.
func (n PlayerNotification) Marshal(s State) []byte {
out := []byte{'!'}
ctx := []byte{}
switch n.Notification {
case DraftPickPrompt:
out = append(out, []byte("pick")...)
ctx = []byte(n.Context.(PileOfCards).String())
case PriorityNotification:
out = append(out, []byte("priority")...)
case DeclaredActionNotification:
out = append(out, []byte("declared")...)
ctx = MarshalAction(n.Context.(Action))
case ResolvedActionNotification:
out = append(out, []byte("resolved")...)
if n.Error != nil {
ctx = []byte(n.Error.Error())
}
case JoinedPlayerNotification:
out = append(out, []byte("joined")...)
ctx = []byte(n.Context.(string))
case ReadyPlayerNotification:
out = append(out, []byte("ready")...)
ctx = []byte(n.Context.(string))
default:
log.Fatalf("Marshal(%s) not implement\n", n)
}
out = fmt.Appendf(out, "{%s}", ctx)
return out
}
var PlayerNotificationRegex = regexp.MustCompile(`!(.*)\{(.*)\}`)
type InvalidPlayerNotificationError struct {
ErrorString string
}
func (err InvalidPlayerNotificationError) Error() string {
return err.ErrorString
}
var (
ErrBadFormat = InvalidPlayerNotificationError{"bad format"}
ErrUnknownNotification = InvalidPlayerNotificationError{"unknown notification"}
ErrNoContextExpected = InvalidPlayerNotificationError{"no context expected"}
)
// UnmarshalPlayerNotification creates a UnmarshalPlayerNotification from plain text.
// For the PlayerNotification plain text format see MarshalPlayerNotification.
func UnmarshalPlayerNotification(s State, in []byte) (n PlayerNotification, err error) {
m := PlayerNotificationRegex.FindSubmatch(in)
if len(m) != 3 {
return n, ErrBadFormat
}
t := string(m[1])
ctx := m[2]
switch t {
case "pick":
pack := NewPileOfCards()
err = pack.FromString(string(ctx))
if err != nil {
return
}
n = newDraftPickPrompt(pack)
case "priority":
if len(ctx) > 0 {
err = ErrNoContextExpected
}
n = newPriorityNotification()
case "resolved":
var err error
if len(ctx) > 0 {
err = ErrNoContextExpected
}
n = newResolvedActionNotification(s.Stack().Actions[len(s.Stack().Actions)-1], err)
case "joined":
n = PlayerNotification{JoinedPlayerNotification, string(ctx), nil}
case "ready":
n = PlayerNotification{ReadyPlayerNotification, string(ctx), nil}
default:
return n, ErrUnknownNotification
}
return
}
type PlayerControl interface {
Player() *Player
// SendAction sends an Action and blocks until it is sent.
SendAction(Action) error
// RecvAction returns the next Action.
// It blocks until the Action is received or an error occurs.
RecvAction() (Action, error)
// SendNotification sends an PlayerNotification and blocks until it is sent.
SendNotification(PlayerNotification) error
// RecvNotification returns a new PlayerNotification.
// If no new notification is available an zero/invalid PlayerNotification is returned and err == nil.
// RecvNotification never blocks.
RecvNotification() (PlayerNotification, error)
Close()
}
// ChanPlayerControl implements a PlayerControl using two go channels.
// Objects are transferred directly.
// Therefore ChanPlayerControl is only suitable for communication in the same process.
type ChanPlayerControl struct {
player *Player
actions chan Action
notifications chan PlayerNotification
}
func (c *ChanPlayerControl) Player() *Player { return c.player }
func (c *ChanPlayerControl) SendAction(a Action) error {
c.actions <- a
return nil
}
func (c *ChanPlayerControl) RecvAction() (Action, error) {
return <-c.actions, nil
}
func (c *ChanPlayerControl) SendNotification(n PlayerNotification) error {
c.notifications <- n
return nil
}
func (c *ChanPlayerControl) RecvNotification() (PlayerNotification, error) {
var n PlayerNotification
select {
case n = <-c.notifications:
default:
}
return n, nil
}
func (c *ChanPlayerControl) Close() {
close(c.actions)
close(c.notifications)
}
func NewChanPlayerControl(p *Player) *ChanPlayerControl {
a := make(chan Action)
n := make(chan PlayerNotification)
return &ChanPlayerControl{p, a, n}
}
func prompt(ctrl PlayerControl, notification PlayerNotification) (Action, error) {
ctrl.SendNotification(notification)
return ctrl.RecvAction()
}
func promptBuy(ctrl PlayerControl) (Action, error) {
return prompt(ctrl, newBuyPrompt(ctrl.Player()))
}
func promptAction(ctrl PlayerControl) (Action, error) {
return prompt(ctrl, newPriorityNotification())
}
// RWPlayerControl implements a player control over any io.ReadWriteCloser.
// The transfer happens in a plain text wire format and is suitable for communication between memory space boundaries.
// Transmission control, such as timeouts or reconnection, is not supported.
type RWPlayerControl struct {
player *Player
rwc io.ReadWriteCloser
r *bufio.Reader
nch chan PlayerNotification
done chan struct{}
nerr error
}
func NewRWPlayerControl(p *Player, rwc io.ReadWriteCloser) *RWPlayerControl {
ctrl := &RWPlayerControl{
p,
rwc,
bufio.NewReader(rwc),
make(chan PlayerNotification),
make(chan struct{}),
nil,
}
go func() {
for {
in, err := ctrl.r.ReadBytes('\n')
if err != nil {
// FIXME
}
var n PlayerNotification
n, ctrl.nerr = UnmarshalPlayerNotification(ctrl.player.gameState, in)
if n.Valid() {
select {
case ctrl.nch <- n:
case _, ok := <-ctrl.done:
if !ok {
close(ctrl.nch)
return
}
}
}
}
}()
return ctrl
}
func (c *RWPlayerControl) Player() *Player { return c.player }
// SendAction encodes and sends an action.
// It is used by the player to respond to a received notification.
func (c *RWPlayerControl) SendAction(a Action) error {
out := MarshalAction(a)
_, err := c.rwc.Write(out)
return err
}
// RecvAction returns the next received and decoded action.
// It is called by the game logic to receive a players action.
func (c *RWPlayerControl) RecvAction() (Action, error) {
in, err := c.r.ReadBytes('\n')
a, err := UnmarshalAction(c.player.gameState, in)
return a, err
}
// SendNotification encodes and sends a PlayerNotification.
func (c *RWPlayerControl) SendNotification(n PlayerNotification) error {
out := n.Marshal(c.player.gameState)
_, err := c.rwc.Write(out)
return err
}
// RecvNotification returns a received and decoded PlayerNotification.
// It is called by the client to be notified about progress in the game.
func (c *RWPlayerControl) RecvNotification() (n PlayerNotification, err error) {
select {
case n = <-c.nch:
default:
}
return n, c.nerr
}
func (c *RWPlayerControl) Close() {
c.rwc.Close()
close(c.nch)
}
|