mchess-server/chess/game.go

131 lines
2.6 KiB
Go

package chess
import (
"encoding/json"
"local/m/mchess_server/api"
"log"
"time"
"github.com/google/uuid"
)
type Game struct {
id uuid.UUID
players []*Player
currentTurnPlayer *Player
}
const (
PlayerToMove = 0
CheckPlayerChange = 1
)
func NewGame() *Game {
var game Game = Game{
id: uuid.New(),
}
return &game
}
func (game Game) GetPlayers() []*Player {
return game.players
}
func (game Game) GetPlayer1() *Player {
return game.players[0]
}
func (game Game) GetPlayer2() *Player {
return game.players[1]
}
func (game *Game) Handle() {
defer game.killGame()
ok := game.waitForWebsocketConnections()
if !ok {
return
}
gameState := PlayerToMove
game.currentTurnPlayer = game.GetPlayer1()
var move api.Move
var receivedMessage []byte
var err error
for {
switch gameState {
case PlayerToMove:
_, receivedMessage, err = game.currentTurnPlayer.ReadMessageFromPlayer()
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
}
err = json.Unmarshal(receivedMessage, &move)
log.Println("Player ", game.currentTurnPlayer, " moved:\n", move)
if err != nil {
log.Println("Game: ", game.id, err)
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)
if gameState == PlayerToMove {
log.Println("with player ", game.currentTurnPlayer, " to move")
}
}
}
func (game *Game) AddPlayersToGame(player *Player) {
game.players = append(game.players, player)
}
func (game *Game) killGame() {
log.Println("Game should be killed")
}
func (game *Game) waitForWebsocketConnections() bool {
timer := time.NewTimer(5 * time.Second)
numberOfConnections := 0
waitingForPlayers := make(chan bool)
go game.GetPlayer1().WaitForWebsocketConnection(waitingForPlayers)
go game.GetPlayer2().WaitForWebsocketConnection(waitingForPlayers)
for numberOfConnections < 2 {
select {
case <-waitingForPlayers:
numberOfConnections++
case <-timer.C:
return false
}
}
return true
}