server/player.go

109 lines
2.2 KiB
Go

package main
import (
"bitbucket.org/hackerbots/bot"
v "bitbucket.org/hackerbots/vector"
"code.google.com/p/go.net/websocket"
"log"
"math/rand"
)
type player struct {
ws *websocket.Conn
game *game
Robot bot.Robot
send chan *bot.Boardstate
Instruction instruction
}
type instruction struct {
MoveTo *v.Point2d `json:"move_to,omitempty"`
FireAt *v.Point2d `json:"fire_at,omitempty"`
Stats bot.Stats `json:"stats"`
}
func (p *player) sender() {
for things := range p.send {
err := websocket.JSON.Send(p.ws, *things)
if err != nil {
break
}
}
p.ws.Close()
}
func (p *player) recv() {
for {
var msg instruction
err := websocket.JSON.Receive(p.ws, &msg)
if err != nil {
log.Print(err)
break
}
if msg.MoveTo != nil {
p.Robot.MoveTo = msg.MoveTo
}
if msg.FireAt != nil {
p.Robot.FireAt = msg.FireAt
}
if msg.Stats.Speed > 0 {
p.Robot.Stats = msg.Stats
p.Robot.Health = p.Robot.Stats.Hp
log.Printf("%+v", p.Robot.Stats)
}
}
p.ws.Close()
}
func (p *player) nudge() {
newPos := v.Move(p.Robot.Position, p.Robot.MoveTo, p.Robot.Stats.Speed, delta)
p.Robot.Position.X = newPos.X
p.Robot.Position.Y = newPos.Y
}
func (p *player) scan() {
p.Robot.Scanners = make([]bot.Scanner, 0)
for player := range p.game.players {
if player.Robot.Id == p.Robot.Id || player.Robot.Health <= 0 {
continue
}
dist := v.Distance(player.Robot.Position, p.Robot.Position)
if dist < float64(p.Robot.Stats.ScannerRadius) {
s := bot.Scanner{
Position: v.Point2d{
X: player.Robot.Position.X,
Y: player.Robot.Position.Y,
},
}
p.Robot.Scanners = append(p.Robot.Scanners, s)
}
}
}
func (p *player) fire() *bot.Projectile {
for proj := range p.game.projectiles {
if proj.Id == p.Robot.Id {
return nil
}
}
return &bot.Projectile{
Id: p.Robot.Id,
Position: p.Robot.Position,
MoveTo: *p.Robot.FireAt,
Damage: 10,
Radius: p.Robot.Stats.WeaponRadius,
Speed: float64(p.Robot.Stats.Speed * 2),
}
}
func (p *player) reset() {
start_pos := v.Point2d{
X: rand.Float64() * *width,
Y: rand.Float64() * *height,
}
p.Robot.MoveTo = &start_pos
p.Robot.Position = start_pos
p.Robot.Health = p.Robot.Stats.Hp
}