/// <summary>
        /// Applies a move for the current player at the given position.
        /// </summary>
        public async Task ApplyMove(ChessMove cmove)
        {
            var possMoves = mBoard.GetPossibleMoves() as IEnumerable <ChessMove>;

            // Validate the move as possible.
            if (possMoves.Contains(cmove))
            {
                mBoard.ApplyMove(cmove);
            }
            RebindState();
            if (Players == NumberOfPlayers.One && !mBoard.IsFinished && this.CurrentPlayer == 2)
            {
                this.canundo = false;
                var bestMove = Task.Run(() => { return(mGameAi.FindBestMove(mBoard)); });
                var temp     = await bestMove;
                this.canundo = true;
                if (bestMove != null)
                {
                    mBoard.ApplyMove(temp as ChessMove);
                }
            }
            RebindState();
            if (mBoard.IsFinished)
            {
                GameFinished?.Invoke(this, new EventArgs());
            }
        }
        public async Task ApplyMove(ChessMove move)
        {
            var possMoves = mBoard.GetPossibleMoves() as IEnumerable <ChessMove>;

            foreach (var m in possMoves)
            {
                if (m.StartPosition.Equals(move.StartPosition) && m.EndPosition.Equals(move.EndPosition))
                {
                    mBoard.ApplyMove(m);
                    //MessageBox.Show("Weight: " + mBoard.Weight.ToString());
                    break;
                }
            }

            RebindState();

            if (Players == NumberOfPlayers.One && CurrentPlayer == 2 && !mBoard.IsFinished)
            {
                var bestMove = await Task.Run(() => mGameAi.FindBestMove(mBoard));

                if (bestMove != null)
                {
                    mBoard.ApplyMove(bestMove);
                    RebindState();
                }
            }

            if (mBoard.IsCheckmate || mBoard.IsStalemate)
            {
                GameFinished?.Invoke(this, new EventArgs());
            }
        }
Beispiel #3
0
        internal void ApplyMove(BoardPosition start_position, BoardPosition end_position)
        {
            var possMoves = mChessBoard.GetPossibleMoves() as IEnumerable <ChessMove>;

            // Validate the move as possible.
            foreach (var move in possMoves)
            {
                if (move.EndPosition.Equals(end_position) && move.StartPosition.Equals(start_position))
                {
                    if (move.MoveType == ChessMoveType.PawnPromote)
                    {
                        //open new window
                        //in new window return chesspieceType
                        //apply in the new window and break
                        var pawnPromotionSelect = new ChessPromotionView(this, start_position, end_position);
                        pawnPromotionSelect.Show();
                        break;
                    }
                    else
                    {
                        mChessBoard.ApplyMove(move);

                        break;
                    }
                }
            }

            RebindState();
            if (mChessBoard.IsFinished)
            {
                GameFinished?.Invoke(this, new EventArgs());
            }
        }
