mchess-server/api/move.go
Marco af993876fd Introduce check if the game has ended (checkmate/stalemate)
Introduce checkmate check and send out 'gameEnded' message
2024-01-17 23:06:48 +01:00

48 lines
1.2 KiB
Go

package api
import (
"encoding/json"
"mchess_server/types"
)
type WebsocketMessage struct {
Type MessageType `json:"messageType"`
Move *types.Move `json:"move,omitempty"`
TurnColor *types.ChessColor `json:"turnColor,omitempty"`
PlayerColor *types.ChessColor `json:"playerColor,omitempty"`
Reason *string `json:"reason,omitempty"`
Position *string `json:"position,omitempty"`
}
type MessageType string
const (
BoardStateMessage MessageType = "boardState"
MoveMessage MessageType = "move"
InvalidMoveMessage MessageType = "invalidMove"
ColorDetermined MessageType = "colorDetermined"
GameEnded MessageType = "gameEnded"
)
func (m WebsocketMessage) IsValid() bool {
return m.IsValidMoveMessage()
}
func (m WebsocketMessage) IsValidMoveMessage() bool {
if m.Type != MoveMessage {
return false
}
if m.Move == nil {
return false
}
return true
}
func GetColorDeterminedMessage(color types.ChessColor) ([]byte, error) {
return json.Marshal(WebsocketMessage{Type: ColorDetermined, PlayerColor: &color})
}
func GetInvalidMoveMessage(move types.Move, reason string) ([]byte, error) {
return json.Marshal(WebsocketMessage{Type: InvalidMoveMessage, Move: &move, Reason: &reason})
}