Example #1
0
        protected virtual void OnMouseClick(object sender, MouseEventArgs e)
        {
            if (HoverPosition == null)
            {
                ThreatenedPositions = Enumerable.Empty <Position>();
                return;
            }

            if (!ThreatenedPositions.Contains(HoverPosition) && ChessRepresentation[HoverPosition] == null)
            {
                return;
            }

            var mechanism = new ChessMechanism();

            SelectedPosition = HoverPosition;
            var selectedPositionOwner = _chessRepresentation[SelectedPosition]?.Owner;

            if (selectedPositionOwner == null)
            {
                ThreatenedPositions = Enumerable.Empty <Position>();
                return;
            }

            ThreatenedPositions = mechanism.GenerateMoves(_chessRepresentation, selectedPositionOwner).OfType <BaseChessMove>()
                                  .Where(x => x.From == SelectedPosition).Select(x => x.To).ToList();
        }
Example #2
0
        public void GenerateMovesTest_KnightMovesReturnedWithCapture_WhiteSide()
        {
            var expectedKnightMoves = new[]
            {
                new ChessMove(ChessPlayer.White, Positions.D4, Positions.C2),
                new ChessMove(ChessPlayer.White, Positions.D4, Positions.E2),
                new ChessMove(ChessPlayer.White, Positions.D4, Positions.B3),
                new ChessMove(ChessPlayer.White, Positions.D4, Positions.F3),
                new ChessMove(ChessPlayer.White, Positions.D4, Positions.F5),
                new ChessMove(ChessPlayer.White, Positions.D4, Positions.C6),
                new ChessMove(ChessPlayer.White, Positions.D4, Positions.E6)
            }.ToHashSet();

            var board = new ChessRepresentation()
            {
                CurrentPlayer = ChessPlayer.White,
            };

            board[Positions.D4] = new Knight(ChessPlayer.White, true);
            board[Positions.B5] = new Pawn(ChessPlayer.White, false);
            board[Positions.B2] = new Pawn(ChessPlayer.White, false);
            board[Positions.E6] = new Pawn(ChessPlayer.Black, false);
            board[Positions.F5] = new Pawn(ChessPlayer.Black, false);

            var game        = new ChessMechanism();
            var moves       = game.GenerateMoves(board).ToList();
            var knightMoves = moves.OfType <ChessMove>()
                              .Where(x => x.From == Positions.D4)
                              .Where(x => x.Owner == ChessPlayer.White)
                              .ToHashSet();

            Assert.Subset(expectedKnightMoves, knightMoves);
            Assert.Subset(knightMoves, expectedKnightMoves);
        }
Example #3
0
        public void GenerateMovesTest_BishopMovesReturnedWithCapture_WhiteSide()
        {
            var expectedBishopMoves = new[]
            {
                new ChessMove(ChessPlayer.White, Positions.D4, Positions.E5),
                new ChessMove(ChessPlayer.White, Positions.D4, Positions.C5),
                new ChessMove(ChessPlayer.White, Positions.D4, Positions.E3),
                new ChessMove(ChessPlayer.White, Positions.D4, Positions.C3)
            }.ToHashSet();

            var board = new ChessRepresentation()
            {
                CurrentPlayer = ChessPlayer.White,
            };

            board[Positions.D4] = new Bishop(ChessPlayer.White, true);
            board[Positions.F6] = new Pawn(ChessPlayer.White, false);
            board[Positions.B6] = new Queen(ChessPlayer.White, false);
            board[Positions.B2] = new Pawn(ChessPlayer.White, false);
            board[Positions.E3] = new Pawn(ChessPlayer.Black, false);
            board[Positions.E8] = new King(ChessPlayer.Black, false);

            var game        = new ChessMechanism();
            var moves       = game.GenerateMoves(board).ToList();
            var bishopMoves = moves.OfType <ChessMove>()
                              .Where(x => x.From == Positions.D4)
                              .Where(x => x.Owner == ChessPlayer.White)
                              .ToHashSet();

            Assert.Subset(expectedBishopMoves, bishopMoves);
            Assert.Subset(bishopMoves, expectedBishopMoves);
        }
