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

84 lines
1.7 KiB
Go

package coordinator
import (
"fmt"
"log"
"time"
"git.saintnet.tech/stryan/snengame/internal/game"
"github.com/google/uuid"
)
type Coordinator struct {
Match *Session
PlayerQueueChan chan uuid.UUID
CallbackChan map[uuid.UUID]chan bool
}
func NewCoordinator() *Coordinator {
return &Coordinator{
Match: NewSession(),
PlayerQueueChan: make(chan uuid.UUID),
CallbackChan: make(map[uuid.UUID]chan bool),
}
}
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")
c.Match = m
m.Game = game.NewGame()
c.CallbackChan[p1] <- true
c.CallbackChan[p2] <- true
}()
go func() {
time.Sleep(5)
if c.Match.Game == nil {
log.Println("clearing old match")
c.Match = nil
}
}()
}
func (c *Coordinator) Coordinate(cmd *SessionCommand) *SessionCommandResult {
switch cmd.Command {
case SessionCmdQuery:
c.CallbackChan[cmd.ID] = make(chan bool)
c.PlayerQueueChan <- cmd.ID
<-c.CallbackChan[cmd.ID]
return &SessionCommandResult{
ID: cmd.ID,
Result: SessionRespFound,
}
case SessionCmdJoin:
resp := c.Match.Join(cmd.ID)
return &SessionCommandResult{
ID: cmd.ID,
Result: resp,
}
case SessionCmdLeave:
c.Match.Leave(cmd.ID)
return &SessionCommandResult{
ID: cmd.ID,
Result: SessionRespLeft,
}
case SessionCmdPlay:
resp := c.Match.Play(cmd.ID, cmd.GameCommand)
return &SessionCommandResult{
ID: cmd.ID,
Result: SessionRespPlayed,
GameResult: resp,
}
}
return &SessionCommandResult{
ID: cmd.ID,
Result: SessionRespError,
}
}