Implemented multiple encoders/decoders

I really think we're close here; once we have gob server-side this might just
work.
This commit is contained in:
Stephen McQuay 2014-03-10 23:25:11 -07:00
parent dc7db48201
commit 839b5789e3

View File

@ -1,6 +1,8 @@
package main package main
import ( import (
"encoding/gob"
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"log" "log"
@ -45,6 +47,14 @@ type robot struct {
wg *sync.WaitGroup wg *sync.WaitGroup
} }
type encoder interface {
Encode(v interface{}) error
}
type decoder interface {
Decode(v interface{}) error
}
func (r *robot) negociate() (err error) { func (r *robot) negociate() (err error) {
if *verbose { if *verbose {
log.Printf("%s: trying to connect to game '%s'", r.name, r.game.Name) log.Printf("%s: trying to connect to game '%s'", r.name, r.game.Name)
@ -158,19 +168,30 @@ func (r *robot) play() {
log.Printf("%s: starting loop", r.name) log.Printf("%s: starting loop", r.name)
var enc encoder
var dec decoder
if r.game.Encoding == "json" {
enc = json.NewEncoder(r.ws)
dec = json.NewDecoder(r.ws)
} else {
enc = gob.NewEncoder(r.ws)
dec = gob.NewDecoder(r.ws)
}
for { for {
r.speed = float32(maxSpeed) r.speed = float32(maxSpeed)
if *verbose { if *verbose {
log.Printf("%s: about to wait on boardstate", r.name) log.Printf("%s: about to wait on boardstate", r.name)
} }
err = websocket.JSON.Receive(r.ws, &r.boardstate) err = dec.Decode(&r.boardstate)
if *verbose {
log.Printf("%s: one recv boardstate", r.name)
}
if err != nil { if err != nil {
log.Printf("%s: Connection lost", r.name) log.Printf("%s: Connection lost", r.name)
return return
} }
if *verbose {
log.Printf("%s: one recv boardstate", r.name)
}
// TODO: I need a truly-verbose flag? // TODO: I need a truly-verbose flag?
// if *verbose { // if *verbose {
// log.Printf("\n\n%#v\n\n", r.boardstate) // log.Printf("\n\n%#v\n\n", r.boardstate)
@ -199,7 +220,7 @@ func (r *robot) play() {
FireAt: r.fireat, FireAt: r.fireat,
}, },
} }
err = websocket.JSON.Send(r.ws, instruction) err = enc.Encode(instruction)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return return