Example #4
0
        public void GameStateCheck_CheckMateTest_WhiteWins()
        {
            var expected = GameState.WhiteWon;

            //Scholar's Mate
            var game      = new ChessRepresentationInitializer().Create();
            var mechanism = new ChessMechanism();
            var moves     = new List <BaseMove>(7)
            {
                new ChessMove(ChessPlayer.White, Positions.E2, Positions.E4),
                new ChessMove(ChessPlayer.Black, Positions.E7, Positions.E5),
                new ChessMove(ChessPlayer.White, Positions.F1, Positions.C4),
                new ChessMove(ChessPlayer.Black, Positions.B8, Positions.C6),
                new ChessMove(ChessPlayer.White, Positions.D1, Positions.H5),
                new ChessMove(ChessPlayer.Black, Positions.G8, Positions.F6),
                new ChessMove(ChessPlayer.White, Positions.H5, Positions.F7)
            };

            foreach (var move in moves)
            {
                game = mechanism.ApplyMove(game, move);
            }

            var actual = mechanism.GetGameState(game);

            Assert.Equal(expected, actual);
        }
        /// <inheritdoc />
        public ChessGameDetails ConvertToChessGameDetails(DbChessGame source)
        {
            if (source == null)
            {
                return(null);
            }

            var history = source.History?.OrderBy(x => x.CreatedAt).Select(CovertToChessMove).ToList() ?? new List <BaseMove>();

            var representation = new ChessRepresentationInitializer().Create();
            var chessMechanism = new ChessMechanism();

            foreach (var move in history)
            {
                representation = chessMechanism.ApplyMove(representation, move);
            }

            return(new ChessGameDetails
            {
                ChallengeDate = source.ChallengeDate,
                Id = source.Id,
                InitiatedBy = ConvertUser(source.InitiatedBy),
                LastMoveDate = source.LastMoveDate,
                Name = source.Name,
                Opponent = ConvertUser(source.Opponent),
                BlackPlayer = ConvertUser(source.BlackPlayer),
                WhitePlayer = ConvertUser(source.WhitePlayer),
                Representation = representation
            });
        }
Example #6
0
        public void ChessBoardTest_SameOutcomeDifferentHistory_BoardsAreNonEqual()
        {
            var mechanism = new ChessMechanism();
            var game1     = new ChessRepresentationInitializer().Create();
            var game2     = new ChessRepresentationInitializer().Create();

            var move1 = new ChessMove(ChessPlayer.White, Positions.B1, Positions.C3);
            var move2 = new ChessMove(ChessPlayer.Black, Positions.B8, Positions.C6);

            game1 = mechanism.ApplyMove(game1, move1);
            game1 = mechanism.ApplyMove(game1, move2);
            game2 = mechanism.ApplyMove(game2, move1);
            game2 = mechanism.ApplyMove(game2, move2);

            var move3 = new ChessMove(ChessPlayer.White, Positions.C3, Positions.E4);
            var move4 = new ChessMove(ChessPlayer.Black, Positions.C6, Positions.E5);
            var move5 = new ChessMove(ChessPlayer.White, Positions.E4, Positions.C3);
            var move6 = new ChessMove(ChessPlayer.Black, Positions.E5, Positions.C6);

            game1 = mechanism.ApplyMove(game1, move3);
            game1 = mechanism.ApplyMove(game1, move4);
            game1 = mechanism.ApplyMove(game1, move5);
            game1 = mechanism.ApplyMove(game1, move6);

            Assert.NotEqual(game1, game2);
        }
        public virtual async Task <ChessGameDetails> GetMatchAsync(string token, string id)
        {
            var url     = $"{GamesControllerUri.AbsoluteUri}/{id}";
            var uri     = new Uri(url);
            var message = new HttpRequestMessage(HttpMethod.Get, uri);

            message.Headers.Add("Authorization", $"Bearer {token}");

            var resultMessage = await _client.SendAsync(message);

            if (!resultMessage.IsSuccessStatusCode)
            {
                return(null);
            }

            var resultString = await resultMessage.Content.ReadAsStringAsync();

            var result = JsonConvert.DeserializeObject <ChessGameDetails>(resultString);

            var history = result.Representation.History;

            result.Representation = new ChessRepresentationInitializer().Create();
            var mechanism = new ChessMechanism();

            foreach (var baseMove in history)
            {
                result.Representation = mechanism.ApplyMove(result.Representation, baseMove);
            }

            return(result);
        }
        public virtual async Task <IEnumerable <ChessGameDetails> > GetMatchesWithDetailsAsync(string token)
        {
            var message = new HttpRequestMessage(HttpMethod.Get, GamesListDetailedControllerUri);

            message.Headers.Add("Authorization", $"Bearer {token}");

            var resultMessage = await _client.SendAsync(message);

            if (!resultMessage.IsSuccessStatusCode)
            {
                return(null);
            }

            var resultString = await resultMessage.Content.ReadAsStringAsync();

            var result    = JsonConvert.DeserializeObject <IEnumerable <ChessGameDetails> >(resultString).ToList();
            var mechanism = new ChessMechanism();

            foreach (var chessGameDetails in result)
            {
                var history = chessGameDetails.Representation.History;

                chessGameDetails.Representation = new ChessRepresentationInitializer().Create();

                foreach (var baseMove in history)
                {
                    chessGameDetails.Representation = mechanism.ApplyMove(chessGameDetails.Representation, baseMove);
                }
            }

            return(result);
        }