Beispiel #4
0
        public async Task ApplyMove(BoardPosition startPos, BoardPosition endPos, ChessPieceType pieceType)
        {
            var possMove = mBoard.GetPossibleMoves().Where(m => startPos == m.StartPosition && endPos == m.EndPosition);

            if (possMove.Count() == 1)
            {
                mBoard.ApplyMove(mBoard.GetPossibleMoves().Where(m => startPos == m.StartPosition && endPos == m.EndPosition).Single());
            }
            else//PROMOTION
            {
                mBoard.ApplyMove(mBoard.GetPossibleMoves().Where(m => startPos == m.StartPosition && endPos == m.EndPosition && pieceType == m.PromoteType).Single());
            }


            if (Players == NumberOfPlayers.One && !mBoard.IsFinished)
            {
                var bestMove     = Task.Run(() => mGameAi.FindBestMove(mBoard));
                var waitBestMove = await bestMove;
                if (waitBestMove != null)
                {
                    mBoard.ApplyMove(waitBestMove as ChessMove);
                }
            }
            RebindState();

            if (mBoard.IsFinished)
            {
                GameFinished?.Invoke(this, new EventArgs());
            }
        }
        /// <summary>
        /// Applies a move for the current player at the given position.
        /// </summary>
        public async Task ApplyMove(BoardPosition start, BoardPosition end, ChessPieceType cpt)
        {
            foreach (var move in mBoard.GetPossibleMoves())
            {
                if (move.StartPosition.Equals(start) & move.EndPosition.Equals(end))
                {
                    if(move.PromotionPiece != ChessPieceType.Empty & move.PromotionPiece == cpt | move.PromotionPiece == ChessPieceType.Empty)
                    {
                        mBoard.ApplyMove(move);
                        break;
                    }
                }
            }

            if (Players == NumberOfPlayers.One && !mBoard.IsFinished)
            {
                var bestMove = await Task.Run(() => mGameAi.FindBestMove(mBoard));
                if (bestMove != null)
                {
                    mBoard.ApplyMove(bestMove as ChessMove);
                }
            }

            RebindState();

            if (mBoard.IsFinished)
                GameFinished?.Invoke(this, new EventArgs());
        }
        public void PawnPromotionWhite()
        {
            ChessBoard b = CreateBoardWithPositions(
                Pos("a7"), ChessPieceType.Pawn, 1,
                Pos("b7"), ChessPieceType.Queen, 2,
                Pos("e8"), ChessPieceType.Queen, 1,
                Pos("f5"), ChessPieceType.Pawn, 1,
                Pos("f6"), ChessPieceType.Pawn, 2,
                Pos("g4"), ChessPieceType.Pawn, 1,
                Pos("g7"), ChessPieceType.Pawn, 2,
                Pos("h4"), ChessPieceType.Pawn, 1,
                Pos("h5"), ChessPieceType.King, 1,
                Pos("h6"), ChessPieceType.Pawn, 2,
                Pos("h7"), ChessPieceType.King, 2
                );

            var possMoves     = b.GetPossibleMoves() as IEnumerable <ChessMove>;
            var expectedMoves = GetMovesAtPosition(possMoves, Pos("a7"));

            expectedMoves.Should().HaveCount(1, "There should only be one move.")
            .And.Contain(Move("a7", "a8"), "The only possible mve is a7 to a8.");

            b.CurrentPlayer.Should().Be(1, "Current player should be White.");

            b.ApplyMove(Move("a7", "a8"));

            var piece = b.GetPieceAtPosition(Pos("a8"));

            piece.PieceType.Should().Be(ChessPieceType.Pawn, "Should be a pawn still.");

            b.CurrentPlayer.Should().Be(1, "Current player should still be White.");

            possMoves     = b.GetPossibleMoves() as IEnumerable <ChessMove>;
            expectedMoves = GetMovesAtPosition(possMoves, Pos("a8"));
            expectedMoves.Should().HaveCount(4, "There should be four moves.")
            .And.OnlyContain(m => ((ChessMove)m).MoveType == ChessMoveType.PawnPromote);

            b.ApplyMove(Move("(a8, Bishop)"));             // Apply pawn promotion.

            piece = b.GetPieceAtPosition(Pos("a8"));

            piece.PieceType.Should().Be(ChessPieceType.Bishop, "Should be a bishop now.");

            b.CurrentPlayer.Should().Be(2, "Current player should be Black.");

            b.UndoLastMove();

            b.CurrentPlayer.Should().Be(1, "Current player should be White.");

            piece = b.GetPieceAtPosition(Pos("a8"));

            piece.PieceType.Should().Be(ChessPieceType.Pawn, "Should be a pawn now.");

            possMoves     = b.GetPossibleMoves() as IEnumerable <ChessMove>;
            expectedMoves = GetMovesAtPosition(possMoves, Pos("a8"));
            expectedMoves.Should().HaveCount(4, "There should be four moves.")
            .And.OnlyContain(m => ((ChessMove)m).MoveType == ChessMoveType.PawnPromote);
        }
        /// <summary>
        /// Applies a move for the current player at the given position.
        /// </summary>
        public async Task ApplyMove(BoardPosition position)
        {
            var possMoves = mBoard.GetPossibleMoves() as IEnumerable <ChessMove>;

            // Validate the move as possible.
            foreach (var move in possMoves)
            {
                if (SelectedSquare.Position.Equals(move.StartPosition) && move.EndPosition.Equals(position))
                {
                    if (move.MoveType == ChessMoveType.PawnPromote)
                    {
                        var window = new PawnPromotionWindow(this, move.StartPosition, move.EndPosition);
                        window.ShowDialog();
                        Promote = window.promotePicked;
                        ChessMove m = new ChessMove(move.StartPosition, move.EndPosition, ChessMove.StringToPromoType(Promote), ChessMoveType.PawnPromote);
                        mBoard.ApplyMove(m);
                        foreach (var s in mSquares)
                        {
                            s.KingInCheck = false;
                        }
                        SelectedState = false;
                        break;
                    }

                    else
                    {
                        mBoard.ApplyMove(move);
                        foreach (var s in mSquares)
                        {
                            s.KingInCheck = false;
                        }
                        SelectedState = false;
                        break;
                    }
                }
            }
            RebindState();

            if (Players == NumberOfPlayers.One && !mBoard.IsFinished)
            {
                var bestMove = await Task.Run(() => mGameAi.FindBestMove(mBoard));

                if (bestMove != null)
                {
                    mBoard.ApplyMove(bestMove as ChessMove);
                }
            }

            RebindState();

            if (mBoard.IsFinished)
            {
                GameFinished?.Invoke(this, new EventArgs());
            }
            //Show Boardweight in a message box when a move is applied
            //MessageBox.Show("Board Weight: " + mBoard.BoardWeight);
        }
