2023-06-02 21:41:43 +00:00
|
|
|
package api
|
|
|
|
|
2023-06-12 20:32:31 +00:00
|
|
|
import (
|
|
|
|
"encoding/json"
|
2023-06-25 14:11:29 +00:00
|
|
|
"mchess_server/types"
|
2023-06-12 20:32:31 +00:00
|
|
|
)
|
2023-06-08 18:20:37 +00:00
|
|
|
|
|
|
|
type WebsocketMessage struct {
|
2023-12-09 13:45:57 +00:00
|
|
|
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"`
|
2023-06-02 21:41:43 +00:00
|
|
|
}
|
|
|
|
|
2023-06-08 18:20:37 +00:00
|
|
|
type MessageType string
|
|
|
|
|
|
|
|
const (
|
2023-12-09 13:45:57 +00:00
|
|
|
PositionMessage MessageType = "position"
|
2023-06-20 21:53:54 +00:00
|
|
|
MoveMessage MessageType = "move"
|
|
|
|
InvalidMoveMessage MessageType = "invalidMove"
|
|
|
|
ColorDetermined MessageType = "colorDetermined"
|
2023-06-08 18:20:37 +00:00
|
|
|
)
|
|
|
|
|
2023-10-12 19:03:12 +00:00
|
|
|
func (m WebsocketMessage) IsValid() bool {
|
|
|
|
return m.IsValidMoveMessage()
|
|
|
|
}
|
|
|
|
|
2023-06-20 21:53:54 +00:00
|
|
|
func (m WebsocketMessage) IsValidMoveMessage() bool {
|
2023-06-08 18:20:37 +00:00
|
|
|
if m.Type != MoveMessage {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if m.Move == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
2023-06-02 21:41:43 +00:00
|
|
|
}
|
2023-06-12 20:32:31 +00:00
|
|
|
|
|
|
|
func GetColorDeterminedMessage(color types.ChessColor) ([]byte, error) {
|
2023-12-09 13:45:57 +00:00
|
|
|
return json.Marshal(WebsocketMessage{Type: ColorDetermined, TurnColor: &color})
|
2023-06-20 21:53:54 +00:00
|
|
|
}
|
2023-06-12 20:32:31 +00:00
|
|
|
|
2023-06-20 21:53:54 +00:00
|
|
|
func GetInvalidMoveMessage(move types.Move, reason string) ([]byte, error) {
|
|
|
|
return json.Marshal(WebsocketMessage{Type: InvalidMoveMessage, Move: &move, Reason: &reason})
|
2023-06-12 20:32:31 +00:00
|
|
|
}
|