Example #9
0
        public MainForm()
        {
            InitializeComponent();
            tabPageGame.Tag    = Tabs.GamePage;
            tabPageMatches.Tag = Tabs.MatchesPage;
            tabPagePlayers.Tag = Tabs.PlayersPage;
            tabPageLog.Tag     = Tabs.LogPage;
            tabPageReadme.Tag  = Tabs.ReadmePage;
            _mechanism         = new ChessMechanism();

            _client = new ServiceConnection(_baseUrl);
            _client.PollFinished    += ClientOnPollFinished;
            _client.PollStarted     += ClientOnPollStarted;
            _client.BackgroundError += ClientOnBackgroundError;

            textboxReadme.Rtf = HumanClientResources.HumanClientDoc;

#if DEBUG
            textboxUsername.Text = "*****@*****.**";
            textboxPassword.Text = "*****@*****.**";
#else
            textboxUsername.Text = string.Empty;
            textboxPassword.Text = string.Empty;
#endif
        }
Example #10
0
        public void ValidationTest_InvalidMove_IllegalExceptionThrown(BaseMove move)
        {
            var game      = new ChessRepresentationInitializer().Create();
            var mechanism = new ChessMechanism();

            Assert.Throws <ChessIllegalMoveException>(() => { mechanism.ApplyMove(game, move); });
        }
Example #11
0
        public void GenerateMovesTest_KingMovesInChess_WhiteSide()
        {
            var expectedKnightMoves = new BaseMove[]
            {
                new SpecialMove(ChessPlayer.White, MessageType.Resign),
                new ChessMove(ChessPlayer.White, Positions.C4, Positions.E2),
                new ChessMove(ChessPlayer.White, Positions.G2, Positions.G3),
                new ChessMove(ChessPlayer.White, Positions.G2, Positions.G1),
                new ChessMove(ChessPlayer.White, Positions.G2, Positions.H3),
                new ChessMove(ChessPlayer.White, Positions.G2, Positions.H1),
                new ChessMove(ChessPlayer.White, Positions.G2, Positions.F3),
                new ChessMove(ChessPlayer.White, Positions.G2, Positions.F1)
            }.ToHashSet();

            var board = new ChessRepresentation
            {
                CurrentPlayer  = ChessPlayer.White,
                [Positions.G2] = new King(ChessPlayer.White, true),
                [Positions.E2] = new Rook(ChessPlayer.Black, false),
                [Positions.C4] = new Queen(ChessPlayer.White, false),
                [Positions.G3] = new Pawn(ChessPlayer.Black, false)
            };

            var game  = new ChessMechanism();
            var moves = game.GenerateMoves(board).ToHashSet();

            Assert.Subset(expectedKnightMoves, moves);
            Assert.Subset(moves, expectedKnightMoves);
        }
