mchess-server/chess/player.go

58 lines
1.2 KiB
Go
Raw Normal View History

package chess
2023-04-18 20:19:28 +00:00
import (
"context"
"log"
2023-06-06 20:58:33 +00:00
"time"
2023-04-18 20:19:28 +00:00
"github.com/google/uuid"
"nhooyr.io/websocket"
2023-04-18 20:19:28 +00:00
)
type Player struct {
Uuid uuid.UUID
Conn *websocket.Conn
InGame bool
wsConnEstablished chan bool
context context.Context
}
2023-04-18 20:19:28 +00:00
func NewPlayer(uuid uuid.UUID) *Player {
return &Player{
Uuid: uuid,
Conn: nil,
InGame: false,
wsConnEstablished: make(chan bool),
}
}
2023-06-06 20:58:33 +00:00
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
}
2023-06-06 20:58:33 +00:00
func (p *Player) WaitForWebsocketConnection(c chan bool) {
timer := time.NewTimer(500 * time.Second)
select {
case <-p.wsConnEstablished:
c <- true
case <-timer.C:
return
}
}