mchess-server/chess/match.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

110 lines
2.3 KiB
Go

package chess
import (
"log"
"github.com/google/uuid"
)
type Game struct {
id uuid.UUID
players [2]Player
currentTurnPlayer Player
}
const (
PlayerToMove = 0
CheckPlayerChange = 1
)
func NewGame() *Game {
var game Game = Game{
id: uuid.New(),
}
return &game
}
func (game Game) getPlayer1() *Player {
return &game.players[0]
}
func (game Game) getPlayer2() *Player {
return &game.players[1]
}
func (game *Game) handle() {
defer log.Println("Game ", game.id, ": handle() ended")
<-game.getPlayer1().wsConnEstablished
log.Println("WS connection for player 1 established")
<-game.getPlayer2().wsConnEstablished
log.Println("WS connection for player 2 established")
gameState := PlayerToMove
game.currentTurnPlayer = *game.getPlayer1()
var move *Move
var receivedMessage []byte
for {
switch gameState {
case PlayerToMove:
var err error
_, receivedMessage, err = game.currentTurnPlayer.ReadMessageFromPlayer()
if err != nil {
log.Println("Error while reading message:", err)
// At the moment, we return when there is an error while reading a message.
// This means, the game just ends uncontrolled
return
}
move, err = parseMove(string(receivedMessage))
log.Println("Player ", game.currentTurnPlayer, " moved: ", move)
if err != nil {
log.Println("Game: ", game.id, err)
continue
}
gameState = CheckPlayerChange
case CheckPlayerChange:
if game.currentTurnPlayer.Uuid == game.players[0].Uuid {
game.currentTurnPlayer = game.players[1]
} else {
game.currentTurnPlayer = game.players[0]
}
err := game.getPlayer1().WriteMessageToPlayer(receivedMessage)
if err != nil {
log.Println("Error during message writing:", err)
continue
}
err = game.getPlayer2().WriteMessageToPlayer(receivedMessage)
if err != nil {
log.Println("Error during message writing:", err)
continue
}
gameState = PlayerToMove
}
log.Println("GameState = ", gameState)
if gameState == PlayerToMove {
log.Println("with player ", game.currentTurnPlayer, " to move")
}
}
}
func (game *Game) addPlayersToGame(players [2]Player) {
log.Printf("Adding players %s and %s to new game", players[0].Uuid.String(), players[1].Uuid.String())
for i := range players {
players[i].InGame = true
}
game.players = players
go game.handle()
}