Marco
efefa4ced5
With this commit, we stop waiting for the websocket connection to be established before the game starts. Now, the Connection type is responsible for waiting for the websocket connection before writing.
91 lines
1.8 KiB
Go
91 lines
1.8 KiB
Go
package chess
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"log"
|
|
"mchess_server/api"
|
|
conn "mchess_server/connection"
|
|
"mchess_server/types"
|
|
|
|
"github.com/google/uuid"
|
|
"nhooyr.io/websocket"
|
|
)
|
|
|
|
type Player struct {
|
|
Uuid uuid.UUID
|
|
Conn *conn.Connection
|
|
InGame bool
|
|
color types.ChessColor
|
|
}
|
|
|
|
func NewPlayer(uuid uuid.UUID) *Player {
|
|
return &Player{
|
|
Uuid: uuid,
|
|
Conn: conn.NewConnection(conn.WithContext(context.Background())),
|
|
InGame: false,
|
|
}
|
|
}
|
|
|
|
func (p Player) HasWebsocketConnection() bool {
|
|
return p.Conn.HasWebsocketConnection()
|
|
}
|
|
|
|
func (p *Player) SetWebsocketConnection(ctx context.Context, ws *websocket.Conn) {
|
|
p.Conn.SetWebsocketConnection(ws)
|
|
}
|
|
|
|
func (p *Player) SendMoveAndPosition(move types.Move, boardPosition string) error {
|
|
messageToSend, err := json.Marshal(api.WebsocketMessage{
|
|
Type: api.MoveMessage,
|
|
Move: &move,
|
|
Position: &boardPosition,
|
|
})
|
|
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 {
|
|
return p.Conn.Write(msg)
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
if !msg.IsValid() {
|
|
return types.Move{}, errors.New("not a valid move")
|
|
}
|
|
|
|
return *msg.Move, nil
|
|
}
|
|
|
|
func (p *Player) readMessage() ([]byte, error) {
|
|
msg, err := p.Conn.Read()
|
|
log.Printf("Reading message: %s from player %s", string(msg), p.Uuid.String())
|
|
|
|
return msg, err
|
|
}
|
|
|
|
func (p Player) GetPlayerColor() string {
|
|
return string(p.color)
|
|
}
|