snengame/internal/coordinator/coordinator.go

118 lines
2.4 KiB
Go
Raw Normal View History

2021-07-22 18:19:21 -04:00
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
2021-07-22 18:19:21 -04:00
PlayerQueueChan chan uuid.UUID
CallbackChan map[uuid.UUID]chan uuid.UUID
2021-07-22 18:19:21 -04:00
}
func NewCoordinator() *Coordinator {
return &Coordinator{
Matches: make(map[uuid.UUID]*Session),
2021-07-22 18:19:21 -04:00
PlayerQueueChan: make(chan uuid.UUID),
CallbackChan: make(map[uuid.UUID]chan uuid.UUID),
2021-07-22 18:19:21 -04:00
}
}
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
2021-07-22 18:19:21 -04:00
m.Game = game.NewGame()
c.Matches[m.ID] = m
c.CallbackChan[p1] <- m.ID
c.CallbackChan[p2] <- m.ID
2021-07-22 18:19:21 -04:00
}()
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)
}
}
2021-07-22 18:19:21 -04:00
}
}()
}
func (c *Coordinator) Coordinate(cmd *SessionCommand) *SessionCommandResult {
switch cmd.Command {
case SessionCmdQuery:
c.CallbackChan[cmd.ID] = make(chan uuid.UUID)
2021-07-22 18:19:21 -04:00
c.PlayerQueueChan <- cmd.ID
m := <-c.CallbackChan[cmd.ID]
2021-07-22 18:19:21 -04:00
return &SessionCommandResult{
ID: cmd.ID,
MatchID: m,
Result: SessionRespFound,
2021-07-22 18:19:21 -04:00
}
case SessionCmdJoin:
m, exists := c.Matches[cmd.MatchID]
if !exists {
2021-07-25 16:23:39 -04:00
return &SessionCommandResult{
ID: cmd.ID,
MatchID: uuid.Nil,
Result: SessionRespJoinError,
2021-07-25 16:23:39 -04:00
}
}
resp := m.Join(cmd.ID)
2021-07-22 18:19:21 -04:00
return &SessionCommandResult{
ID: cmd.ID,
MatchID: m.ID,
Result: resp,
2021-07-22 18:19:21 -04:00
}
case SessionCmdLeave:
m, exists := c.Matches[cmd.MatchID]
if !exists || !m.PlayerIn(cmd.ID) {
2021-07-25 16:23:39 -04:00
return &SessionCommandResult{
ID: cmd.ID,
MatchID: uuid.Nil,
Result: SessionRespLeft,
2021-07-25 16:23:39 -04:00
}
}
m.Leave(cmd.ID)
2021-07-22 18:19:21 -04:00
return &SessionCommandResult{
ID: cmd.ID,
MatchID: uuid.Nil,
Result: SessionRespLeft,
2021-07-22 18:19:21 -04:00
}
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)
2021-07-22 18:19:21 -04:00
return &SessionCommandResult{
ID: cmd.ID,
MatchID: m.ID,
2021-07-22 18:19:21 -04:00
Result: SessionRespPlayed,
GameResult: resp,
}
}
return &SessionCommandResult{
ID: cmd.ID,
MatchID: uuid.Nil,
Result: SessionRespError,
2021-07-22 18:19:21 -04:00
}
}