Simplify state machine.

This commit is contained in:
Marco 2022-12-22 00:02:07 +01:00
parent b0db6145e8
commit 39a824a1bc

View File

@ -12,9 +12,8 @@ type chessGame struct {
}
const (
WhiteToMove = 0
BlackToMove = 1
CheckPlayerChange = 2
PlayerToMove = 0
CheckPlayerChange = 1
)
func NewChessGame(gameId int, players [2]Player) *chessGame {
@ -28,7 +27,9 @@ func NewChessGame(gameId int, players [2]Player) *chessGame {
func (game *chessGame) handle() {
gameState := WhiteToMove
defer log.Println("Game ", game.id, ": handle() ended")
gameState := PlayerToMove
game.currentTurnPlayer = game.players[0]
var move *chessMove
var messageType int
@ -43,72 +44,56 @@ func (game *chessGame) handle() {
for {
switch gameState {
case WhiteToMove:
case PlayerToMove:
var err error
messageType, receivedMessage, err = ReadMessageFromPlayer(&game.players[0])
messageType, receivedMessage, err = ReadMessageFromPlayer(&game.currentTurnPlayer)
if err != nil {
log.Println("Error during message reading:", err)
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 0 moved: ", move)
log.Println("Player ", game.currentTurnPlayer, " moved: ", move)
if err != nil {
log.Println("Game: ", game.id, err)
return
continue
}
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))
if err != nil {
log.Println("Game: ", game.id, err)
return
}
log.Println("Player 1 moved: ", move)
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
continue
}
err = WriteMessageToPlayer(&game.players[1], receivedMessage, messageType)
if err != nil {
log.Println("Error during message writing:", err)
break
continue
}
gameState = PlayerToMove
} else {
if game.currentTurnPlayer.id == game.players[0].id {
gameState = WhiteToMove
} else {
gameState = BlackToMove
}
// Nothing to do if move was not real
}
}
log.Println("GameState = ", gameState)
if gameState == PlayerToMove {
log.Println("with player ", game.currentTurnPlayer, " to move")
}
}
}
func addPlayersToGame(players [2]Player) {