mchess-server/server/game.go

105 lines
2.4 KiB
Go
Raw Normal View History

package server
import (
"log"
"math/rand"
)
type chessGame struct {
id int
players [2]Player
currentTurnPlayer Player
}
const (
2022-12-21 23:02:07 +00:00
PlayerToMove = 0
CheckPlayerChange = 1
)
func NewChessGame(gameId int, players [2]Player) *chessGame {
var game chessGame = chessGame{
players: players,
id: gameId,
}
return &game
}
func (game *chessGame) handle() {
2022-12-21 23:02:07 +00:00
defer log.Println("Game ", game.id, ": handle() ended")
gameState := PlayerToMove
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 {
2022-12-21 23:02:07 +00:00
case PlayerToMove:
var err error
2022-12-21 23:02:07 +00:00
messageType, receivedMessage, err = ReadMessageFromPlayer(&game.currentTurnPlayer)
if err != nil {
2022-12-21 23:02:07 +00:00
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))
2022-12-21 23:02:07 +00:00
log.Println("Player ", game.currentTurnPlayer, " moved: ", move)
if err != nil {
log.Println("Game: ", game.id, err)
2022-12-21 23:02:07 +00:00
continue
}
gameState = CheckPlayerChange
case CheckPlayerChange:
if move.realMove {
if game.currentTurnPlayer.id == game.players[0].id {
game.currentTurnPlayer = game.players[1]
} else {
game.currentTurnPlayer = game.players[0]
}
2022-12-18 22:13:25 +00:00
err := WriteMessageToPlayer(&game.players[0], receivedMessage, messageType)
if err != nil {
log.Println("Error during message writing:", err)
2022-12-21 23:02:07 +00:00
continue
2022-12-18 22:13:25 +00:00
}
err = WriteMessageToPlayer(&game.players[1], receivedMessage, messageType)
if err != nil {
log.Println("Error during message writing:", err)
2022-12-21 23:02:07 +00:00
continue
}
2022-12-21 23:02:07 +00:00
gameState = PlayerToMove
} else {
2022-12-21 23:02:07 +00:00
// Nothing to do if move was not real
}
}
log.Println("GameState = ", gameState)
2022-12-21 23:02:07 +00:00
if gameState == PlayerToMove {
log.Println("with player ", game.currentTurnPlayer, " to move")
}
}
2022-12-21 23:02:07 +00:00
}
func addPlayersToGame(players [2]Player) {
2022-12-18 00:41:44 +00:00
log.Printf("Adding players %d and %d to new game", players[0].id, players[1].id)
game := NewChessGame(rand.Int(), players)
go game.handle()
}