mchess-server/chess/lobby.go
Marco aac428baab First changes to move away from central registry of all players
1. Introduce 'usher' that opens lobbies and fills it and waits for them
   to be filled
2. Add global registry of all games
2023-05-31 23:55:40 +02:00

61 lines
976 B
Go

package chess
import (
"sync"
"github.com/google/uuid"
)
type Lobby struct {
players map[uuid.UUID]*Player
mutex sync.Mutex
}
var lobbyInstance *Lobby = nil
func GetLobby() *Lobby {
if lobbyInstance == nil {
lobbyInstance = newLobby()
}
return lobbyInstance
}
func newLobby() *Lobby {
return &Lobby{
players: make(map[uuid.UUID]*Player, 0),
}
}
func (l *Lobby) RegisterPlayer(player *Player) {
l.players[player.Uuid] = player
var playersToBeAddedToGame []Player
for _, player := range l.players {
if !player.InGame {
playersToBeAddedToGame = append(playersToBeAddedToGame, *player)
}
}
if len(playersToBeAddedToGame) < 2 {
return
}
game := NewGame()
game.addPlayersToGame([2]Player(playersToBeAddedToGame[:2]))
}
func (l *Lobby) GetPlayer(playerID uuid.UUID) (*Player, bool) {
player, found := l.players[playerID]
return player, found
}
func (l *Lobby) Lock() {
l.mutex.Lock()
}
func (l *Lobby) Unlock() {
l.mutex.Unlock()
}