public void Save_FileAlreadySaved_ShouldOverwrite()
        {
            // arrange
            const string repoDirectory = "Test2/";

            Assert.False(Directory.Exists(repoDirectory));
            const string repoPath     = "Save_FileAlreadySaved_ShouldOverwrite.bin";
            const string entryPath    = "Test_Save_FileAlreadySaved_ShouldOverwrite.bin";
            var          gameStateOld = new ChessGameState(null, false, null, TeamColor.None, PlayerMode.SinglePlayer, 0);
            var          gameStateNew = new ChessGameState(null, true, null, TeamColor.None, PlayerMode.SinglePlayer, 0);
            var          repo         = new SaveRepository(repoDirectory, repoPath);

            repo.Save(entryPath, gameStateOld);

            // act
            bool isInRepoBefore = repo.Contains(entryPath);

            repo.Save(entryPath, gameStateNew);
            bool isInRepoAfter = repo.Contains(entryPath);
            var  fromRepo      = repo.Read(entryPath);

            // assert
            Assert.True(isInRepoBefore);
            Assert.True(isInRepoAfter);
            Assert.NotNull(fromRepo);
            Assert.AreEqual(fromRepo.IsEnded, gameStateNew.IsEnded);
            Assert.AreEqual(fromRepo.PlayerMode, gameStateNew.PlayerMode);

            // clear
            Directory.Delete(repoDirectory, true);
        }
        public void Delete_EntryInRepo_ShouldDelete_ShouldReturnTrue()
        {
            // arrange
            const string repoDirectory = "Test6/";

            Assert.False(Directory.Exists(repoDirectory));
            const string repoPath  = "Delete_EntryInRepo_ShouldDelete_ShouldReturnTrue.bin";
            const string entryPath = "Test_Delete_EntryInRepo_ShouldDelete_ShouldReturnTrue.bin";
            var          gameState = new ChessGameState(null, true, null, TeamColor.None, PlayerMode.SinglePlayer, 0);
            var          repoSaver = new SaveRepository(repoDirectory, repoPath);

            repoSaver.Save(entryPath, gameState);

            var repoDeleter = new SaveRepository(repoDirectory, repoPath);

            // act
            bool isInRepo = repoDeleter.Contains(entryPath);
            bool result   = repoDeleter.Delete(entryPath);

            // assert
            Assert.True(isInRepo);
            Assert.True(result);

            // clear
            Directory.Delete(repoDirectory, true);
        }
        public void Serialize_NextDeserialize_NullObject()
        {
            // arrange
            var        board       = new OrdinaryChessBoard();
            var        validator   = new OrdinaryBoardMoveValidator(board);
            var        verifier    = new OrdinaryBoardCheckVerifier(board, validator);
            var        moveResult  = new ValidMoveResult(board, verifier, validator, null, null);
            const bool isGameEnded = false;
            TeamColor  currentTeam = TeamColor.Black;

            const string filePath = "Test_Serialize_NextDeserialize_NullObject.bin";

            ChessGameState gameState =
                new ChessGameState(moveResult, isGameEnded, null, currentTeam, PlayerMode.TwoPlayers, 0);

            // act
            ChessGameSerializer.SaveInFile(filePath, gameState);
            ChessGameState fromFile = ChessGameSerializer.ReadFromFile <ChessGameState>(filePath);

            // assert
            Assert.AreEqual(fromFile.IsEnded, isGameEnded);
            Assert.AreEqual(fromFile.CurrentMovingTeam, currentTeam);

            // clear
            Assert.True(ChessGameSerializer.ClearFile(filePath));
        }
        public void Serialize_NextDeserialize_AlreadyWrittenFile()
        {
            // arrange
            var board     = new OrdinaryChessBoard();
            var validator = new OrdinaryBoardMoveValidator(board);
            var verifier  = new OrdinaryBoardCheckVerifier(board, validator);
            LastMoveViewModel lastMoveVm = new LastMoveViewModel(new King(new Position(1, 2), TeamColor.Black),
                                                                 new Position(1, 2), new Position(2, 3), null);
            var        moveResult  = new ValidMoveResult(board, verifier, validator, lastMoveVm, null);
            const bool isGameEnded = false;
            TeamColor  currentTeam = TeamColor.Black;

            const string filePath = "Serialize_NextDeserialize_AlreadyWrittenFile.bin";

            ChessGameState gameState =
                new ChessGameState(moveResult, isGameEnded, null, currentTeam, PlayerMode.TwoPlayers, 0);

            // act
            ChessGameSerializer.SaveInFile(filePath, gameState);
            ChessGameSerializer.SaveInFile(filePath, gameState);
            ChessGameState fromFile = ChessGameSerializer.ReadFromFile <ChessGameState>(filePath);

            // assert
            Assert.AreEqual(fromFile.IsEnded, isGameEnded);
            Assert.AreEqual(fromFile.CurrentMovingTeam, currentTeam);
            Assert.AreEqual(fromFile.LastGameMoveResult.LastMoveFigureAndPositionFromAndDest().Item2,
                            moveResult.LastMoveFigureAndPositionFromAndDest().Item2);

            // clear
            Assert.True(ChessGameSerializer.ClearFile(filePath));
        }