Beispiel #8
0
        public async Task ApplyMove(ChessMove cMove)
        {
            if (mBoard.IsCheckmate)
            {
                GameFinished?.Invoke(this, new EventArgs());
            }
            else
            {
                if (cMove.MoveType == ChessMoveType.PawnPromote)
                {
                    IsPawnPromotion = true;
                }

                if (IsPawnPromotion)
                {
                    mBoard.ApplyMove(cMove);
                    IsPawnPromotion = false;
                    RebindState();
                }

                //Need to account for pawn promotion
                var possMoves = mBoard.GetPossibleMoves() as IEnumerable <ChessMove>;
                foreach (var move in possMoves)
                {
                    if (move.Equals(cMove))
                    {
                        mBoard.ApplyMove(move);
                        break;
                    }
                }

                RebindState();
                //CheckPromotionMoves();

                if (Players == NumberOfPlayers.One && !mBoard.IsFinished && mBoard.CurrentPlayer == 2)
                {
                    var bestMove = await Task.Run(() => mGameAi.FindBestMove(mBoard));

                    if (bestMove != null)
                    {
                        mBoard.ApplyMove(bestMove);
                        RebindState();
                    }
                }

                CheckPromotionMoves();
            }
        }
Beispiel #9
0
        public void KingCheckBlack()
        {
            ChessBoard b = CreateBoardWithPositions(
                Pos("c2"), ChessPieceType.RookQueen, 1,
                Pos("c6"), ChessPieceType.King, 2,
                Pos("e1"), ChessPieceType.King, 1,
                Pos("g2"), ChessPieceType.Pawn, 1
                );

            b.ApplyMove(Move("g2", "g3")); // This is to make sure player is now Black (to switch players from White to Black).

            b.CurrentPlayer.Should().Be(2, "Current player should be Black.");

            var possMoves = b.GetPossibleMoves();

            possMoves.Count().Should().Be(6, "There should only be six moves available.");

            possMoves.Should().Contain(Move("c6", "b7"), "Should contain C6 to B7.")
            .And.Contain(Move("c6", "d7"), "Should contain C6 to D7.")
            .And.Contain(Move("c6", "b6"), "Should contain C6 to B6.")
            .And.Contain(Move("c6", "d6"), "Should contain C6 to D6.")
            .And.Contain(Move("c6", "d5"), "Should contain C6 to B5.")
            .And.Contain(Move("c6", "d5"), "Should contain C6 to D5.");

            b.IsCheck.Should().Be(true, "Black's king should be checked.");
            b.IsCheckmate.Should().Be(false, "Should NOT be checkmate.");
            b.IsStalemate.Should().Be(false, "Not a stalemate.");
        }
Beispiel #10
0
        public void EasyPeasyAttackWhite()
        {
            ChessBoard b = CreateBoardFromMoves(new ChessMove[]
            {
                Move("d2", "d4"),
                Move("e7", "e5"),
            });

            var possMoves = b.GetPossibleMoves();

            possMoves.Should().Contain(Move("d4", "e5"), "Move from d4 to e5 should exist.");

            var blackPawn = b.GetPieceAtPosition(Pos("e5"));

            blackPawn.PieceType.Should().Be(ChessPieceType.Pawn, "This spot should contain a pawn.");
            blackPawn.Player.Should().Be(2, "This piece should be Black's.");

            b.ApplyMove(Move("d4", "e5")); // Attack the pawn (White's doing).

            var oldLocation = b.GetPieceAtPosition(Pos("d4"));

            oldLocation.PieceType.Should().Be(ChessPieceType.Empty, "This spot should now be empty.");

            var newLocation = b.GetPieceAtPosition(Pos("e5"));

            newLocation.PieceType.Should().Be(ChessPieceType.Pawn, "This spot should now contain a pawn.");
            newLocation.Player.Should().Be(1, "This piece should be White's.");
        }
Beispiel #11
0
        public void CheckMateWhite()
        {
            ChessBoard b = CreateBoardFromMoves(new ChessMove[]
            {
                Move("e2", "e4"),
                Move("e7", "e5"),
                Move("f1", "c4"),
                Move("b8", "c6"),
                Move("d1", "h5"),
                Move("d7", "d6")
            });

            b.CurrentPlayer.Should().Be(1, "Current player should be White.");

            b.ApplyMove(Move("h5", "f7"));             // Checkmate (White's doing)!

            b.CurrentPlayer.Should().Be(2, "Current player should be Black.");

            var possMoves = b.GetPossibleMoves();

            possMoves.Count().Should().Be(0);             // There should be no available moves!

            b.IsCheck.Should().Be(false, "Should not be checked since it's already checkmate.");
            b.IsCheckmate.Should().Be(true, "Should be checkmate.");
            b.IsStalemate.Should().Be(false, "Not a stalemate");
        }
