2023-05-31 21:55:40 +00:00
|
|
|
package chess
|
2022-12-14 21:19:47 +00:00
|
|
|
|
2023-04-18 20:19:28 +00:00
|
|
|
import (
|
2023-05-30 20:01:20 +00:00
|
|
|
"context"
|
|
|
|
"log"
|
|
|
|
|
2023-04-18 20:19:28 +00:00
|
|
|
"github.com/google/uuid"
|
2023-04-22 19:41:24 +00:00
|
|
|
"nhooyr.io/websocket"
|
2023-04-18 20:19:28 +00:00
|
|
|
)
|
2022-12-14 21:19:47 +00:00
|
|
|
|
|
|
|
type Player struct {
|
2023-05-30 20:01:20 +00:00
|
|
|
Uuid uuid.UUID
|
|
|
|
Conn *websocket.Conn
|
|
|
|
InGame bool
|
|
|
|
wsConnEstablished chan bool
|
|
|
|
context context.Context
|
2023-05-31 21:55:40 +00:00
|
|
|
|
|
|
|
JoinedLobby chan bool
|
2023-04-22 19:41:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type PlayerInfo struct {
|
|
|
|
PlayerID uuid.UUID `json:"playerID"`
|
2022-12-14 21:19:47 +00:00
|
|
|
}
|
|
|
|
|
2023-04-18 20:19:28 +00:00
|
|
|
func NewPlayer(uuid uuid.UUID) *Player {
|
2022-12-14 21:19:47 +00:00
|
|
|
return &Player{
|
2023-05-30 20:01:20 +00:00
|
|
|
Uuid: uuid,
|
|
|
|
Conn: nil,
|
|
|
|
InGame: false,
|
|
|
|
wsConnEstablished: make(chan bool),
|
2023-05-31 21:55:40 +00:00
|
|
|
JoinedLobby: make(chan bool),
|
2022-12-14 21:19:47 +00:00
|
|
|
}
|
|
|
|
}
|
2023-05-30 20:01:20 +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
|
|
|
|
}
|