package coordinator import ( "fmt" "log" "time" "git.saintnet.tech/stryan/snengame/internal/game" "github.com/google/uuid" ) type Coordinator struct { Matches map[uuid.UUID]*Session PlayerQueueChan chan uuid.UUID CallbackChan map[uuid.UUID]chan uuid.UUID } func NewCoordinator() *Coordinator { return &Coordinator{ Matches: make(map[uuid.UUID]*Session), PlayerQueueChan: make(chan uuid.UUID), CallbackChan: make(map[uuid.UUID]chan uuid.UUID), } } func (c *Coordinator) Start() { go func() { m := NewSession() var p1, p2 uuid.UUID p1 = <-c.PlayerQueueChan fmt.Println("p1 join") p2 = <-c.PlayerQueueChan fmt.Println("p2 join") m.Active = true m.Game = game.NewGame() c.Matches[m.ID] = m c.CallbackChan[p1] <- m.ID c.CallbackChan[p2] <- m.ID }() go func() { for { time.Sleep(10) for _, v := range c.Matches { if v.Game == nil && v.Active { log.Println("clearing match with no game") delete(c.Matches, v.ID) } } } }() } func (c *Coordinator) Coordinate(cmd *SessionCommand) *SessionCommandResult { switch cmd.Command { case SessionCmdQuery: c.CallbackChan[cmd.ID] = make(chan uuid.UUID) c.PlayerQueueChan <- cmd.ID m := <-c.CallbackChan[cmd.ID] return &SessionCommandResult{ ID: cmd.ID, MatchID: m, Result: SessionRespFound, } case SessionCmdJoin: m, exists := c.Matches[cmd.MatchID] if !exists { return &SessionCommandResult{ ID: cmd.ID, MatchID: uuid.Nil, Result: SessionRespJoinError, } } resp := m.Join(cmd.ID) return &SessionCommandResult{ ID: cmd.ID, MatchID: m.ID, Result: resp, } case SessionCmdLeave: m, exists := c.Matches[cmd.MatchID] if !exists || !m.PlayerIn(cmd.ID) { return &SessionCommandResult{ ID: cmd.ID, MatchID: uuid.Nil, Result: SessionRespLeft, } } m.Leave(cmd.ID) return &SessionCommandResult{ ID: cmd.ID, MatchID: uuid.Nil, Result: SessionRespLeft, } case SessionCmdPlay: m, exists := c.Matches[cmd.MatchID] if !exists || !m.PlayerIn(cmd.ID) { return &SessionCommandResult{ ID: cmd.ID, MatchID: uuid.Nil, Result: SessionRespLeft, } } resp := m.Play(cmd.ID, cmd.GameCommand) return &SessionCommandResult{ ID: cmd.ID, MatchID: m.ID, Result: SessionRespPlayed, GameResult: resp, } } return &SessionCommandResult{ ID: cmd.ID, MatchID: uuid.Nil, Result: SessionRespError, } }