mchess-server/api/move.go

47 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"
)
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})
}