server/player.go

118 lines
2.2 KiB
Go

package main
import (
"code.google.com/p/go.net/websocket"
"encoding/json"
"log"
)
const maxMessageSize = 1024
type player struct {
ws *websocket.Conn
Robots []*Robot
send chan Message
Instruction Instruction
Id string
}
func (p *player) sender() {
log.Printf("%s: sender launched", p.Id)
for things := range p.send {
b, err := json.Marshal(things)
if err != nil {
break
}
// XXX: send the count to our bandwidth analyzer ...
_, err = p.ws.Write(b)
if err != nil {
break
}
}
p.ws.Close()
log.Printf("%s: robot (%s) sender close", p.Id, p.Robots[0].Id)
}
func (p *player) recv() {
buff := make([]byte, maxMessageSize)
var msgs map[string]Instruction
for {
n, err := p.ws.Read(buff)
if err != nil {
log.Printf("%s: problem reading from player: %s", p.Id, err)
break
}
// XXX: send n to our bandwidth analyzer ...
if n == len(buff) {
log.Printf("%s: read buffer overfull: %s", p.Id, string(buff))
break
}
err = json.Unmarshal(buff[:n], &msgs)
if err != nil {
log.Printf("%s: problem reading from player: %s", p.Id, err)
break
}
for _, r := range p.Robots {
msg, ok := msgs[r.Id]
if !ok {
continue
}
if msg.Repair != nil && *msg.Repair == true {
r.ActiveScan = false
r.TargetSpeed = 0
r.FireAt = nil
r.MoveTo = nil
if r.RepairCounter <= 0 {
r.RepairCounter = 3.0
}
} else if msg.Scan != nil && *msg.Scan == true {
r.RepairCounter = 0
r.TargetSpeed = 0
r.FireAt = nil
r.MoveTo = nil
r.ActiveScan = true
} else {
r.RepairCounter = 0
r.ActiveScan = false
// Reapiring halts all other activity
if msg.MoveTo != nil {
r.MoveTo = msg.MoveTo
}
if msg.Heading != nil {
r.DesiredHeading = msg.Heading
}
if msg.FireAt != nil {
r.FireAt = msg.FireAt
} else {
r.FireAt = nil
}
if msg.TargetSpeed != nil {
r.TargetSpeed = float32(*msg.TargetSpeed)
} else {
r.TargetSpeed = r.Stats.Speed
}
}
if msg.Probe != nil {
r.Probe = msg.Probe
r.ProbeResult = nil
} else {
r.Probe = nil
}
if msg.Message != nil {
r.Message = *msg.Message
}
}
}
log.Printf("%s: recv close", p.Id)
p.ws.Close()
}