package server import ( "log" "math/rand" ) type chessGame struct { id int players [2]Player currentTurnPlayer Player } const ( Player0_Move = 0 Player1_Move = 1 Check_Player_Change = 2 ) func NewChessGame(gameId int, players [2]Player) *chessGame { var game chessGame = chessGame{ players: players, id: gameId, } return &game } func (game *chessGame) handle() { gameState := Player0_Move game.currentTurnPlayer = game.players[0] var move *chessMove var messageType int var receivedMessage []byte game.players[1].conn.WriteMessage(1, []byte("fb")) for { switch gameState { case Player0_Move: var err error messageType, receivedMessage, err = game.players[0].conn.ReadMessage() 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 = Check_Player_Change case Player1_Move: var err error messageType, receivedMessage, err = game.players[1].conn.ReadMessage() 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 = Check_Player_Change case Check_Player_Change: if move.realMove { if game.currentTurnPlayer.id == game.players[0].id { game.currentTurnPlayer = game.players[1] gameState = Player1_Move } else { game.currentTurnPlayer = game.players[0] gameState = Player0_Move } err := game.currentTurnPlayer.conn.WriteMessage(messageType, []byte(receivedMessage)) if err != nil { log.Println("Error during message writing:", err) break } } else { if game.currentTurnPlayer.id == game.players[0].id { gameState = Player0_Move } else { gameState = Player1_Move } } } log.Println("GameState = ", gameState) } } func addPlayersToGame(players [2]Player) { log.Printf("Adding players \n%d\n%d\nto new game", players[0].id, players[1].id) game := NewChessGame(rand.Int(), players) go game.handle() }