snengame/internal/coordinator/session.go
2021-07-22 18:19:21 -04:00

99 lines
2.2 KiB
Go

package coordinator
import (
"fmt"
"git.saintnet.tech/stryan/snengame/internal/game"
"github.com/google/uuid"
)
type SessionCmd string
type SessionResp string
const (
SessionCmdQuery SessionCmd = "query"
SessionCmdJoin = "join"
SessionCmdLeave = "leave"
SessionCmdPlay = "play"
)
const (
SessionRespFound SessionResp = "found"
SessionRespJoined1 = "joined p1"
SessionRespJoined2 = "joined p2"
SessionRespJoinError = "join error"
SessionRespLeft = "left"
SessionRespPlayed = "played"
SessionRespError = "generic error"
)
type Session struct {
p1 uuid.UUID
p2 uuid.UUID
pMap map[uuid.UUID]int
Game *game.Game
}
func NewSession() *Session {
return &Session{
p1: uuid.Nil,
p2: uuid.Nil,
pMap: make(map[uuid.UUID]int),
Game: nil,
}
}
func (s *Session) Join(id uuid.UUID) SessionResp {
if s.p1 == uuid.Nil {
s.p1 = id
s.pMap[id] = game.SentinalID
return SessionRespJoined1
} else if s.p2 == uuid.Nil {
s.p2 = id
s.pMap[id] = game.ScourgeID
return SessionRespJoined2
} else {
return SessionRespJoinError
}
}
func (s *Session) Leave(id uuid.UUID) {
if id == s.p1 {
s.p1 = uuid.Nil
} else if id == s.p2 {
s.p2 = uuid.Nil
}
if s.p1 == uuid.Nil && s.p2 == uuid.Nil {
s.Game = nil
} else if s.Game.Status != game.StatusDraw || s.Game.Status != game.StatusScourgeWin || s.Game.Status != game.StatusSentinalWin {
s.Game.Status = game.StatusStop
}
}
func (s *Session) Play(id uuid.UUID, cmd *game.Command) *game.CommandResult {
if s.pMap[id] != cmd.PlayerID {
return nil
}
return s.Game.Parse(cmd)
}
type SessionCommand struct {
ID uuid.UUID `json:"player_id"`
Command SessionCmd `json:"command"`
GameCommand *game.Command `json:"game_command"`
}
func (s *SessionCommand) String() string {
return fmt.Sprintf("%v %v\n%v\n", s.ID, s.Command, s.GameCommand)
}
type SessionCommandResult struct {
ID uuid.UUID `json:"player_id"`
Result SessionResp `json:"result"`
GameResult *game.CommandResult `json:"game_result"`
}
func (s *SessionCommandResult) String() string {
return fmt.Sprintf("%v %v\n%v\n", s.ID, s.Result, s.GameResult)
}