Beispiel #12
0
        /// <summary>
        /// Applies a move for the current player at the given position
        /// </summary>
        /// <param name="position"> The position the piece is moved to</param>
        public async Task ApplyMove(BoardPosition position)
        {
            var possMoves = mBoard.GetPossibleMoves() as IEnumerable <ChessMove>;

            //Make sure the move is valid
            foreach (var move in possMoves)
            {
                if ((move.StartPosition.Equals(StartBoardPosition)) && (move.EndPosition.Equals(position)))
                {
                    if (!PromotedPiece.Equals(ChessPieceType.Empty))
                    {
                        if (move.PromoteTo == PromotedPiece)
                        {
                            mBoard.ApplyMove(move);
                            break;
                        }
                    }
                    else
                    {
                        mBoard.ApplyMove(move);
                        break;
                    }
                }
            }

            RebindState();

            if (Players == NumberOfPlayers.One && !mBoard.IsFinished)
            {
                var bestMoveTask = Task.Run(() => mGameAi.FindBestMove(mBoard));

                var bestMove = await bestMoveTask;

                if (bestMove != null)
                {
                    mBoard.ApplyMove(bestMove as ChessMove);
                }
                RebindState();
            }
            //MessageBox.Show(mBoard.BoardWeight.ToString());

            if (mBoard.IsFinished)
            {
                GameFinished?.Invoke(this, new EventArgs());
            }
        }
Beispiel #13
0
        public void ApplyMove(ChessMove position)
        {
            mBoard.ApplyMove(position);

            PossibleMoves = new HashSet <ChessMove>(
                from ChessMove m in mBoard.GetPossibleMoves()
                select m
                );
            var newSquares =
                from r in Enumerable.Range(0, 8)
                from c in Enumerable.Range(0, 8)
                select new BoardPosition(r, c);
            int  i    = 0;
            bool look = false;

            if (mBoard.IsCheck || mBoard.IsCheckmate)
            {
                look = true;
            }

            foreach (var pos in newSquares)
            {
                mSquares[i].Player = mBoard.GetPieceAtPosition(pos).Player;
                mSquares[i].Piece  = mBoard.GetPieceAtPosition(pos).ToString();
                if ((mBoard.IsCheck || mBoard.IsCheckmate) && mBoard.GetPieceAtPosition(pos).PieceType == ChessPieceType.King && mBoard.GetPieceAtPosition(pos).Player == CurrentPlayer)
                {
                    mSquares[i].IsChecked = true;
                }
                else
                {
                    mSquares[i].IsChecked = false;
                }

                i++;
            }

            if (mBoard.IsCheckmate || mBoard.IsStalemate)
            {
                GameFinished?.Invoke(this, new EventArgs());
            }

            OnPropertyChanged(nameof(BoardValue));
            OnPropertyChanged(nameof(CurrentPlayer));
            OnPropertyChanged(nameof(CanUndo));
        }
Beispiel #14
0
        public void KnightCapturesAQueen()
        {
            ChessBoard b = new ChessBoard();

            b.ApplyMove(Move("d2", "d4"));
            b.ApplyMove(Move("e7", "e5"));
            b.ApplyMove(Move("b1", "c3"));
            b.ApplyMove(Move("d7", "d5"));
            b.ApplyMove(Move("d5", "d4"));
            b.ApplyMove(Move("c3", "e4"));
            b.ApplyMove(Move("d8", "d5"));
            b.ApplyMove(Move("e4", "c3"));
            b.ApplyMove(Move("d5", "e4"));
            //KNight eats the queen
            b.ApplyMove(Move("c3", "e4"));
            b.GetPieceAtPosition(Pos("c3")).PieceType.Should().Be(ChessPieceType.Empty, "The peice is no longer there its empty was eaten");
            b.GetPieceAtPosition(Pos("e4")).PieceType.Should().Be(ChessPieceType.Knight, "The new occupied space is a knight");
        }
Beispiel #15
0
        /// <summary>
        /// Applies a move for the current player at the given position.
        /// </summary>
        public void ApplyMove(BoardPosition position)
        {
            var possMoves = mBoard.GetPossibleMoves() as IEnumerable <ChessMove>;

            // Validate the move as possible.
            foreach (var move in possMoves)
            {
                if (SelectedSquare.Position.Equals(move.StartPosition) && move.EndPosition.Equals(position))
                {
                    if (move.MoveType == ChessMoveType.PawnPromote)
                    {
                        var window = new PawnPromotionWindow(this, move.StartPosition, move.EndPosition);
                        window.ShowDialog();
                        Promote = window.promotePicked;
                        ChessMove m = new ChessMove(move.StartPosition, move.EndPosition, ChessMove.StringToPromoType(Promote), ChessMoveType.PawnPromote);
                        mBoard.ApplyMove(m);
                        foreach (var s in mSquares)
                        {
                            s.KingInCheck = false;
                        }
                        SelectedState = false;
                        break;
                    }

                    else
                    {
                        mBoard.ApplyMove(move);
                        foreach (var s in mSquares)
                        {
                            s.KingInCheck = false;
                        }
                        SelectedState = false;
                        break;
                    }
                }
            }

            RebindState();

            if (mBoard.IsFinished)
            {
                GameFinished?.Invoke(this, new EventArgs());
            }
        }