Exemple #5
0
 public GameConductor(ChessGameState state)
 {
     _currentMovingTeam = state.CurrentMovingTeam;
     _isCheckMate       = state.IsEnded;
     _smashed           = state.LastGameMoveResult.AllSmashedFigures().ToList();
     _moveManager       = new MoveManager.MoveManager(state.LastGameMoveResult.GetBoard().GetCopy());
 }
        public void Read_ValidPath_ShouldReturnSavedValue()
        {
            // arrange
            const string repoDirectory = "Test4/";

            Assert.False(Directory.Exists(repoDirectory));
            const string repoPath  = "Read_ValidPath_ShouldReturnSavedValue.bin";
            const string entryPath = "Test_Read_ValidPath_ShouldReturnSavedValue.bin";
            var          gameState = new ChessGameState(null, true, null, TeamColor.None, PlayerMode.SinglePlayer, 0);
            var          repoSaver = new SaveRepository(repoDirectory, repoPath);

            repoSaver.Save(entryPath, gameState);

            var repoReader = new SaveRepository(repoDirectory, repoPath);

            // act
            bool isInRepo = repoReader.Contains(entryPath);
            var  fromRepo = repoReader.Read(entryPath);

            // assert
            Assert.True(isInRepo);
            Assert.AreEqual(fromRepo.IsEnded, gameState.IsEnded);
            Assert.AreEqual(fromRepo.PlayerMode, gameState.PlayerMode);

            // clear
            Directory.Delete(repoDirectory, true);
        }
        public async Task PieceMovedAsync(string playerName, string from, string to, ChessGameState gameState)
        {
            await gameHubContext.Clients.User(gameState.GameInfo.White.Name == playerName?gameState.GameInfo.Black.Name : gameState.GameInfo.White.Name)
            .SendAsync("OnPieceMoved", from, to, gameState);

            await gameHubContext.Clients.Group(ChessFabrickUtils.GameGroupName(gameState.GameInfo.GameId)).SendAsync("OnBoardChanged", gameState);
        }
