mchess-server/server/lobby.go
Marco 6cbd7d37aa Various changes
1. Make lobby a struct containing the players and a mutex used to lock
   itself
2. Wait for websocket connections to be established by both players
   before starting the game.
3. Add methods to write to and read from players
2023-05-30 22:01:20 +02:00

61 lines
977 B
Go

package server
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()
}