mchess-server/server/game.go

106 lines
2.2 KiB
Go

package server
import (
"log"
"math/rand"
)
type chessGame struct {
id int
players [2]Player
currentTurnPlayer Player
}
const (
Player0_Move = 0
Player1_Move = 1
Check_Player_Change = 2
)
func NewChessGame(gameId int, players [2]Player) *chessGame {
var game chessGame = chessGame{
players: players,
id: gameId,
}
return &game
}
func (game *chessGame) handle() {
gameState := Player0_Move
game.currentTurnPlayer = game.players[0]
var move *chessMove
var messageType int
var receivedMessage []byte
game.players[0].conn.WriteMessage(1, []byte("fb"))
for {
switch gameState {
case Player0_Move:
var err error
messageType, receivedMessage, err = game.players[0].conn.ReadMessage()
if err != nil {
log.Println("Error during message reading:", err)
return
}
move, err = parseMove(string(receivedMessage))
if err != nil {
log.Println("Game: ", game.id, err)
return
}
gameState = Check_Player_Change
case Player1_Move:
var err error
messageType, receivedMessage, err = game.players[1].conn.ReadMessage()
if err != nil {
log.Println("Error during message reading:", err)
return
}
move, err = parseMove(string(receivedMessage))
if err != nil {
log.Println("Game: ", game.id, err)
return
}
gameState = Check_Player_Change
case Check_Player_Change:
if move.realMove {
if game.currentTurnPlayer == game.players[0] {
game.currentTurnPlayer = game.players[1]
gameState = Player1_Move
} else {
game.currentTurnPlayer = game.players[0]
gameState = Player0_Move
}
err := game.currentTurnPlayer.conn.WriteMessage(messageType, []byte(receivedMessage))
if err != nil {
log.Println("Error during message writing:", err)
break
}
} else {
if game.currentTurnPlayer == game.players[0] {
gameState = Player0_Move
} else {
gameState = Player1_Move
}
}
}
log.Println("GameState = ", gameState)
}
}
func addPlayersToGame(players [2]Player) {
log.Printf("Adding players \n%s\n%s\nto new game", players[0].name, players[1].name)
game := NewChessGame(rand.Int(), players)
go game.handle()
}