Example #12
0
 public MoveGenerator(ChessMechanism mechanism)
 {
     _mechanism             = mechanism;
     _forbiddenMessageTypes = new List <MessageType>()
     {
         MessageType.Resign,
         MessageType.DrawAccept,
         MessageType.DrawOffer
     };
 }
Example #13
0
        private ChessRepresentation CalculateBoard(IReadOnlyList <BaseMove> history, int index)
        {
            var newBoard  = new ChessRepresentationInitializer().Create();
            var mechanism = new ChessMechanism();

            for (var i = 0; i < index; i++)
            {
                newBoard = mechanism.ApplyMove(newBoard, history[i]);
            }

            return(newBoard);
        }
Example #14
0
        public void GenerateMovesTest_Initial_AppropriateMovesReturned()
        {
            var expected = 21;

            var representation = new ChessRepresentationInitializer().Create();

            var game = new ChessMechanism();

            var moves  = game.GenerateMoves(representation);
            var result = moves.Count();

            Assert.Equal(expected, result);
        }
Example #15
0
        public void ChessBoardTest_EqualityCheck_BoardsAreEqual()
        {
            var generatorMechanism = new ChessMechanism();
            var applierMechanism1  = new ChessMechanism();
            var applierMechanism2  = new ChessMechanism();

            var numberOfTries = 10;

            var result = true;

            for (var i = 0; i < numberOfTries; i++)
            {
                var game1         = new ChessRepresentationInitializer().Create();
                var game2         = new ChessRepresentationInitializer().Create();
                var referenceGame = new ChessRepresentationInitializer().Create();

                var count = 0;
                while (true)
                {
                    count++;
                    var move = generatorMechanism.GenerateMoves(referenceGame)
                               .OfType <BaseChessMove>()
                               .OrderBy(x => Guid.NewGuid())
                               .FirstOrDefault();

                    if (move == null || count > 20)
                    {
                        break;
                    }

                    game1         = applierMechanism1.ApplyMove(game1, move);
                    game2         = applierMechanism2.ApplyMove(game2, move);
                    referenceGame = generatorMechanism.ApplyMove(referenceGame, move);
                }

                result = result && game1.Equals(game1);
                result = result && game2.Equals(game2);
                result = result && referenceGame.Equals(referenceGame);

                result = result && game1.Equals(game2);
                result = result && game2.Equals(referenceGame);
                result = result && referenceGame.Equals(game1);

                result = result && game1.Equals(referenceGame);
                result = result && referenceGame.Equals(game2);
                result = result && game2.Equals(game1);
            }

            Assert.True(result);
        }
Example #16
0
        /// <summary>
        /// Creates an instance of the service connection class.
        /// </summary>
        /// <param name="baseUrl">The base URL of the service the client connects to.</param>
        public ServiceConnection(string baseUrl)
        {
            _lock           = new object();
            _client         = new ChessServiceClient(baseUrl);
            _runningMethods = new ConcurrentHashSet <string>();
            _mechanism      = new ChessMechanism();

            _players    = new List <Player>();
            _matches    = new List <ChessGameDetails>();
            CurrentGame = null;

            InitTokenRefreshTimer();
            InitStateRefreshTimer();
        }
Example #17
0
        public void GameStateCheck_KingVsKing_Draw()
        {
            var expected = GameState.Draw;

            // Draw
            var game = new ChessRepresentation()
            {
                History = new List <BaseMove>(),
                ["C5"]  = new King(ChessPlayer.White, true),
                ["F4"]  = new King(ChessPlayer.Black, true)
            };
            var mechanism = new ChessMechanism();

            var actual = mechanism.GetGameState(game);

            Assert.Equal(expected, actual);
        }