Exemple #8
0
        public async Task <ChessGameState> MovePieceAsync(string gameId, string playerName, string from, string to)
        {
            var dictActiveGames = await GetActiveGameDict();

            var dictCompletedGames = await GetCompletedGameDict();

            ChessGameState newGameState;
            var            board = new Board();

            using (var tx = StateManager.CreateTransaction())
            {
                var game = await GetActiveGameAsync(tx, gameId);

                if (playerName != game.White.Name && playerName != game.Black.Name)
                {
                    throw new ArgumentException("Player not in the game.");
                }

                board.PerformMoves(game.MoveHistory);
                var fromField = ChessGameUtils.FieldFromString(from);
                var toField   = ChessGameUtils.FieldFromString(to);
                var piece     = board[fromField.Item1, fromField.Item2];
                if (!piece.MoveTo(toField.Item1, toField.Item2))
                {
                    throw new ArgumentException("Illegal move.");
                }

                var newGameInfo = new ChessGameInfo(game.GameId, game.White, game.Black, board.ToMovesString());
                if (board.IsCheckmate || board.IsDraw)
                {
                    await dictActiveGames.TryRemoveAsync(tx, gameId);

                    await dictCompletedGames.TryAddAsync(tx, gameId, newGameInfo);
                }
                else
                {
                    await dictActiveGames.TryUpdateAsync(tx, gameId, newGameInfo, game);
                }

                await tx.CommitAsync();

                newGameState = new ChessGameState(newGameInfo);
            }

            var chessSignalRClient = proxyFactory.CreateServiceProxy <IChessFabrickSignalRService>(chessSignalRUri /*, ChessFabrickUtils.GuidPartitionKey(gameId)*/);

            chessSignalRClient.PieceMovedAsync(playerName, from, to, newGameState);

            if (newGameState.GetCurrentPlayer().IsBot() && !board.IsCheckmate && !board.IsDraw)
            {
                var actor = ActorProxy.Create <IChessFabrickActor>(new ActorId(gameId), chessActorUri);
                actor.PerformMove();
            }

            return(newGameState);
        }
        public SinglePlayerModeConsoleGame(ChessGameState state)
        {
            _player          = state.Players[0];
            _difficulty      = state.DifficultyLevel;
            _gameConductor   = new GameConductor(state);
            _startMoveResult = state.LastGameMoveResult;
            TeamColor computerColor = _player.TeamColor == TeamColor.Black ? TeamColor.White : TeamColor.Black;

            _computer = new ComputerPlayer(computerColor, _difficulty + 1, _difficulty);
        }
 private void OnBoardChanged(ChessGameState board)
 {
     Console.WriteLine($"OnBoardChanged: {JsonConvert.SerializeObject(board)}");
     if (board?.GameInfo?.GameId != gameId)
     {
         return;
     }
     gameState     = board;
     selectedField = null;
     possibleMoves = null;
     showLastMove  = true;
     UpdateBoard();
 }
Exemple #11
0
        public static ChessGameState LookForCheckMateOrDraw(ChessBoard board, ChessPieceColor turn, List <ChessMove> chessMoves)
        {
            ChessGameState newGameState = ChessGameState.Active;

            List <ChessMove> possibleMoves = GetPossibleMoves(board, turn);

            if (possibleMoves.Count == 0)
            {
                if (IsInCheck(board, turn))
                {
                    newGameState = ChessGameState.CheckMate;
                }
                else
                {
                    newGameState = ChessGameState.StaleMate;
                }
            }

            if (newGameState == ChessGameState.Active)
            {
                if (chessMoves != null && chessMoves.Count > 8)
                {
                    int index = chessMoves.Count - 1;
                    if (CompareMoves(index - 7, index - 3, chessMoves) &&
                        CompareMoves(index - 6, index - 2, chessMoves) &&
                        CompareMoves(index - 5, index - 1, chessMoves) &&
                        CompareMoves(index - 4, index, chessMoves))
                    {
                        newGameState = ChessGameState.DrawByRepetition;
                    }
                }
            }

            if (newGameState == ChessGameState.Active)
            {
                if (board.count50MoveRule > 99)
                {
                    newGameState = ChessGameState.DrawBy50MoveRule;
                }
            }

            if (newGameState == ChessGameState.Active)
            {
                if (board.CheckDrawByMaterial())
                {
                    newGameState = ChessGameState.DrawByMaterial;
                }
            }

            return(newGameState);
        }
        private IMoveResult SaveGame(IMoveResult moveResult)
        {
            Console.WriteLine("Under what name save the game?");
            string file           = UserInteraction.ReadNotEmptyStringFromUser();
            var    saveRepository = SaveRepository.GetDefaultRepository();

            bool isEnded = moveResult.IsCheckMate(TeamColor.Black) || moveResult.IsCheckMate(TeamColor.White);
            var  state   = new ChessGameState(moveResult, isEnded, new [] { _player },
                                              _computer.MyTeamColor, PlayerMode.SinglePlayer, _difficulty);

            saveRepository.Save(file + ".bin", state);
            Console.WriteLine("Game saved.");
            return(new StoppedMoveResult());
        }
        private IMoveResult SaveGame(IMoveResult moveResult, int currentPlayer)
        {
            Console.WriteLine("Under what name save the game?");
            string file           = UserInteraction.ReadNotEmptyStringFromUser();
            var    saveRepository = SaveRepository.GetDefaultRepository();

            bool isEnded = moveResult.IsCheckMate(TeamColor.Black) || moveResult.IsCheckMate(TeamColor.White);
            var  state   = new ChessGameState(moveResult, isEnded, _players,
                                              _players[currentPlayer].TeamColor, PlayerMode.TwoPlayers, 0);

            saveRepository.Save(file + ".bin", state);
            Console.WriteLine("Game saved.");
            return(new StoppedMoveResult());
        }
        private async void btnAddBot_Click(object sender, EventArgs e)
        {
            try
            {
                var game = await PostAddBot();

                gameState = new ChessGameState(game);
                UpdateBoard();
            }
            catch (Exception ex)
            {
                txbMessage.Text = ex.Message;
                Console.Error.WriteLine(ex);
            }
        }