Beispiel #16
0
        public async Task ApplyMove(ChessMove userMove)
        {
            Debug.WriteLine("Weight Before Move: " + mBoard.Weight);
            var possMoves = mBoard.GetPossibleMoves() as IEnumerable <ChessMove>;

            foreach (var move in possMoves)
            {
                if (move.Equals(userMove))
                {
                    mBoard.ApplyMove(move);
                    break;
                }
            }
            RebindState();
            Debug.WriteLine("White weight:" + mBoard.Weight);
            if (Players == NumberOfPlayers.One && !mBoard.IsFinished)
            {
                var bestMove = await Task.Run(() => mGameAi.FindBestMove(mBoard));

                Debug.WriteLine("AI Turn");
                if (bestMove != null)
                {
                    mBoard.ApplyMove(bestMove);
                    if (mBoard.CurrentPlayer == 2) // If the current player did not change, we are doing pawn promotion...
                    {
                        bestMove = await Task.Run(() => mGameAi.FindBestMove(mBoard));

                        if (bestMove != null)
                        {
                            mBoard.ApplyMove(bestMove);
                        }
                    }
                    RebindState();
                    Debug.WriteLine("Black weight:" + mBoard.Weight);
                }
            }

            if (mBoard.IsStalemate || mBoard.IsCheckmate)
            {
                GameFinished?.Invoke(this, new EventArgs());
            }
        }
        public void CastlingAndEnPassantBlack()          //Tricky moves2:En passant & castling for black side with king side rook and undoes it.
        {
            ChessBoard c = CreateBoardFromMoves(new ChessMove[]
            {
                Move("b2", "b4"),
                Move("f7", "f5"),
                Move("b4", "b5"),
                Move("f5", "f4"),
                Move("a2", "a3"),
                Move("e7", "e5"),
                Move("h2", "h4"),
                Move("f8", "a3")
            });

            c.Value.Should().Be(-1, "White pawn was captured.");
            c.ApplyMove(Move("b1", "a3"));
            c.Value.Should().Be(2, "Black bishop was captured.");
            c.ApplyMove(Move("g8", "h6"));
            c.ApplyMove(Move("a3", "c4"));
            ApplyMove(c, Move("e8", "g8"));
            var king = c.GetPieceAtPosition(Pos("g8"));

            king.PieceType.Should().Be(ChessPieceType.King, "King has applied castling with king side rook.");
            var rook = c.GetPieceAtPosition(Pos("f8"));

            rook.PieceType.Should().Be(ChessPieceType.RookKing, "King side Rook has applied castling with king.");
            c.UndoLastMove();
            c.GetPieceAtPosition(Pos("e8")).PieceType.Should().Be(ChessPieceType.King, "King returns to original position after undo");
            c.GetPieceAtPosition(Pos("h8")).PieceType.Should().Be(ChessPieceType.RookKing, "Rook returns to original position after undo");
            ChessBoard b = CreateBoardFromMoves(new ChessMove[] {
                Move("g2", "g4"),
                Move("a7", "a5"),
                Move("g4", "g5"),
                Move("a5", "a4"),
                Move("b2", "b4"),
            });
            var poss      = b.GetPossibleMoves() as IEnumerable <ChessMove>;
            var enpassant = GetMovesAtPosition(poss, Pos("a4"));

            enpassant.Should().Contain(Move("a4", "b3"), "Enemy pawn moved 2 spaces and fits criteria for en passant").And.HaveCount(2, "Two available moves for pawn: forward and en passant");
        }
