80 lines
1.6 KiB
Go
80 lines
1.6 KiB
Go
package store
|
|
|
|
import (
|
|
"github.com/danyel/go-fish/internal/game"
|
|
"sync"
|
|
)
|
|
|
|
type PlayerStore struct {
|
|
mu sync.Mutex
|
|
players map[string]*game.Player
|
|
games map[string]*game.Game // keyed by player ID
|
|
}
|
|
|
|
func NewPlayerStore() *PlayerStore {
|
|
return &PlayerStore{
|
|
players: make(map[string]*game.Player),
|
|
games: make(map[string]*game.Game),
|
|
}
|
|
}
|
|
|
|
func (s *PlayerStore) AddPlayer(id, name string) *game.Player {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
p := game.NewPlayer(id, name)
|
|
s.players[id] = p
|
|
return p
|
|
}
|
|
|
|
func (s *PlayerStore) GetPlayer(id string) (*game.Player, bool) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
p, ok := s.players[id]
|
|
return p, ok
|
|
}
|
|
|
|
func (s *PlayerStore) GetAvailablePlayers() []*game.Player {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
var available []*game.Player
|
|
for _, p := range s.players {
|
|
if p.Connected && len(p.Hand) < 7 {
|
|
available = append(available, p)
|
|
}
|
|
}
|
|
return available
|
|
}
|
|
|
|
func (s *PlayerStore) RemovePlayer(id string) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
delete(s.players, id)
|
|
delete(s.games, id)
|
|
}
|
|
|
|
func (s *PlayerStore) MarkPlaying(id string) bool {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
p, ok := s.players[id]
|
|
if !ok {
|
|
return false
|
|
}
|
|
p.Connected = false // player is now in a game
|
|
return true
|
|
}
|
|
|
|
func (s *PlayerStore) GetGame(id string) (*game.Game, bool) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
g, ok := s.games[id]
|
|
return g, ok
|
|
}
|
|
|
|
func (s *PlayerStore) CreateGame(playerID string, g *game.Game) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
// Store game under the player's ID so ask handler can find it
|
|
s.games[playerID] = g
|
|
// Also store under game ID
|
|
s.games[g.ID] = g
|
|
}
|