server/protocol.go
2013-09-03 23:26:40 -07:00

70 lines
1.4 KiB
Go

package main
import (
"bitbucket.org/hackerbots/bot"
"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",
}
}
func Negociate(ws *websocket.Conn, id string, width, height float64) (*bot.Config, error) {
var err error
err = websocket.JSON.Send(ws, bot.NewIdRequest(id))
if err != nil {
return nil, errors.New("generic servr error")
}
var clientid bot.ClientID
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)
}
gameParam := bot.NewGameParam(width, height)
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":
var conf bot.Config
for {
err = websocket.JSON.Receive(ws, &conf)
if err != nil {
return nil, err
}
// TODO: verify conf's type
if conf.Stats.Valid() {
_ = websocket.JSON.Send(ws, bot.NewHandshake(id, true))
break
} else {
_ = websocket.JSON.Send(ws, bot.NewHandshake(id, false))
}
}
return &conf, nil
case "spectator":
return nil, nil
}
return nil, nil
}