forked from cygni/snakebot-client-golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
247 lines (216 loc) · 5.94 KB
/
main.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
package main
import (
"encoding/json"
"flag"
"fmt"
"github.com/gorilla/websocket"
"github.com/hokaccha/go-prettyjson"
log "github.com/sirupsen/logrus"
prefixed "github.com/x-cray/logrus-prefixed-formatter"
"gopkg.in/alecthomas/kingpin.v2"
"net/url"
"os"
"text/tabwriter"
"time"
)
var (
host = kingpin.Flag("host", "Host to connect to").Short('r').Default("localhost").String()
port = kingpin.Flag("port", "Port to connect to").Short('p').Default("8080").String()
venue = kingpin.Flag("venue", "Venue to connect to").Short('v').Default("training").Enum("training", "tournament")
logLevel = kingpin.Flag("log-level", "Logging level to use").Short('l').Default("info").Enum(log.DebugLevel.String(), log.InfoLevel.String(), log.WarnLevel.String(), log.ErrorLevel.String(), log.FatalLevel.String())
)
func main() {
kingpin.Parse()
logLevel, _ := log.ParseLevel(*logLevel)
log.SetLevel(logLevel)
formatter := new(prefixed.TextFormatter)
log.SetFormatter(formatter)
conn := Connection{}
conn.Start(*host, *port, *venue)
log.Info("All done, closing down")
}
type Connection struct {
logger *log.Entry
conn *websocket.Conn
done chan struct{}
messages chan Message
heartBeat chan string
isTraining bool
snake Snake
}
type Message struct {
t interface{}
bytes []byte
}
func (c *Connection) connect(host string, port string, venue string) {
c.logger = log.WithFields(log.Fields{"host": host, "port": port, "venue": venue, "prefix": "client"})
addr := flag.String("addr", host+":"+port, "http service address")
u := url.URL{Scheme: "ws", Host: *addr, Path: "/" + venue}
c.logger.Info("Connecting to websocket")
conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
c.logger.WithError(err).Fatal("Error connecting to websocket")
}
c.conn = conn
c.done = make(chan struct{}, 1)
}
func (c *Connection) Start(host string, port string, venue string) {
c.connect(host, port, venue)
c.messages = make(chan Message, 1)
c.snake = GetSnake()
c.conn.WriteJSON(RegisterPlayerMessage(c.snake.Name))
c.conn.WriteJSON(ClientInfoMessage())
go c.readMessages()
for {
select {
case message := <-c.messages:
c.routeMessage(message)
case playerId := <-c.heartBeat:
c.sendHeartBeat(playerId)
case <-c.done:
return
}
}
}
func (c *Connection) readMessages() {
for {
msg := c.nextMessage()
if msg != nil {
c.messages <- *msg
}
}
}
func (c Connection) nextMessage() *Message {
msgType, bytes, err := c.conn.ReadMessage()
if err != nil {
c.logger.WithError(err).Error("Got an error reading the next message from websocket.")
c.close()
return nil
}
if msgType == websocket.BinaryMessage {
c.logger.Error("Received unexpected binary message!")
return nil
}
var msg TypedMessage
err = json.Unmarshal(bytes, &msg)
if err != nil {
c.logger.WithError(err).WithFields(log.Fields{
"msg": string(bytes),
}).Error("Unable to parse incoming message as JSON")
return nil
}
if msg.Type == "" {
c.logger.WithField("msg", string(bytes)).Error("No type for message!")
return nil
}
return &Message{
t: msg.Type,
bytes: bytes,
}
}
func (c *Connection) routeMessage(msg Message) {
switch msg.t {
case PLAYER_REGISTERED:
var m PlayerRegistered
c.messageToJson(&m, msg.bytes)
c.snake.OnPlayerRegistered(m.GameSettings)
c.conn.WriteJSON(StartGameMessage())
c.isTraining = m.GameMode == "TRAINING"
if !c.isTraining {
go c.startHeartBeat(m.ReceivingPlayerId)
}
case GAME_LINK_EVENT:
var m GameLink
c.messageToJson(&m, msg.bytes)
c.logger.WithFields(log.Fields{
"url": m.Url,
}).Info("Received link to watch game")
case GAME_STARTING:
var m GameStarting
c.messageToJson(&m, msg.bytes)
c.snake.OnGameStarting()
case MAP_UPDATE:
var m MapUpdate
c.messageToJson(&m, msg.bytes)
move := c.snake.GetNextMove(m.Map)
c.logger.WithFields(log.Fields{
"move": move,
}).Debug("Registering move to client")
c.conn.WriteJSON(RegisterMoveMessage(move, m))
case GAME_RESULT_EVENT:
var m GameResult
c.messageToJson(&m, msg.bytes)
c.logger.Info("Received game result, printing player ranks.")
LogFinalScore(m)
case SNAKE_DEAD:
var m SnakeDead
c.messageToJson(&m, msg.bytes)
c.snake.OnSnakeDead(m.DeathReason)
case INVALID_PLAYER_NAME:
var m InvalidPlayerName
c.messageToJson(&m, msg.bytes)
c.snake.OnInvalidPlayername(m.ReasonCode)
case HEART_BEAT_RESPONSE:
// do nothing
case GAME_ENDED:
var m GameEnded
c.messageToJson(&m, msg.bytes)
if c.isTraining {
c.close()
}
case TOURNAMENT_ENDED:
var m TournamentEnded
c.messageToJson(&m, msg.bytes)
c.close()
default:
c.logger.WithFields(log.Fields{
"type": msg.t,
"msg": string(msg.bytes),
}).Warn("Unknown message type received")
}
}
func (c Connection) messageToJson(s interface{}, bytes []byte) {
err := json.Unmarshal(bytes, &s)
if err != nil {
c.logger.WithFields(log.Fields{
"msg": string(bytes),
}).Error("Unable to parse JSON message to matching struct", err)
}
json, _ := prettyjson.Marshal(s)
c.logger.WithFields(log.Fields{
"json": string(json),
"msg": string(bytes),
}).Debug("Successfully parsed JSON message to struct")
}
func (c Connection) startHeartBeat(playerId string) {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
c.heartBeat <- playerId
case <-c.done:
return
}
}
}
func (c Connection) sendHeartBeat(playerId string) {
c.conn.WriteJSON(HeartBeatMessage(playerId))
}
func (c Connection) close() {
defer c.conn.Close()
c.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
close(c.done)
}
func LogFinalScore(result GameResult) {
w := new(tabwriter.Writer)
w.Init(os.Stdout, 5, 0, 1, ' ', tabwriter.AlignRight)
for _, player := range result.PlayerRanks {
alive := "dead"
if player.Alive {
alive = "alive"
}
fmt.Fprintf(w, "%d.\t%d pts \t%s \t(%s)\n", player.Rank, player.Points, player.PlayerName, alive)
}
w.Flush()
}