Beispiel #18
0
        public void CheckKing()
        {
            ChessBoard b = new ChessBoard();

            b.ApplyMove(Move("b2", "b4"));
            b.ApplyMove(Move("b7", "b5"));
            b.ApplyMove(Move("d2", "d4"));
            b.ApplyMove(Move("b8", "a6"));
            b.ApplyMove(Move("e2", "e4"));
            b.ApplyMove(Move("b5", "a4"));
            b.ApplyMove(Move("d1", "h5"));
            b.ApplyMove(Move("c7", "c5"));
            //Black King is in Check
            //can only be saved by checking the queen
            b.ApplyMove(Move("h5", "f7"));
            b.GetPossibleMoves().Should().Contain(Move("e8", "f7")).And.HaveCount(1, "Must take quen for check");
        }
        internal async Task ApplyMoveAsync(BoardPosition start_position, BoardPosition end_position)
        {
            var possMoves = mChessBoard.GetPossibleMoves() as IEnumerable <ChessMove>;

            // Validate the move as possible.
            foreach (var move in possMoves)
            {
                if (move.EndPosition.Equals(end_position) && move.StartPosition.Equals(start_position))
                {
                    if (move.MoveType == ChessMoveType.PawnPromote)
                    {
                        //open new window
                        //in new window return chesspieceType
                        //apply in the new window and break
                        var pawnPromotionSelect = new ChessPromotionView(this, start_position, end_position);
                        pawnPromotionSelect.Show();
                        break;
                    }
                    else
                    {
                        mChessBoard.ApplyMove(move);
                        break;
                    }
                }
            }
            RebindState();
            if (Players == NumberOfPlayers.One && !mChessBoard.IsFinished)
            {
                var bestMove = await Task.Run(() => mGameAi.FindBestMove(mChessBoard));

                if (bestMove != null)
                {
                    mChessBoard.ApplyMove(bestMove as ChessMove);
                }
            }
            RebindState();
            if (mChessBoard.IsFinished)
            {
                GameFinished?.Invoke(this, new EventArgs());
            }
        }
Beispiel #20
0
        /// <summary>
        /// Applies a move for the current player at the given position.
        /// </summary>
        async public Task ApplyMove(ChessMove move) => await Task.Run(() =>
        {
            mBoard.ApplyMove(move);
            RebindState();

            if (Players == NumberOfPlayers.One && !mBoard.IsFinished)
            {
                var bestMove = mGameAi.FindBestMove(mBoard);

                if (bestMove != null)
                {
                    mBoard.ApplyMove(bestMove as ChessMove);
                    RebindState();
                }
            }

            if (mBoard.IsFinished)
            {
                GameFinished?.Invoke(this, new EventArgs());
            }
        });
Beispiel #21
0
        public void DavidVanBuster()
        {
            ChessBoard b = new ChessBoard();

            Action act;

            act = () => b.GetPossibleMoves();
            act.ShouldNotThrow("No exceptions should be thrown for GetPossibleMoves()");

            act = () => b.GetThreatenedPositions(1);
            act.ShouldNotThrow("No exceptions should be thrown for GetThreatenedPositions()");

            act = () => b.GetPositionsOfPiece(ChessPieceType.Pawn, 1);
            act.ShouldNotThrow("No exceptions should be thrown for GetPositionsOfPiece()");

            act = () => b.GetPlayerAtPosition(Pos("a1"));
            act.ShouldNotThrow("No exceptions should be thrown for GetPlayerAtPosition()");

            act = () => b.GetPieceAtPosition(Pos("a1"));
            act.ShouldNotThrow("No exceptions should be thrown for GetPieceAtPosition()");

            act = () => b.GetPieceValue(ChessPieceType.Pawn);
            act.ShouldNotThrow("No exceptions should be thrown for GetPieceValue()");

            act = () => b.ApplyMove(Move("a2", "a3"));
            act.ShouldNotThrow("No exceptions should be thrown for ApplyMove()");

            act = () => b.UndoLastMove();
            act.ShouldNotThrow("No exceptions should be thrown for UndoLastMove()");

            act = () => b.PositionIsEmpty(Pos("a1"));
            act.ShouldNotThrow("No exceptions should be thrown for PositionIsEmpty()");

            act = () => b.PositionIsEnemy(Pos("a1"), 2);
            act.ShouldNotThrow("No exceptions should be thrown for PositionIsEnemy()");

            act = () => b.UndoLastMove();
            act.ShouldThrow <Exception>("No moves to undo!");

            b = new ChessBoard();

            var possMoves = b.GetPossibleMoves();

            possMoves.Should().NotBeNullOrEmpty("No empty moves or nulls allowed in initial state.")
            .And.OnlyHaveUniqueItems("Should not contain duplicate moves.");

            var threatened1 = b.GetThreatenedPositions(1);
            var threatened2 = b.GetThreatenedPositions(2);

            threatened1.Should().NotContain(threatened2, "Player 1's threatened positions should not contain Player 2's threatened positions.");
            threatened2.Should().NotContain(threatened1, "Player 2's threatened positions should not contain Player 1's threatened positions.");
        }