Exemple #15
0
        public void StartMove(string gameName, int x, int y)
        {
            SingleGame game;

            if (gameName != null && Games.ActualGames.TryGetValue(gameName, out game))
            {
                if (PlayersTurn(game))
                {
                    ChessGameState state = game.ActualGameState;

                    if (state != null)
                    {
                        Clients.Group(gameName).highLightFields(state.GetPossibleMoves(x, y));
                    }
                }
            }
        }
        private async Task StartHubConnection()
        {
            try
            {
                await connection.StartAsync();
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                var result = MessageBox.Show(this, ex.Message, "Unable to connect to the server. Retry?", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                switch (result)
                {
                case DialogResult.Yes:
                    await StartHubConnection();

                    return;

                case DialogResult.No:
                    Close();
                    return;
                }
            }
            try
            {
                if (playerColor == null)
                {
                    gameState = await connection.InvokeAsync <ChessGameState>("SpectateGame", gameId);

                    Console.WriteLine($"SpectateGame: {JsonConvert.SerializeObject(gameState)}");
                }
                else if (gameState != null)
                {
                    gameState = await connection.InvokeAsync <ChessGameState>("JoinGame", gameId);

                    Console.WriteLine($"JoinGame: {JsonConvert.SerializeObject(gameState)}");
                }
            }
            catch (HubException ex)
            {
                Console.Error.WriteLine(ex);
                txbMessage.Text = ex.Message;
            }
            UpdateBoard();
        }
        public ChessOnlineForm(UserModel user, Uri host, ChessGameInfo gameInfo)
        {
            this.user   = user;
            this.host   = host;
            this.gameId = gameInfo.GameId;

            if (gameInfo.White?.Name == user.Player.Name)
            {
                playerColor = PieceColor.White;
            }
            else if (gameInfo.Black?.Name == user.Player.Name)
            {
                playerColor = PieceColor.Black;
            }

            if (gameInfo.White != null && gameInfo.Black != null)
            {
                gameState = new ChessGameState(gameInfo);
            }

            InitializeComponent();
            InitializeBoard();
            InitHttpClient();
            InitHubConnection();

            Icon = Icon.FromHandle(Properties.Resources.knight_white.GetHicon());
            Text = $"Chess - {user.Player.Name}";

            if (playerColor == null)
            {
                grbPlayerColor.Text  = "Spectating";
                cfbPlayerColor.Image = Properties.Resources.eye;
            }
            else
            {
                grbPlayerColor.Text  = "Your color";
                cfbPlayerColor.Image = PieceImageUtils.Pawn(playerColor.Value);
            }
        }
        public void Contains_TrueAndFalse()
        {
            // arrange
            const string repoDirectory = "Test3/";

            Assert.False(Directory.Exists(repoDirectory));
            const string repoPath  = "Contains_Contains_ShouldReturnTrue.bin";
            const string entryPath = "Test_Contains_Contains_ShouldReturnTrue.bin";
            var          gameState = new ChessGameState(null, true, null, TeamColor.None, PlayerMode.SinglePlayer, 0);
            var          repo      = new SaveRepository(repoDirectory, repoPath);

            repo.Save(entryPath, gameState);

            // act
            bool isInValid   = repo.Contains(entryPath);
            bool isInInvalid = repo.Contains(entryPath + "!");

            // assert
            Assert.True(isInValid);
            Assert.False(isInInvalid);

            // clear
            Directory.Delete(repoDirectory, true);
        }
        private async void FieldBox_Click(object sender, EventArgs e)
        {
            var fieldBox = sender as ChessFieldBox;
            var field    = fieldBox.Tag as Tuple <int, int>;

            showLastMove = false;

            if (selectedField == null)
            {
                selectedField = field;
                var selectedPiece = board[selectedField.Item1, selectedField.Item2];
                if (selectedPiece?.Color != playerColor || selectedPiece?.Color != gameState.OnTurn)
                {
                    selectedField = null;
                }
                if (selectedField != null)
                {
                    fieldBox.Style = ChessFieldBox.BoxStyle.Selected;
                    fieldBox.Invalidate();
                    try
                    {
                        possibleMoves = new List <Tuple <int, int> >();
                        var newPossibleMoves = new List <Tuple <int, int> >();
                        var moves            = await connection.InvokeAsync <List <string> >("GetPieceMoves", gameId,
                                                                                             ChessGameUtils.FieldToString(selectedField.Item1, selectedField.Item2)
                                                                                             );

                        foreach (var move in moves)
                        {
                            newPossibleMoves.Add(ChessGameUtils.FieldFromString(move));
                        }
                        possibleMoves = newPossibleMoves;
                    } catch (HubException ex)
                    {
                        selectedField = null;
                        possibleMoves = null;
                        Console.Error.WriteLine(ex);
                        txbMessage.Text = ex.Message;
                    }
                }
            }
            else
            {
                if (possibleMoves.Contains(field))
                {
                    try
                    {
                        gameState = await connection.InvokeAsync <ChessGameState>("MovePiece", gameId,
                                                                                  ChessGameUtils.FieldToString(selectedField.Item1, selectedField.Item2),
                                                                                  ChessGameUtils.FieldToString(field.Item1, field.Item2)
                                                                                  );
                    } catch (HubException ex)
                    {
                        Console.Error.WriteLine(ex);
                        txbMessage.Text = ex.Message;
                    }
                }
                selectedField = null;
                possibleMoves = null;
            }
            UpdateBoard();
        }
Exemple #20
0
 public SingleGame()
 {
     ActualGameState = new ChessGameState();
     IsOver          = false;
 }
Exemple #21
0
        public void MoveTo(string gameName, int x1, int y1, int x2, int y2)
        {
            SingleGame game;

            if (gameName != null && Games.ActualGames.TryGetValue(gameName, out game))
            {
                if (PlayersTurn(game))
                {
                    lock (game)
                    {
                        if (!game.IsOver)
                        {
                            ChessGameState state     = game.ActualGameState;
                            ChessGameState nextState = state.GetNextMove(x1, y1, x2, y2);

                            if (nextState != null)
                            {
                                AddToChat(
                                    gameName,
                                    "" +
                                    state.PieceSymbolAtPosition(x1, y1) +
                                    (char)('A' + x1) + (1 + y1) +
                                    " to " +
                                    nextState.PieceSymbolAtPosition(x2, y2) +
                                    (char)('A' + x2) + (1 + y2), "");

                                game.ActualGameState = nextState;
                                state = nextState;

                                Games.ShudeleGameRemoval(
                                    gameName,
                                    game.UpdateTime,
                                    game.TourTime,
                                    "Timeout: " + (state.Tour == ChessGameState.Color.White ? "balck player won" : "white player won"));
                            }

                            updateGameState(Clients.Group(gameName), game);

                            if (game.IsOver)
                            {
                                string status = "draw";
                                if (game.ActualGameState.WhiteChecked.Value)
                                {
                                    status = "balck player won";
                                }
                                if (game.ActualGameState.BlackChecked.Value)
                                {
                                    status = "white player won";
                                }

                                AddToChat(
                                    gameName,
                                    "Game over: " + status,
                                    "");
                            }
                        }
                    }
                }
                else
                {
                    updateGameState(Clients.Caller, game);
                }
            }
        }
 public TwoPlayersModeConsoleGame(ChessGameState state)
 {
     _players       = state.Players;
     _gameConductor = new GameConductor(state);
     _moveResult    = state.LastGameMoveResult;
 }
 public ChessOnlineForm(UserModel user, Uri host, ChessGameState gameState)
     : this(user, host, gameState.GameInfo)
 {
 }