Example #18
0
        public void GameStateCheck_KingBishopVsKingBishopDifferentColour_InProgress()
        {
            var expected = GameState.InProgress;

            // Draw
            var game = new ChessRepresentation()
            {
                History = new List <BaseMove>(),
                ["C5"]  = new King(ChessPlayer.White, true),
                ["F4"]  = new King(ChessPlayer.Black, true),
                ["C8"]  = new Bishop(ChessPlayer.White, true),
                ["G1"]  = new Bishop(ChessPlayer.Black, true),
            };
            var mechanism = new ChessMechanism();

            var actual = mechanism.GetGameState(game);

            Assert.Equal(expected, actual);
        }
Example #19
0
        private async void listboxMatches_SelectedIndexChanged(object sender, EventArgs e)
        {
            var match     = (DecoratedMatch)listboxMatches.SelectedItem;
            var mechanism = new ChessMechanism();
            var board     = new ChessRepresentationInitializer().Create();

            if (match == null)
            {
                return;
            }

            labelStatus.Text = $"Getting details of selected match... ({match.Name})";
            var details = await _client.GetMatchAsync(_jwtToken, match.Id.ToString());

            listboxGameHistory.Items.Clear();

            if (details?.Representation?.History == null)
            {
                MessageBox.Show("Couldn't get details of selected match. (Maybe unauthorized?)");
                labelStatus.Text = "Error while getting details of match";
                return;
            }

            listboxGameHistory.Items.Add(new ChessRepresentationStage()
            {
                AfterMove           = null,
                ChessRepresentation = board
            });

            foreach (var move in details.Representation.History)
            {
                board = mechanism.ApplyMove(board, move);

                var item = new ChessRepresentationStage
                {
                    AfterMove           = move,
                    ChessRepresentation = board
                };

                listboxGameHistory.Items.Add(item);
            }
        }
Example #20
0
        public void GenerateMovesTest_CastlingsReturned_BlackSide()
        {
            var expected = 2;

            var board = new ChessRepresentation()
            {
                CurrentPlayer = ChessPlayer.Black,
            };

            board[Positions.E8] = new King(ChessPlayer.Black, false);
            board[Positions.A8] = new Rook(ChessPlayer.Black, false);
            board[Positions.H8] = new Rook(ChessPlayer.Black, false);
            board[Positions.E1] = new King(ChessPlayer.White, false);

            var game   = new ChessMechanism();
            var moves  = game.GenerateMoves(board).OfType <KingCastlingMove>();
            var result = moves.Count();

            Assert.Equal(expected, result);
        }
Example #21
0
        public void GameStateCheck_StaleMateTest_Draw()
        {
            var expected = GameState.Draw;

            //Stalemate
            var game      = new ChessRepresentationInitializer().Create();
            var mechanism = new ChessMechanism();
            var moves     = new List <BaseMove>(19)
            {
                new ChessMove(ChessPlayer.White, Positions.E2, Positions.E3),
                new ChessMove(ChessPlayer.Black, Positions.A7, Positions.A5),
                new ChessMove(ChessPlayer.White, Positions.D1, Positions.H5),
                new ChessMove(ChessPlayer.Black, Positions.A8, Positions.A6),
                new ChessMove(ChessPlayer.White, Positions.H5, Positions.A5),
                new ChessMove(ChessPlayer.Black, Positions.H7, Positions.H5),
                new ChessMove(ChessPlayer.White, Positions.H2, Positions.H4),
                new ChessMove(ChessPlayer.Black, Positions.A6, Positions.H6),
                new ChessMove(ChessPlayer.White, Positions.A5, Positions.C7),
                new ChessMove(ChessPlayer.Black, Positions.F7, Positions.F6),
                new ChessMove(ChessPlayer.White, Positions.C7, Positions.D7),
                new ChessMove(ChessPlayer.Black, Positions.E8, Positions.F7),
                new ChessMove(ChessPlayer.White, Positions.D7, Positions.B7),
                new ChessMove(ChessPlayer.Black, Positions.D8, Positions.D3),
                new ChessMove(ChessPlayer.White, Positions.B7, Positions.B8),
                new ChessMove(ChessPlayer.Black, Positions.D3, Positions.H7),
                new ChessMove(ChessPlayer.White, Positions.B8, Positions.C8),
                new ChessMove(ChessPlayer.Black, Positions.F7, Positions.G6),
                new ChessMove(ChessPlayer.White, Positions.C8, Positions.E6)
            };

            foreach (var move in moves)
            {
                game = mechanism.ApplyMove(game, move);
            }

            var actual = mechanism.GetGameState(game);

            Assert.Equal(expected, actual);
        }
