mchess-server/chess/game.go

106 lines
2.3 KiB
Go
Raw Normal View History

package chess
import (
"encoding/json"
"local/m/mchess_server/api"
"log"
"github.com/google/uuid"
)
type Game struct {
id uuid.UUID
players []*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) getPlayer1() *Player {
return game.players[0]
}
func (game Game) getPlayer2() *Player {
return game.players[1]
}
func (game *Game) Handle() {
2022-12-21 23:02:07 +00:00
defer log.Println("Game ", game.id, ": handle() ended")
log.Println("Game ", game.id, " started")
<-game.getPlayer1().wsConnEstablished
log.Println("WS connection for player 1 established")
<-game.getPlayer2().wsConnEstablished
log.Println("WS connection for player 2 established")
2022-12-21 23:02:07 +00:00
gameState := PlayerToMove
game.currentTurnPlayer = game.getPlayer1()
var move api.Move
var receivedMessage []byte
var err error
for {
switch gameState {
2022-12-21 23:02:07 +00:00
case PlayerToMove:
_, receivedMessage, err = game.currentTurnPlayer.ReadMessageFromPlayer()
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
}
err = json.Unmarshal(receivedMessage, &move)
log.Println("Player ", game.currentTurnPlayer, " moved:\n", move)
if err != nil {
log.Println("Game: ", game.id, err)
2022-12-21 23:02:07 +00:00
continue
}
gameState = CheckPlayerChange
case CheckPlayerChange:
if game.currentTurnPlayer.Uuid == game.players[0].Uuid {
game.currentTurnPlayer = game.players[1]
} else {
game.currentTurnPlayer = game.players[0]
}
err := game.getPlayer1().WriteMessageToPlayer(receivedMessage)
if err != nil {
log.Println("Error during message writing:", err)
continue
}
err = game.getPlayer2().WriteMessageToPlayer(receivedMessage)
if err != nil {
log.Println("Error during message writing:", err)
continue
}
gameState = PlayerToMove
}
log.Println("GameState = ", gameState)
2022-12-21 23:02:07 +00:00
if gameState == PlayerToMove {
log.Println("with player ", game.currentTurnPlayer, " to move")
}
}
}
func (game *Game) AddPlayersToGame(player *Player) {
game.players = append(game.players, player)
}