mchess-server/server/game.go

105 lines
2.4 KiB
Go

package server
import (
"log"
"math/rand"
)
type chessGame struct {
id int
players [2]Player
currentTurnPlayer Player
}
const (
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() {
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 {
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 move.realMove {
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
} else {
// 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) {
log.Printf("Adding players %d and %d to new game", players[0].uuid, players[1].uuid)
game := NewChessGame(rand.Int(), players)
go game.handle()
}