Example #22
0
        public MainForm()
        {
            InitializeComponent();
            tabPageGame.Tag    = Tabs.GamePage;
            tabPageMatches.Tag = Tabs.MatchesPage;
            tabPagePlayers.Tag = Tabs.PlayersPage;
            tabPageLog.Tag     = Tabs.LogPage;
            _mechanism         = new ChessMechanism();

            _client = new ServiceConnection(_baseUrl);
            _client.PollFinished    += ClientOnPollFinished;
            _client.PollStarted     += ClientOnPollStarted;
            _client.BackgroundError += ClientOnBackgroundError;

            comboboxAlgorithms.Items.Add(new AlgorithmItem("Minimax", typeof(MinimaxAlgorithm <ChessRepresentation, BaseMove>)));
            comboboxAlgorithms.Items.Add(new AlgorithmItem("Minimax Average", typeof(MinimaxAverageAlgorithm <ChessRepresentation, BaseMove>)));
            comboboxAlgorithms.Items.Add(new AlgorithmItem("Alpha Beta", typeof(AlphaBetaAlgorithm <ChessRepresentation, BaseMove>)));
            comboboxAlgorithms.Items.Add(new AlgorithmItem("Greedy", typeof(GreedyAlgorithm <ChessRepresentation, BaseMove>)));
            comboboxAlgorithms.Items.Add(new AlgorithmItem("Random", typeof(RandomAlgorithm <ChessRepresentation, BaseMove>)));

            comboboxEvaluators.Items.Add(new EvaluatorItem("Version 1", typeof(Version1Evaluator)));
            comboboxEvaluators.Items.Add(new EvaluatorItem("Version 2", typeof(Version1Evaluator)));

            comboboxAlgorithms.SelectedIndex = 0;
            comboboxEvaluators.SelectedIndex = 0;

            textboxLog.SelectionFont    = new Font(FontFamily.GenericMonospace, 8.25f);
            textboxBotLog.SelectionFont = new Font(FontFamily.GenericMonospace, 8.25f);

            textboxReadme.Rtf = BotClientResources.BotClientDoc;

#if DEBUG
            textboxUsername.Text = "*****@*****.**";
            textboxPassword.Text = "*****@*****.**";
#else
            textboxUsername.Text = string.Empty;
            textboxPassword.Text = string.Empty;
#endif
        }
Example #23
0
        static void Main(string[] args)
        {
            var board = new ChessRepresentationInitializer().Create();

            board.CurrentPlayer = ChessPlayer.White;

            var manager = new ChessMechanism();

            var step1 = new ChessMove(ChessPlayer.White, (Position)"B2", (Position)"B4");
            var step2 = new ChessMove(ChessPlayer.Black, (Position)"E7", (Position)"E5");
            var step3 = new ChessMove(ChessPlayer.White, (Position)"B4", (Position)"B5");
            var step4 = new ChessMove(ChessPlayer.Black, (Position)"B8", (Position)"C6");
            var step5 = new ChessMove(ChessPlayer.White, (Position)"B5", (Position)"C6");

            board = manager.ApplyMove(board, step1);
            board = manager.ApplyMove(board, step2);
            board = manager.ApplyMove(board, step3);
            board = manager.ApplyMove(board, step4);
            board = manager.ApplyMove(board, step5);

            Tools.ChessboardVisualizer.ChessboardVisualizer.TestShowVisualizer(board);
        }
