mchess-server/server/player.go
Marco 6cbd7d37aa Various changes
1. Make lobby a struct containing the players and a mutex used to lock
   itself
2. Wait for websocket connections to be established by both players
   before starting the game.
3. Add methods to write to and read from players
2023-05-30 22:01:20 +02:00

50 lines
1.1 KiB
Go

package server
import (
"context"
"log"
"github.com/google/uuid"
"nhooyr.io/websocket"
)
type Player struct {
Uuid uuid.UUID
Conn *websocket.Conn
InGame bool
wsConnEstablished chan bool
context context.Context
}
type PlayerInfo struct {
PlayerID uuid.UUID `json:"playerID"`
}
func NewPlayer(uuid uuid.UUID) *Player {
return &Player{
Uuid: uuid,
Conn: nil,
InGame: false,
wsConnEstablished: make(chan bool),
}
}
func (p *Player) SetConnection(ctx context.Context, conn websocket.Conn) {
p.Conn = &conn
p.context = ctx
p.wsConnEstablished <- true
}
func (p *Player) WriteMessageToPlayer(msg []byte) error {
log.Printf("Writing message: %s to player %d", string(msg), p.Uuid)
return p.Conn.Write(p.context, websocket.MessageText, msg)
}
func (p *Player) ReadMessageFromPlayer() (websocket.MessageType, []byte, error) {
msgType, msg, err := p.Conn.Read(p.context)
log.Printf("Reading message: %s (with messagetype %d) from player %d", string(msg), msgType, p.Uuid)
return msgType, msg, err
}