snengame/internal/coordinator/coordinator.go

96 lines
1.9 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 {
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:
2021-07-25 16:23:39 -04:00
if c.Match == nil {
return &SessionCommandResult{
ID: cmd.ID,
Result: SessionRespJoinError,
}
}
2021-07-22 18:19:21 -04:00
resp := c.Match.Join(cmd.ID)
return &SessionCommandResult{
ID: cmd.ID,
Result: resp,
}
case SessionCmdLeave:
2021-07-25 16:23:39 -04:00
if c.Match == nil {
return &SessionCommandResult{
ID: cmd.ID,
Result: SessionRespLeft,
}
}
2021-07-22 18:19:21 -04:00
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,
}
}