Example #24
0
        public void GameStateCheck_CheckMateTest_BlackWins()
        {
            var expected = GameState.BlackWon;

            // Fool's mate
            var game      = new ChessRepresentationInitializer().Create();
            var mechanism = new ChessMechanism();
            var moves     = new List <BaseMove>(4)
            {
                new ChessMove(ChessPlayer.White, Positions.G2, Positions.G4),
                new ChessMove(ChessPlayer.Black, Positions.E7, Positions.E5),
                new ChessMove(ChessPlayer.White, Positions.F2, Positions.F3),
                new ChessMove(ChessPlayer.Black, Positions.D8, Positions.H4)
            };

            foreach (var move in moves)
            {
                game = mechanism.ApplyMove(game, move);
            }

            var actual = mechanism.GetGameState(game);

            Assert.Equal(expected, actual);
        }
Example #25
0
 public Version1Evaluator(ChessMechanism mechanism)
 {
     _mechanism = mechanism;
 }
        /// <inheritdoc />
        public ChessGameMoveResult Move <T>(string participantPlayerName, Guid chessGameId, T move) where T : BaseMove
        {
            var match = GetMainQuery(participantPlayerName)
                        .Include(x => x.History)
                        .FirstOrDefault(x => x.Id == chessGameId);

            if (match is null)
            {
                return(new ChessGameMoveResult
                {
                    NewState = null,
                    MoveRequestResultStatus = ChessGameMoveRequestResultStatuses.NoMatchFound
                });
            }

            var players = match.GetPlayerNames();

            var oldChessGameDetails = _chessGameConverter.ConvertToChessGameDetails(match);

            var game          = oldChessGameDetails.Representation;
            var gameMechanism = new ChessMechanism();

            // Game has already ended, not accepting any more moves!
            if (gameMechanism.GetGameState(game) != GameState.InProgress)
            {
                return(new ChessGameMoveResult
                {
                    MoveRequestResultStatus = ChessGameMoveRequestResultStatuses.GameHasAlreadyEnded,
                    NewState = null
                });
            }

            // Checking if the current player tries to move.
            var currentPlayerName = players[game.CurrentPlayer];

            if (currentPlayerName != participantPlayerName)
            {
                return(new ChessGameMoveResult
                {
                    MoveRequestResultStatus = ChessGameMoveRequestResultStatuses.WrongTurn,
                    NewState = null
                });
            }

            // Validating move...
            if (!gameMechanism.ValidateMove(game, move))
            {
                var previousState = new ChessGameDetails
                {
                    BlackPlayer    = oldChessGameDetails.BlackPlayer,
                    ChallengeDate  = oldChessGameDetails.ChallengeDate,
                    Id             = oldChessGameDetails.Id,
                    InitiatedBy    = oldChessGameDetails.InitiatedBy,
                    LastMoveDate   = oldChessGameDetails.LastMoveDate,
                    Name           = oldChessGameDetails.Name,
                    Opponent       = oldChessGameDetails.Opponent,
                    WhitePlayer    = oldChessGameDetails.WhitePlayer,
                    Representation = game
                };

                return(new ChessGameMoveResult
                {
                    MoveRequestResultStatus = ChessGameMoveRequestResultStatuses.InvalidMove,
                    NewState = previousState
                });
            }

            // Everything seems fine, applying and returning...
            var newState        = gameMechanism.ApplyMove(game, move);
            var newStateOutcome = gameMechanism.GetGameState(newState);

            var result = new ChessGameDetails()
            {
                BlackPlayer    = oldChessGameDetails.BlackPlayer,
                ChallengeDate  = oldChessGameDetails.ChallengeDate,
                Id             = oldChessGameDetails.Id,
                InitiatedBy    = oldChessGameDetails.InitiatedBy,
                LastMoveDate   = DateTime.UtcNow,
                Name           = oldChessGameDetails.Name,
                Opponent       = oldChessGameDetails.Opponent,
                WhitePlayer    = oldChessGameDetails.WhitePlayer,
                Representation = newState
            };

            var newDbMove = _chessGameConverter.CovertToDbChessMove(move);
            var dbGame    = _dbContext.ChessGames.Find(match.Id);

            dbGame.Status = newStateOutcome;
            dbGame.History.Add(newDbMove);
            _dbContext.SaveChanges();

            return(new ChessGameMoveResult
            {
                MoveRequestResultStatus = ChessGameMoveRequestResultStatuses.Ok,
                NewState = result
            });
        }
