mchess-server/server/game.go

102 lines
2.2 KiB
Go
Raw Normal View History

package server
import (
"log"
"github.com/google/uuid"
)
type Game struct {
id uuid.UUID
players [2]Player
currentTurnPlayer Player
}
const (
2022-12-21 23:02:07 +00:00
PlayerToMove = 0
CheckPlayerChange = 1
)
func NewGame() *Game {
var game Game = Game{
id: uuid.New(),
}
return &game
}
func (game *Game) 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
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 {
2023-04-18 20:19:28 +00:00
if game.currentTurnPlayer.uuid == game.players[0].uuid {
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 (game *Game) addPlayersToGame(players [2]Player) {
log.Printf("Adding players %s and %s to new game", players[0].uuid.String(), players[1].uuid.String())
game.players = players
}
2023-04-18 20:47:51 +00:00
func removePlayersFromLobby(players [2]Player) {
panic("not yet implemented")
}