package server import ( "log" "math/rand" ) type chessGame struct { id int players [2]Player currentTurnPlayer Player } const ( WhiteToMove = 0 BlackToMove = 1 CheckPlayerChange = 2 ) func NewChessGame(gameId int, players [2]Player) *chessGame { var game chessGame = chessGame{ players: players, id: gameId, } return &game } func (game *chessGame) handle() { gameState := WhiteToMove game.currentTurnPlayer = game.players[0] var move *chessMove var messageType int var receivedMessage []byte WriteMessageToPlayer(&game.players[0], []byte("bd init"), 1) WriteMessageToPlayer(&game.players[1], []byte("bd init"), 1) WriteMessageToPlayer(&game.players[0], []byte("cl white"), 1) WriteMessageToPlayer(&game.players[1], []byte("cl black"), 1) for { switch gameState { case WhiteToMove: var err error messageType, receivedMessage, err = ReadMessageFromPlayer(&game.players[0]) if err != nil { log.Println("Error during message reading:", err) return } move, err = parseMove(string(receivedMessage)) log.Println("Player 0 moved: ", move) if err != nil { log.Println("Game: ", game.id, err) return } gameState = CheckPlayerChange case BlackToMove: var err error messageType, receivedMessage, err = ReadMessageFromPlayer(&game.players[1]) if err != nil { log.Println("Error during message reading:", err) return } move, err = parseMove(string(receivedMessage)) log.Println("Player 1 moved: ", move) if err != nil { log.Println("Game: ", game.id, err) return } gameState = CheckPlayerChange case CheckPlayerChange: if move.realMove { if game.currentTurnPlayer.id == game.players[0].id { game.currentTurnPlayer = game.players[1] gameState = BlackToMove } else { game.currentTurnPlayer = game.players[0] gameState = WhiteToMove } err := WriteMessageToPlayer(&game.players[0], receivedMessage, messageType) if err != nil { log.Println("Error during message writing:", err) break } err = WriteMessageToPlayer(&game.players[1], receivedMessage, messageType) if err != nil { log.Println("Error during message writing:", err) break } } else { if game.currentTurnPlayer.id == game.players[0].id { gameState = WhiteToMove } else { gameState = BlackToMove } } } log.Println("GameState = ", gameState) } } func addPlayersToGame(players [2]Player) { log.Printf("Adding players %d and %d to new game", players[0].id, players[1].id) game := NewChessGame(rand.Int(), players) go game.handle() }