Example #27
0
 public ChessBoardGamePanel()
 {
     DoubleBuffered = true;
     _mechanism     = new ChessMechanism();
 }
Example #28
0
 public Evaluator(ChessMechanism mechanism)
 {
     _mechanism = mechanism;
 }
Example #29
0
        public MainForm()
        {
            game = new ChessRepresentationInitializer().Create();

            _mechanism = new ChessMechanism(true);
            _evaluator = new Evaluator(_mechanism);
            _generator = new MoveGenerator(_mechanism);
            _applier   = new MoveApplier(_mechanism);

            taskRight = new Task(() =>
            {
                do
                {
                    if (!_isActive || _mechanism.GetGameState(game) != GameState.InProgress)
                    {
                        InvokeIfRequired(progressbarBotActiveRight, () =>
                        {
                            progressbarBotActiveRight.MarqueeAnimationSpeed = 0;
                        });

                        // Not doing anything, checking in every second...
                        Thread.Sleep(1000);
                        continue;
                    }

                    InvokeIfRequired(progressbarBotActiveRight, () =>
                    {
                        if (progressbarBotActiveRight.MarqueeAnimationSpeed != 10)
                        {
                            progressbarBotActiveRight.MarqueeAnimationSpeed = 10;
                        }
                    });

                    DoRobotWork(ChessPlayer.White);

                    Thread.Sleep(1000);
                } while (true);
            });

            taskLeft = new Task(() =>
            {
                do
                {
                    if (!_isActive || _mechanism.GetGameState(game) != GameState.InProgress)
                    {
                        InvokeIfRequired(progressbarBotActiveLeft, () =>
                        {
                            progressbarBotActiveLeft.MarqueeAnimationSpeed = 0;
                        });

                        // Not doing anything, checking in every second...
                        Thread.Sleep(1000);
                        continue;
                    }

                    InvokeIfRequired(progressbarBotActiveLeft, () =>
                    {
                        if (progressbarBotActiveLeft.MarqueeAnimationSpeed != 10)
                        {
                            progressbarBotActiveLeft.MarqueeAnimationSpeed = 10;
                        }
                    });

                    DoRobotWork(ChessPlayer.Black);

                    Thread.Sleep(1000);
                } while (true);
            });

            InitializeComponent();

            listboxAlgorithmsRight.Items.Add(Algorithms.Minimax);
            listboxAlgorithmsRight.Items.Add(Algorithms.MinimaxAverage);
            listboxAlgorithmsRight.Items.Add(Algorithms.AlphaBeta);
            listboxAlgorithmsRight.Items.Add(Algorithms.Greedy);
            listboxAlgorithmsRight.Items.Add(Algorithms.Random);
            listboxAlgorithmsRight.SelectedIndex = Randomizer.Next(0, listboxAlgorithmsRight.Items.Count - 1);

            listboxAlgorithmsLeft.Items.Add(Algorithms.Minimax);
            listboxAlgorithmsLeft.Items.Add(Algorithms.MinimaxAverage);
            listboxAlgorithmsLeft.Items.Add(Algorithms.AlphaBeta);
            listboxAlgorithmsLeft.Items.Add(Algorithms.Greedy);
            listboxAlgorithmsLeft.Items.Add(Algorithms.Random);
            listboxAlgorithmsLeft.SelectedIndex = Randomizer.Next(0, listboxAlgorithmsLeft.Items.Count - 1);

            chessBoardVisualizerPanel1.ChessRepresentation = game;
            chessBoardVisualizerPanel1.Refresh();

            taskLeft.Start();
            taskRight.Start();
        }
Example #30
0
 public MoveApplier(ChessMechanism mechanism)
 {
     _mechanism = mechanism;
 }