simple-web-game/player.go

85 lines
1.3 KiB
Go

package main
import (
"encoding/json"
"fmt"
"log"
"math"
"golang.org/x/net/websocket"
)
type Position struct {
X, Y int
}
type player struct {
Position Position `json:"position"`
Name string `json:"name"`
ws *websocket.Conn
send chan *player
}
func (p *player) validMove(next Position) (r bool) {
r = true
if math.Abs(float64(p.Position.X-next.X)) > 1 {
r = false
}
if math.Abs(float64(p.Position.Y-next.Y)) > 1 {
r = false
}
return
}
func (p *player) sender() {
for pinfo := range p.send {
err := websocket.JSON.Send(p.ws, pinfo)
if err != nil {
break
}
}
p.ws.Close()
}
func (p *player) recv() {
for {
var msg string
err := websocket.Message.Receive(p.ws, &msg)
if err != nil {
break
}
// XXX: the danger!
var pos Position
err = json.Unmarshal([]byte(msg), &pos)
if err != nil {
break
}
if !p.validMove(pos) {
break
}
p.Position = pos
g.broadcast <- p
}
p.ws.Close()
}
func addPlayer(ws *websocket.Conn) {
var name string
err := websocket.Message.Receive(ws, &name)
if err != nil {
log.Fatal("trouble parsing username")
}
p := &player{
Name: name,
send: make(chan *player, 256),
ws: ws,
}
g.register <- p
defer func() {
g.unregister <- p
}()
go p.sender()
p.recv()
fmt.Printf("%v has been disconnect from this game\n", p)
}