mchess-server/server/game.go

102 lines
2.2 KiB
Go

package server
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) handle() {
defer log.Println("Game ", game.id, ": handle() ended")
gameState := PlayerToMove
game.currentTurnPlayer = game.players[0]
var move *Move
var messageType int
var receivedMessage []byte
for {
switch gameState {
case PlayerToMove:
var err error
messageType, receivedMessage, err = ReadMessageFromPlayer(&game.currentTurnPlayer)
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 := WriteMessageToPlayer(&game.players[0], receivedMessage, messageType)
if err != nil {
log.Println("Error during message writing:", err)
continue
}
err = WriteMessageToPlayer(&game.players[1], receivedMessage, messageType)
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 _, player := range players {
player.InGame = true
}
game.players = players
go game.handle()
}
func removePlayersFromLobby(players [2]Player) {
panic("not yet implemented")
}