Beispiel #22
0
        /// <summary>
        /// Applies a move for the current player at the given position.
        /// </summary>
        public async Task ApplyMove(BoardPosition startPosition, BoardPosition endPosition, ChessPieceType type)
        {
            var       possMoves = mBoard.GetPossibleMoves() as IEnumerable <ChessMove>;
            ChessMove promoMove;

            // Validate the move as possible.

            foreach (var move in possMoves)
            {
                if (move.StartPosition.Equals(startPosition) && move.EndPosition.Equals(endPosition) && mBoard.GetPieceAtPosition(startPosition).PieceType == type)
                {
                    mBoard.ApplyMove(move);
                    break;
                }
                else if (move.StartPosition.Equals(startPosition) && move.EndPosition.Equals(endPosition) && mBoard.GetPieceAtPosition(startPosition).PieceType != type)
                {
                    promoMove = new ChessMove(startPosition, endPosition, type, ChessMoveType.PawnPromote);
                    mBoard.ApplyMove(promoMove);
                    break;
                }
            }

            if (Players == NumberOfPlayers.One && !mBoard.IsFinished)
            {
                var bestMove = await Task.Run(() => mGameAi.FindBestMove(mBoard));

                if (bestMove != null)
                {
                    mBoard.ApplyMove(bestMove as ChessMove);
                }
            }

            RebindState();

            if (mBoard.IsFinished)
            {
                GameFinished?.Invoke(this, new EventArgs());
            }
        }
        public void EnPassantUndo()
        {
            ChessBoard b = new ChessBoard();

            b.ApplyMove(Move(Pos("a2"), Pos("a4")));
            b.UndoLastMove();
            var possMoves         = b.GetPossibleMoves();
            var enPassantExpected = GetMovesAtPosition(possMoves, Pos("a2"));

            enPassantExpected.Should().HaveCount(2, "pawn can move forward one or en passant even if you undo enpassant once")
            .And.Contain(Move("a2, a3"))
            .And.Contain(Move(Pos("a2"), Pos("a4"), ChessMoveType.EnPassant));
        }
Beispiel #24
0
        public async Task ApplyMove(ChessMove chessMove)
        {
            //add ai pawn promotion
            //if(LastMove.MoveType == ChessMoveType.PawnPromote)


            var possMoves = mBoard.GetPossibleMoves() as IEnumerable <ChessMove>;

            foreach (var move in possMoves)
            {
                if (move.Equals(chessMove))
                {
                    mBoard.ApplyMove(move);
                    LastMove = chessMove;
                    if (!mBoard.IsCheck)
                    {
                        kingSquare.IsCheck = false;
                    }
                    break;
                }
            }
            RebindState();
            if (Players == NumberOfPlayers.One && !mBoard.IsFinished)
            {
                var bestMove = await Task.Run(() => mGameAi.FindBestMove(mBoard));

                if (bestMove != null)
                {
                    mBoard.ApplyMove(bestMove);
                    RebindState();
                }
            }

            if (mBoard.IsCheckmate || mBoard.IsStalemate)
            {
                GameFinished?.Invoke(this, new EventArgs());
            }
        }
        static void Main(string[] args)
        {
            ChessBoard b         = new ChessBoard();
            IGameAi    ai        = new MinimaxAi(3);
            int        MAX_MOVES = 6;
            Stopwatch  watch     = new Stopwatch();

            watch.Start();
            for (int i = 0; i < MAX_MOVES; i++)
            {
                var move = ai.FindBestMove(b);
                b.ApplyMove(move as ChessMove);
            }
            watch.Stop();
            Console.WriteLine($"{watch.ElapsedMilliseconds} ms total");
        }
Beispiel #26
0
        /// <summary>
        /// Applies the given move to the given board.
        /// </summary>
        private static void ApplyMove(ChessBoard board, ChessMove move)
        {
            int currentValue = board.Value;
            var possMoves    = board.GetPossibleMoves();

            board.Value.Should().Be(currentValue, "the board's value should not change after calling GetPossibleMoves");
            var toApply = possMoves.FirstOrDefault(m => m.Equals(move));

            if (toApply == null)
            {
                throw new InvalidOperationException("Could not apply the move " + move);
            }
            else
            {
                board.ApplyMove(toApply);
            }
        }
Beispiel #27
0
        public void ForceKingMovesWhenInCheck()          //Force player to move piece to save the King
        {
            ChessBoard b = CreateBoardWithPositions(
                Pos("e8"), ChessPieceType.King, 2,
                Pos("f7"), ChessPieceType.RookKing, 2,
                Pos("h6"), ChessPieceType.Bishop, 1,
                Pos("f2"), ChessPieceType.RookKing, 1,
                Pos("f1"), ChessPieceType.Queen, 1,
                Pos("d2"), ChessPieceType.RookKing, 1,
                Pos("a1"), ChessPieceType.King, 1
                );

            b.ApplyMove(Move("f1", "e1"));
            var poss = b.GetPossibleMoves() as IEnumerable <ChessMove>;

            poss.Should().Contain(Move("f7", "e7")).And.HaveCount(1, "Rook must move to block the queen from taking the king");
        }
