server/protocol.go

70 lines
1.4 KiB
Go
Raw Normal View History

2013-08-21 07:53:34 -07:00
package main
import (
2013-09-03 23:26:40 -07:00
"bitbucket.org/hackerbots/bot"
2013-08-21 07:53:34 -07:00
"code.google.com/p/go.net/websocket"
"errors"
)
type Failure struct {
Reason string `json:"reason"`
Type string `json:"type"`
}
func NewFailure(reason string) *Failure {
return &Failure{
Reason: reason,
Type: "failure",
}
}
2013-09-03 23:26:40 -07:00
func Negociate(ws *websocket.Conn, id string, width, height float64) (*bot.Config, error) {
2013-08-21 07:53:34 -07:00
var err error
2013-09-03 23:26:40 -07:00
err = websocket.JSON.Send(ws, bot.NewIdRequest(id))
2013-08-21 07:53:34 -07:00
if err != nil {
return nil, errors.New("generic servr error")
}
2013-09-03 23:26:40 -07:00
var clientid bot.ClientID
2013-08-21 07:53:34 -07:00
err = websocket.JSON.Receive(ws, &clientid)
if err != nil {
return nil, errors.New("could not parse id")
}
if v, msg := clientid.Valid(); !v {
websocket.JSON.Send(
ws,
NewFailure(msg),
)
return nil, errors.New(msg)
}
2013-09-03 23:26:40 -07:00
gameParam := bot.NewGameParam(width, height)
2013-08-21 07:53:34 -07:00
err = websocket.JSON.Send(ws, gameParam)
if err != nil {
websocket.JSON.Send(ws, NewFailure("generic server error"))
return nil, err
}
switch clientid.Type {
case "robot":
2013-09-03 23:26:40 -07:00
var conf bot.Config
2013-08-21 07:53:34 -07:00
for {
err = websocket.JSON.Receive(ws, &conf)
if err != nil {
return nil, err
}
// TODO: verify conf's type
2013-09-03 23:26:40 -07:00
if conf.Stats.Valid() {
_ = websocket.JSON.Send(ws, bot.NewHandshake(id, true))
2013-08-21 07:53:34 -07:00
break
} else {
2013-09-03 23:26:40 -07:00
_ = websocket.JSON.Send(ws, bot.NewHandshake(id, false))
2013-08-21 07:53:34 -07:00
}
}
return &conf, nil
case "spectator":
return nil, nil
}
return nil, nil
}