mchess-server/chess/player.go

100 lines
2.0 KiB
Go
Raw Normal View History

package chess
2023-04-18 20:19:28 +00:00
import (
"context"
2023-06-08 18:20:37 +00:00
"encoding/json"
"errors"
"log"
2023-06-25 14:11:29 +00:00
"mchess_server/api"
"mchess_server/types"
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
}
2023-08-13 22:05:47 +00:00
func (p *Player) SendMoveAndPosition(move types.Move, boardPosition string) error {
2023-06-08 18:20:37 +00:00
messageToSend, err := json.Marshal(api.WebsocketMessage{
2023-10-12 19:03:12 +00:00
Type: api.MoveMessage,
Move: &move,
Position: &boardPosition,
2023-06-08 18:20:37 +00:00
})
if err != nil {
log.Println("Error while marshalling: ", err)
return err
}
err = p.writeMessage(messageToSend)
if err != nil {
log.Println("Error during message writing:", err)
return err
}
return nil
}
func (p *Player) writeMessage(msg []byte) error {
log.Printf("Writing message: %s to player %s", string(msg), p.Uuid.String())
return p.Conn.Write(p.context, websocket.MessageText, msg)
}
2023-06-08 18:20:37 +00:00
func (p *Player) ReadMove() (types.Move, error) {
_, receivedMessage, err := p.readMessage()
if err != nil {
return types.Move{}, err
}
var msg api.WebsocketMessage
err = json.Unmarshal(receivedMessage, &msg)
if err != nil {
return types.Move{}, err
}
2023-10-12 19:03:12 +00:00
if !msg.IsValid() {
2023-06-08 18:20:37 +00:00
return types.Move{}, errors.New("not a valid move")
}
return *msg.Move, nil
}
func (p *Player) readMessage() (websocket.MessageType, []byte, error) {
msgType, msg, err := p.Conn.Read(p.context)
2023-06-08 18:20:37 +00:00
log.Printf("Reading message: %s from player %s", string(msg), p.Uuid.String())
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
}
}