Beispiel #28
0
        public void FullPawnCapturePawnUndo()
        {
            //Make a board with only pawns
            ChessBoard b = new ChessBoard();

            b.ApplyMove(Move("a2", "a4"));
            b.ApplyMove(Move("b7", "b5"));
            //White Captured 1
            b.ApplyMove(Move("a4", "b5"));

            b.ApplyMove(Move("d7", "d5"));
            b.ApplyMove(Move("c2", "c4"));
            //Black Capurted 1
            b.ApplyMove(Move("d5", "c4"));
            b.ApplyMove(Move("b5", "b6"));
            b.ApplyMove(Move("c4", "c3"));

            //Move The horsey
            b.ApplyMove(Move("b1", "c3"));

            b.UndoLastMove();
            b.GetPieceAtPosition(Pos("b1")).PieceType.Should().Be(ChessPieceType.Knight, "Last Move knight capture pwn was undone");
        }
Beispiel #29
0
        public void KingInCheckPossMoves()
        {
            ChessBoard b = CreateBoardWithPositions(
                Pos("e8"), ChessPieceType.King, 2,
                Pos("a4"), ChessPieceType.Bishop, 1,
                Pos("e1"), ChessPieceType.RookKing, 1);

            b.GetThreatenedPositions(1).Should().Contain(new BoardPosition(0, 4), "King should be in threatened list");
            b.ApplyMove(Move("e1", "e2"));

            b.GetPossibleMoves().Count().Should().Be(3, "Only 3 possible moves for king in this position");
            b.GetPossibleMoves().Should().Contain(Move("e8", "d8")).And
            .NotContain(Move("e2", "f3"), "King should have this possible move in this position.");
            b.GetPossibleMoves().Should().Contain(Move("e8", "f8")).And
            .NotContain(Move("e2", "f3"), "King should have this possible move in this position.");
            b.GetPossibleMoves().Should().Contain(Move("e8", "f7")).And
            .NotContain(Move("e2", "f3"), "King should have this possible move in this position.");
        }
Beispiel #30
0
        public void PawnsPossibleMovesBlack() // (ID + 1) % 6 = 1 => Test Pawns
        {
            ChessBoard b = new ChessBoard();

            b.ApplyMove(Move("a2", "a3")); // Make sure we switch to player 2 (Black).
            var  pawnsPosition = b.GetPositionsOfPiece(ChessPieceType.Pawn, 2);
            char c             = 'a';      // Set up for later.
            bool movePawnsNow  = false;

            foreach (BoardPosition pawns in pawnsPosition)
            {
                var pawn = b.GetPieceAtPosition(pawns);
                pawn.PieceType.Should().Be(ChessPieceType.Pawn, "This should be a pawn.");
                pawn.Player.Should().Be(2, "This should be Black's pawn.");
                var possMoves     = b.GetPossibleMoves() as IEnumerable <ChessMove>;
                var expectedMoves = GetMovesAtPosition(possMoves, pawns);
                c.Should().BeLessThan('i', "var c should not have gone past letter h. Check pawnPositions (including its size/contents).");
                expectedMoves.Should().HaveCount(2, "There should only be two moves in the initial state")
                .And.Contain(Move(c + "7", c + "6"), "First move should be one space ahead")
                .And.Contain(Move(c + "7", c + "5"), "Second move should be two spaces ahead.");
                b.ApplyMove(Move(c + "7", c + "6")); // Move Black's pawn forward one spot.
                if (movePawnsNow)
                {
                    b.ApplyMove(Move(c + "2", c + "3"));                     // Dummy move to change player.
                }
                else
                {
                    b.ApplyMove(Move(c + "1", c + "2"));                     // Dummy move to change player.
                    movePawnsNow = true;
                }
                var newPossMoves     = b.GetPossibleMoves() as IEnumerable <ChessMove>;
                var newExpectedMoves = GetMovesAtPosition(newPossMoves, Pos(c + "6"));
                newExpectedMoves.Should().HaveCount(1, "There should only be one move...")
                .And.Contain(Move(c + "6", c + "5"), "Move an only go forward one spot.");
                b.UndoLastMove();                    // Undo dummy move.
                b.UndoLastMove();                    // Undo pawn move.
                b.ApplyMove(Move(c + "7", c + "5")); // Move Black's pawn forward two spots now.
                b.ApplyMove(Move(c + "2", c + "3")); // Dummy move to change player.
                newPossMoves     = b.GetPossibleMoves() as IEnumerable <ChessMove>;
                newExpectedMoves = GetMovesAtPosition(newPossMoves, Pos(c + "5"));
                newExpectedMoves.Should().HaveCount(1, "There should only be one move...")
                .And.Contain(Move(c + "5", c + "4"), "Move an only go forward one spot.");
                b.UndoLastMove(); // Undo dummy move.
                b.UndoLastMove(); // Undo pawn move.
                c++;              // Go on to the next letter...
            }
        }