-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmatch.go
203 lines (179 loc) · 4.38 KB
/
match.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
package main
import (
"log"
"net"
"sync"
"time"
"github.com/gophergala2016/Gobots/botapi"
"github.com/gophergala2016/Gobots/engine"
gocontext "golang.org/x/net/context"
"zombiezen.com/go/capnproto2"
"zombiezen.com/go/capnproto2/rpc"
)
type aiEndpoint struct {
ds datastore
// fields below are protected by mu
mu sync.Mutex
online map[aiID]botapi.Ai
}
func startAIEndpoint(addr string, ds datastore) (*aiEndpoint, error) {
l, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
e := &aiEndpoint{
ds: ds,
online: make(map[aiID]botapi.Ai),
}
go e.listen(l)
return e, nil
}
// listen runs in its own goroutine, listening for connections.
func (e *aiEndpoint) listen(l net.Listener) {
for {
c, err := l.Accept()
if err != nil {
log.Println("ai endpoint: accept:", err)
return
}
go e.handleConn(c)
}
}
// handleConn runs in its own goroutine, started by listen.
func (e *aiEndpoint) handleConn(c net.Conn) {
aic := &aiConnector{e: e}
rc := rpc.NewConn(rpc.StreamTransport(c), rpc.MainInterface(botapi.AiConnector_ServerToClient(aic).Client))
rc.Wait()
aic.drop()
}
// listOnlineAIs lists the active AIs connected to the server right now. The AIs can be passed over to startMatch.
func (e *aiEndpoint) listOnlineAIs() []onlineAI {
e.mu.Lock()
defer e.mu.Unlock()
online := make([]onlineAI, 0, len(e.online))
for id, client := range e.online {
info, err := e.ds.lookupAI(id)
if err != nil {
log.Printf("Failed to lookup AI %s: %v", id, err)
continue
}
online = append(online, onlineAI{
Info: *info,
client: client,
})
}
return online
}
// connect adds an online AI, given the secret auth token.
func (e *aiEndpoint) connect(token string, ai botapi.Ai) (aiID, error) {
info, err := e.ds.lookupAIToken(token)
if err != nil {
return "", err
}
e.mu.Lock()
defer e.mu.Unlock()
e.online[info.ID] = ai
return info.ID, nil
}
// removeAIs drops AIs from online, usually via disconnection.
func (e *aiEndpoint) removeAIs(ids []aiID) {
e.mu.Lock()
defer e.mu.Unlock()
for _, i := range ids {
delete(e.online, i)
}
}
type aiConnector struct {
e *aiEndpoint
ais []aiID
}
func (aic *aiConnector) Connect(call botapi.AiConnector_connect) error {
creds, _ := call.Params.Credentials()
tok, _ := creds.SecretToken()
id, err := aic.e.connect(tok, call.Params.Ai())
if err != nil {
return err
}
aic.ais = append(aic.ais, id)
return nil
}
func (aic *aiConnector) drop() {
aic.e.removeAIs(aic.ais)
}
func runMatch(ctx gocontext.Context, ds datastore, aiA, aiB *onlineAI) error {
// Create new board and store it.
b := engine.NewBoard(20, 20)
_, seg, _ := capnp.NewMessage(capnp.SingleSegment(nil))
wb, _ := botapi.NewRootBoard(seg)
b.ToWire(wb, 0)
gid, err := ds.startGame(aiA.Info.ID, aiB.Info.ID, wb)
if err != nil {
return err
}
// Run the game
for !b.IsFinished() {
turnCtx, _ := gocontext.WithTimeout(ctx, 30*time.Second)
chA, chB := make(chan turnResult), make(chan turnResult)
go aiA.takeTurn(turnCtx, gid, b, 0, chA)
go aiB.takeTurn(turnCtx, gid, b, 1, chB)
ra, rb := <-chA, <-chB
if ra.err.HasError() || rb.err.HasError() {
// TODO: Something with errors
}
b.Update(ra.results, rb.results)
_, s, err := capnp.NewMessage(capnp.SingleSegment(nil))
if err != nil {
return err
}
r, err := botapi.NewRootReplay_Round(s)
if err != nil {
return err
}
wireBoard, err := r.NewEndBoard()
if err != nil {
return err
}
b.ToWire(wireBoard, engine.P1Faction)
// TODO: Concatenate ra.results and rb.results and make that the move_list for this round
db.addRound(gid, r)
}
return nil
}
type onlineAI struct {
Info aiInfo
client botapi.Ai
}
type turnResult struct {
results botapi.Turn_List
err turnError
}
func (oa *onlineAI) takeTurn(ctx gocontext.Context, gid gameID, b *engine.Board, faction int, ch chan<- turnResult) {
results, err := oa.client.TakeTurn(ctx, func(p botapi.Ai_takeTurn_Params) error {
wb, err := p.NewBoard()
if err != nil {
return err
}
wb.SetGameId(string(gid))
return b.ToWire(wb, faction)
}).Struct()
var te turnError
if err != nil {
te = append(te, err)
}
tl, err := results.Turns()
if err != nil {
te = append(te, err)
}
ch <- turnResult{tl, te}
}
type turnError []error
func (t turnError) Error() string {
var e string
for _, err := range t {
e += err.Error()
}
return e
}
func (t turnError) HasError() bool {
return len(t) > 0
}