Ejemplo n.º 1
0
        public object Put()
        {
            var chessBoard = new ChessBoard();
            (new TraditionalBoardStager()).Stage(chessBoard);

            var chessGame = new ChessGame(
                chessBoard,
                PlayerTypeEnum.White,
                new Dictionary<PlayerTypeEnum, List<ChessPiece>>());

            var id = Guid.NewGuid();
            m_chessGameRepo.Put(id, chessGame);

            return new
            {
                _id = id,
                _turn = ((char)chessGame.PlayerTurn),
                _taken = new
                {
                    w = chessGame.GetTakenPiecesByPlayer(PlayerTypeEnum.White).Select(x => (char)x.Type),
                    b = chessGame.GetTakenPiecesByPlayer(PlayerTypeEnum.Black).Select(x => (char)x.Type),
                },
                _state = chessBoard.GetBoardAsListOfString(),
                _history = chessGame.GetMoves(),
                _moves = new PotentialMoveService().GetPotentialMoves(chessGame, chessGame.PlayerTurn),
            };
        }
Ejemplo n.º 2
0
        public void King_Two_Move_No_Rook()
        {
            ChessBoard b = new ChessBoard();
            b.Set("e1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.King });

            b.Set("e8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.King });

            ChessGame g = new ChessGame(b, PlayerTypeEnum.White, null);
            var move = g.PlayerMove(PlayerTypeEnum.White, "e1g1");

            Assert.IsFalse(move.Success);
        }
Ejemplo n.º 3
0
        public void PawnSwap()
        {
            ChessBoard b = new ChessBoard();
            b.Set("e1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.King });
            b.Set("f7", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });

            b.Set("e8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.King });

            ChessGame g = new ChessGame(b, PlayerTypeEnum.White, null);
            var moveResult = g.PlayerMove(PlayerTypeEnum.White, "f7f8");
            ChessPiece queen = b.Get("f8");

            Assert.IsTrue(moveResult.Success);
            Assert.IsTrue(queen.Type == PieceTypeEnum.Queen);
        }
Ejemplo n.º 4
0
        private bool CanMoveIntoAttackersPath(PlayerTypeEnum player, string lastMoveNotation, ChessBoard board, List<string> attackers, Tuple<int, int> opponentKingTuple)
        {
            if (attackers.Count > 1)
                return false;

            bool canBlockPathOfAttackers = false;

            string attackerNotation = attackers.First();
            Tuple<int, int> attackerTuple = NotationHelper.Translate(attackerNotation);
            ChessPiece attackerPiece = board.Get(attackerTuple);

            if (attackerPiece.Type == PieceTypeEnum.Knight)
                return false;

            // get star pattern of each attacker
            List<Tuple<int, int>[]> relativePaths = new QueenRelativePathProvider().GetRelativePaths(
                new ChessPiece() { Player = player });

            var absolutePaths = BoardLogic.ConvertToAbsolutePaths(attackerTuple, relativePaths);

            // get path that leads to king
            var pathOfAttacker = BoardLogic.GetPathContaining(opponentKingTuple, absolutePaths);
            var trimmedPathOfAttacker = BoardLogic.TrimToBeforeDestination(opponentKingTuple, pathOfAttacker);

            // can any opponents move into path and block?
            var opponentPlayerSquares = board.GetPiecesForPlayer(GetOppositePlayer(player));
            foreach (var opponentSquare in opponentPlayerSquares)
            {
                bool canMoveIntoAttackersPath =
                    trimmedPathOfAttacker.Any(location =>
                    {
                        string dest = NotationHelper.Translate(location);
                        return CanMove(board, opponentSquare + dest, GetOppositePlayer(player), lastMoveNotation).Success;
                    });

                if (canMoveIntoAttackersPath)
                {
                    canBlockPathOfAttackers = true;
                    break;
                }
            }

            return canBlockPathOfAttackers;
        }
Ejemplo n.º 5
0
        public void PotentialMoves()
        {
            ChessBoard b = new ChessBoard();
            b.Set("e1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.King });
            b.Set("f7", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });

            b.Set("e8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.King });

            ChessGame g = new ChessGame(b, PlayerTypeEnum.White, null);

            PotentialMoveService s = new PotentialMoveService();
            s.GetPotentialMoves(g, PlayerTypeEnum.White);
            var whiteMoves = s.GetPotentialMoves(g, PlayerTypeEnum.White);
            var blackMoves = s.GetPotentialMoves(g, PlayerTypeEnum.Black);

            Assert.AreEqual(5, whiteMoves["e1"].Count);
            Assert.AreEqual(2, whiteMoves["f7"].Count);

            Assert.AreEqual(5, blackMoves["e8"].Count);
        }
Ejemplo n.º 6
0
        public ChessGame(
            ChessBoard b,
            PlayerTypeEnum player,
            Dictionary<PlayerTypeEnum,
            List<ChessPiece>> takenPieces,
            IRulesOfChess rules)
        {
            _chessBoard = b;
            _currentPlayer = player;
            _moves = new List<string>();
            _takenPieces = takenPieces ?? new Dictionary<PlayerTypeEnum, List<ChessPiece>>();

            List<ChessPiece> takenOut;
            if (!_takenPieces.TryGetValue(PlayerTypeEnum.White, out takenOut) || takenOut == null)
                _takenPieces[PlayerTypeEnum.White] = new List<ChessPiece>();

            if (!_takenPieces.TryGetValue(PlayerTypeEnum.Black, out takenOut) || takenOut == null)
                _takenPieces[PlayerTypeEnum.Black] = new List<ChessPiece>();

            _rules = rules;
        }
Ejemplo n.º 7
0
        private ValidateMoveResult CanMove(ChessBoard board, string source, string dest, PlayerTypeEnum player, string lastMoveNotation, bool playerInCheck)
        {
            var result = new ValidateMoveResult();

            var sourceTuple = NotationHelper.Translate(source);

            if (!BoardLogic.IsOnBoard(sourceTuple))
                return result.SetMessage(source + " is not on board");

            var destTuple = NotationHelper.Translate(dest);

            if (!BoardLogic.IsOnBoard(destTuple))
                return result.SetMessage(dest + " is not on board");

            if (source.Equals(dest, StringComparison.OrdinalIgnoreCase))
                return result.SetMessage("source and dest are the same");

            var sourcePiece = board.Get(sourceTuple);

            if (sourcePiece == null)
                return result.SetMessage("source piece is null");

            if (sourcePiece.Player != player)
                return result.SetMessage("piece does not belong to player.");

            var destPiece = board.Get(destTuple);

            if (destPiece != null && sourcePiece.Player == destPiece.Player)
                return result.SetMessage("cannot move on top of own piece");

            var relativeMoves = m_relativeMoveProviderFactory
                .GetProviderByPieceType(sourcePiece.Type)
                .GetRelativePaths(sourcePiece);
            var absoluteMoves = BoardLogic.ConvertToAbsolutePaths(sourceTuple, relativeMoves);
            bool destInPath = BoardLogic.IsInAtleastOnePath(destTuple, absoluteMoves);

            if (!destInPath)
                return result.SetMessage("destination not in available path");

            string takenPiece = null;
            string additionalMove = null;

            switch (sourcePiece.Type)
            {
                case PieceTypeEnum.Pawn:
                    {
                        bool isRankOnlyMove = BoardLogic.IsRankOnlyMove(sourceTuple, destTuple);

                        if (isRankOnlyMove)
                        {
                            var pathContaingDestination = BoardLogic.GetPathContaining(destTuple, absoluteMoves);

                            if (!BoardLogic.IsPathClear(board, pathContaingDestination))
                                return result.SetMessage("path blocked");

                            var absDelta = BoardLogic.GetAbsoluteDelta(sourceTuple, destTuple);
                            if (absDelta.Item1 == 2 && sourcePiece.HasMoved)
                                return result.SetMessage("pawn has already moved, cannot jump 2 squares");
                        }
                        else
                        {
                            // en-passant
                            // > is piece in source *rank, destination *file an enemy pawn?
                            // > if yes, was its last move two squares?e
                            var pieceBehindTuple = new Tuple<int, int>(
                                sourceTuple.Item1,
                                destTuple.Item2);

                            var pieceBehind = board.Get(pieceBehindTuple);
                            bool targetWasLastMove = false;
                            bool twoSquareLastMove = false;

                            Tuple<string, string> lastMove = null;
                            if (lastMoveNotation != null)
                            {
                                lastMove = NotationHelper.Breakdown(lastMoveNotation);
                                var lastMoveSourceTuple = NotationHelper.Translate(lastMove.Item1);
                                var lastMoveDestTuple = NotationHelper.Translate(lastMove.Item2);
                                var lastMoveAbsDelta = BoardLogic.GetAbsoluteDelta(lastMoveSourceTuple, lastMoveDestTuple);

                                twoSquareLastMove = lastMoveAbsDelta.Item1 == 2;

                                targetWasLastMove =
                                    pieceBehindTuple.Item1 == lastMoveDestTuple.Item1 &&
                                    pieceBehindTuple.Item2 == lastMoveDestTuple.Item2;
                            }

                            bool enPassant =
                                pieceBehind != null &&
                                pieceBehind.Player != player &&
                                pieceBehind.Type == PieceTypeEnum.Pawn &&
                                twoSquareLastMove &&
                                targetWasLastMove
                                ;

                            if (enPassant)
                            {
                                takenPiece = lastMove.Item2;
                                break;
                            }

                            if (destPiece == null)
                                return result.SetMessage("enemy piece not present at destination");
                        }

                        break;
                    }
                case PieceTypeEnum.King:
                    {
                        // castle

                        if (BoardLogic.IsFileOnlyMove(sourceTuple, destTuple) &&
                            BoardLogic.GetAbsoluteDelta(sourceTuple, destTuple).Item2 == 2)
                        {
                            if (sourcePiece.HasMoved)
                                return result.SetMessage("king has already moved.");

                            ChessPiece rook = null;
                            Tuple<int, int> rookTuple = null;
                            Tuple<int, int> toRookDelta = null;
                            var rookNotations = board.GetPiecesOfType(player, PieceTypeEnum.Rook);
                            if (rookNotations != null && rookNotations.Count > 0)
                            {
                                var moveDelta = BoardLogic.GetDelta(sourceTuple, destTuple);

                                foreach (var rn in rookNotations)
                                {
                                    rookTuple = NotationHelper.Translate(rn);
                                    toRookDelta = BoardLogic.GetDelta(sourceTuple, rookTuple);
                                    if (BoardLogic.IsFileOnlyMove(sourceTuple, rookTuple) &&
                                        BoardLogic.AreDeltasInSameDirection(moveDelta.Item2, toRookDelta.Item2))
                                    {
                                        rook = board.Get(rn);
                                        break;
                                    }
                                }
                            }

                            if (rook == null)
                                return result.SetMessage("no rook present on rank " + sourceTuple.Item1);

                            if (rook.HasMoved)
                                return result.SetMessage("rook has moved.");

                            Tuple<int, int>[] kingToRookPath = BoardLogic.GetRankPath(sourceTuple, rookTuple);
                            Tuple<int, int>[] trimmedPath = BoardLogic.TrimToBeforeDestination(rookTuple,
                                kingToRookPath);

                            bool isPathClear = BoardLogic.IsPathClear(board, trimmedPath);

                            if (!isPathClear)
                                return result.SetMessage("path blocked");

                            if (playerInCheck)
                                return result.SetMessage("cannot castle out of check");

                            bool moveToLeft = toRookDelta.Item2 < 0;
                            additionalMove = NotationHelper.Translate(rookTuple) +
                                                NotationHelper.Translate(new Tuple<int, int>(rookTuple.Item1,
                                                    destTuple.Item2 + (moveToLeft ? 1 : -1)));
                        }

                        break;
                    }
                case PieceTypeEnum.Knight:
                    {
                        break;
                    }
                case PieceTypeEnum.Bishop:
                case PieceTypeEnum.Rook:
                case PieceTypeEnum.Queen:
                    {
                        // cases handled in general

                        var pathContaingDestination = BoardLogic.GetPathContaining(destTuple, absoluteMoves);
                        var trimmedPath = BoardLogic.TrimToBeforeDestination(destTuple, pathContaingDestination);

                        if (!BoardLogic.IsPathClear(board, trimmedPath))
                            return result.SetMessage("path blocked");

                        break;
                    }
            }

            if (destPiece != null)
                takenPiece = dest;

            result.Success = true;
            result.TakenPiece = takenPiece;
            result.Moves = new[] { source + dest, additionalMove }.Where(x => x != null).ToArray();
            return result;
        }
Ejemplo n.º 8
0
        private Tuple<bool, List<string>> IsInCheck(PlayerTypeEnum playerType, ChessBoard board, string lastMoveNotation)
        {
            PlayerTypeEnum opponentPlayerType = GetOppositePlayer(playerType);
            List<string> opponentSquares = board.GetPiecesForPlayer(opponentPlayerType);
            string kingNotation = board.GetKing(playerType);

            if (kingNotation == null)
                return new Tuple<bool, List<string>>(false, null);

            bool isInCheck = false;
            List<string> attackers = new List<string>();
            foreach (var square in opponentSquares)
            {
                var opponentMoveResult = CanMove(board, square, kingNotation, opponentPlayerType, lastMoveNotation, false);
                if (opponentMoveResult.Success)
                {
                    isInCheck = true;
                    attackers.Add(square);
                }
            }

            return new Tuple<bool, List<string>>(isInCheck, attackers);
        }
Ejemplo n.º 9
0
        public ValidateMoveResult CanMove(ChessBoard board, string move, PlayerTypeEnum player,
            string lastMoveNotation)
        {
            Tuple<string, string> breakdown = NotationHelper.Breakdown(move);
            string source = breakdown.Item1;
            string destination = breakdown.Item2;

            bool playerInCheck = IsInCheck(player, board, lastMoveNotation).Item1;
            ValidateMoveResult canMoveResult = CanMove(board, source, destination, player, lastMoveNotation, playerInCheck);

            if (canMoveResult.Success)
            {
                // pawn to queen swap
                ChessPiece sourceBeforeSimulate = board.Get(source);
                bool pawnSwap =
                    sourceBeforeSimulate != null &&
                    sourceBeforeSimulate.Type == PieceTypeEnum.Pawn &&
                    (sourceBeforeSimulate.Direction == -1 ? (int.Parse(destination[1].ToString()) == 8) : (int.Parse(destination[1].ToString()) == 1));

                string swap = pawnSwap ? destination : null;
                canMoveResult.Swap = swap;

                ChessBoard boardAfterMove = board.SimulateMoves(move, canMoveResult.TakenPiece, swap);

                // did player move into check?
                var movedIntoCheckResult = IsInCheck(player, boardAfterMove, lastMoveNotation);
                if (movedIntoCheckResult.Item1)
                {
                    canMoveResult.Success = false;
                    return canMoveResult.SetMessage("cannot move into check.");
                }

                // did player put opponent in check?
                var isOpponentInCheckResult = IsInCheck(GetOppositePlayer(player), boardAfterMove, lastMoveNotation);
                bool isOpponentInCheck = isOpponentInCheckResult.Item1;
                canMoveResult.MoveType = isOpponentInCheck ? MoveTypeEnum.Check : MoveTypeEnum.Normal;

                // if player checked opponent, can opponent get out of check? if not, check mate
                if (isOpponentInCheck)
                {
                    string opponentKingNotation = boardAfterMove.GetKing(GetOppositePlayer(player));
                    Tuple<int, int> opponentKingTuple = NotationHelper.Translate(opponentKingNotation);

                    // can checked king move out of check?
                    bool canMoveOutOfCheck = CanMoveOutOfCheck(player, lastMoveNotation, boardAfterMove, opponentKingNotation, opponentKingTuple);

                    // can opponent kill piece that put king in check? is still in check afterwards?
                    bool canTakedownAttacker = false;
                    if (!canMoveOutOfCheck)
                        canTakedownAttacker = CanTakedownAttackers(player, lastMoveNotation, boardAfterMove, isOpponentInCheckResult.Item2);

                    // can block path of piece that put king in check? (brute force method)
                    bool canBlockPathOfAttackers = false;
                    if (!canMoveOutOfCheck && !canTakedownAttacker)
                        canBlockPathOfAttackers = CanMoveIntoAttackersPath(player, lastMoveNotation, boardAfterMove, isOpponentInCheckResult.Item2, opponentKingTuple);

                    if (!canMoveOutOfCheck && !canTakedownAttacker && !canBlockPathOfAttackers)
                        canMoveResult.MoveType = MoveTypeEnum.Checkmate;
                }
            }

            return canMoveResult;
        }
Ejemplo n.º 10
0
        private bool CanMoveOutOfCheck(PlayerTypeEnum player, string lastMoveNotation, ChessBoard board, string opponentKingNotation, Tuple<int, int> opponentKingTuple)
        {
            bool canMoveOutOfCheck = false;
            ChessPiece opponentKingPiece = board.Get(opponentKingTuple);
            var relativeMoves = m_relativeMoveProviderFactory
                .GetProviderByPieceType(opponentKingPiece.Type)
                .GetRelativePaths(opponentKingPiece);

            var absolutePaths = BoardLogic.ConvertToAbsolutePaths(opponentKingTuple, relativeMoves);

            var flattenedAbsoluteMoves = absolutePaths.SelectMany(x => x);
            foreach (var square in flattenedAbsoluteMoves)
            {
                // simulate move of king to available move
                string destinationNotation = NotationHelper.Translate(square);
                var getKingOutOfCheckMoveResult = CanMove(board, opponentKingNotation + destinationNotation,
                    GetOppositePlayer(player), lastMoveNotation);

                if (getKingOutOfCheckMoveResult.Success)
                {
                    canMoveOutOfCheck = true;
                    break;
                }
            }

            return canMoveOutOfCheck;
        }
Ejemplo n.º 11
0
        private bool CanTakedownAttackers(PlayerTypeEnum player, string lastMoveNotation, ChessBoard board, List<string> attackers)
        {
            if (attackers.Count > 1)
                return false;

            bool canTakedownAttacker = false;
            PlayerTypeEnum opponentPlayerType = GetOppositePlayer(player);
            List<string> opponentSquares = board.GetPiecesForPlayer(opponentPlayerType);
            string attackerNotation = attackers.First();

            foreach (var square in opponentSquares)
            {
                bool canDefeatAllAttackers = CanMove(board, square + attackerNotation, opponentPlayerType, lastMoveNotation).Success;
                if (canDefeatAllAttackers)
                {
                    canTakedownAttacker = true;
                    break;
                }
            }

            return canTakedownAttacker;
        }
Ejemplo n.º 12
0
        public void Cannot_Move_Into_Check()
        {
            ChessBoard b = new ChessBoard();
            b.Set("e1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.King });

            b.Set("e8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.King });
            b.Set("h2", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Queen });

            ChessGame g = new ChessGame(b, PlayerTypeEnum.White, null);
            var moveResult = g.PlayerMove(PlayerTypeEnum.White, "e1e2");

            Assert.IsFalse(moveResult.Success);
        }
Ejemplo n.º 13
0
        static void RandomIntoCheck()
        {
            Random r = new Random(Guid.NewGuid().GetHashCode());

            ChessBoard chessBoard = new ChessBoard();
            (new TraditionalBoardStager()).Stage(chessBoard);

            PlayerTypeEnum currentPlayer = PlayerTypeEnum.White;
            ChessGame chessGame = new ChessGame(
                chessBoard,
                currentPlayer,
                new Dictionary<PlayerTypeEnum, List<ChessPiece>>());

            bool isCheckmate = false;
            while (true)
            {
                int movesWithoutSuccess = 0;

                while (true)
                {
                    List<string> notation = chessBoard.GetPiecesForPlayer(currentPlayer);
                    List<string> opponentNotation =
                        chessBoard.GetPiecesForPlayer(currentPlayer == PlayerTypeEnum.White
                            ? PlayerTypeEnum.Black
                            : PlayerTypeEnum.White);

                    if ((notation.Count == 1 && opponentNotation.Count == 1) || movesWithoutSuccess > 5000)
                    {
                        //Console.WriteLine("{0} on {1}, moves w/o success: {2}", notation.Count, notation.Count, movesWithoutSuccess);

                        chessBoard = new ChessBoard();
                        (new TraditionalBoardStager()).Stage(chessBoard);

                        currentPlayer = PlayerTypeEnum.White;
                        chessGame = new ChessGame(
                            chessBoard,
                            currentPlayer,
                            new Dictionary<PlayerTypeEnum, List<ChessPiece>>());
                    }

                    int randomPieceIndex = r.Next(0, notation.Count);
                    string randomSource = notation.ElementAt(randomPieceIndex);

                    int randomRank = r.Next(0, 8);
                    int randomFile = r.Next(0, 8);

                    string randomDestination = NotationHelper.Translate(randomRank, randomFile);
                    var move = chessGame.PlayerMove(currentPlayer, randomSource + randomDestination);

                    if (move.Success)
                    {
                        movesWithoutSuccess = 0;

                        if (move.MoveType == MoveTypeEnum.Checkmate)
                        {
                            (new ConsoleBoardPrinter()).PrintBoard(chessBoard.CreateStateCopy(), currentPlayer);
                            Console.WriteLine("Check: {0}, Moves: {1}", Enum.GetName(typeof(MoveTypeEnum), move.MoveType), string.Join(", ", move.Moves));
                        }

                        currentPlayer = move.Turn;

                        if (move.MoveType == MoveTypeEnum.Checkmate)
                        {
                            isCheckmate = true;
                        }

                        break;
                    }

                    ++movesWithoutSuccess;
                }

                if (isCheckmate)
                {
                    break;
                }
            }
        }
Ejemplo n.º 14
0
        public void Castle_Block()
        {
            ChessBoard b = new ChessBoard();
            b.Set("e1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.King });
            b.Set("a1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Rook });
            b.Set("b1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Knight });

            ChessGame g = new ChessGame(b, PlayerTypeEnum.White, null);
            var moveResult = g.PlayerMove(PlayerTypeEnum.White, "e1c1");

            Assert.IsFalse(moveResult.Success);
        }
Ejemplo n.º 15
0
        public void Overtake()
        {
            ChessBoard b = new ChessBoard();
            b.Set("g4", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("h5", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });

            TraditionalRulesOfChess rules = new TraditionalRulesOfChess();

            ChessGame chessGame = new ChessGame(
                b,
                PlayerTypeEnum.White,
                null);

            var move = chessGame.PlayerMove(PlayerTypeEnum.White, "g4h5");

            Assert.IsTrue(move.Success, move.Error);
            Assert.IsNotNull(move.Taken);
            Assert.AreEqual(chessGame.GetTakenPiecesByPlayer(PlayerTypeEnum.White).Length, 1);
            Assert.AreEqual(chessGame.GetTakenPiecesByPlayer(PlayerTypeEnum.White)[0].Player, PlayerTypeEnum.Black);
        }
Ejemplo n.º 16
0
        public void Checkmate()
        {
            ChessBoard b = new ChessBoard();
            b.Set("e1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.King });

            b.Set("e8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.King });
            b.Set("h2", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Queen });
            b.Set("g2", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Rook });

            ChessGame g = new ChessGame(b, PlayerTypeEnum.Black, null);
            var moveResult = g.PlayerMove(PlayerTypeEnum.Black, "h2h1");

            Assert.IsTrue(moveResult.Success);
            Assert.IsTrue(moveResult.MoveType == MoveTypeEnum.Checkmate, "expected checkmate");
        }
Ejemplo n.º 17
0
        public void Pawn()
        {
            ChessBoard b = new ChessBoard();

            b.Set("a2", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("a7", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("e7", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });
            b.Set("g4", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("h5", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });

            TraditionalRulesOfChess rules = new TraditionalRulesOfChess();

            // basic move

            var move = rules.CanMove(b, "a2a3", PlayerTypeEnum.White, null);
            Assert.IsTrue(move.Success, move.Message);

            // move two squares on first move

            move = rules.CanMove(b, "a2a4", PlayerTypeEnum.White, null);
            Assert.IsTrue(move.Success, move.Message);

            // can't move two squares on subsequent moves

            move = rules.CanMove(b, "a2a5", PlayerTypeEnum.White, null);
            Assert.IsFalse(move.Success, move.Message);

            // can't move backwards

            move = rules.CanMove(b, "a2a1", PlayerTypeEnum.White, null);
            Assert.IsFalse(move.Success, move.Message);

            // piece does not exist

            move = rules.CanMove(b, "h2g3", PlayerTypeEnum.White, null);
            Assert.IsFalse(move.Success, move.Message);

            // g4 pawn over-take h5 pawn

            move = rules.CanMove(b, "g4h5", PlayerTypeEnum.White, null);
            Assert.IsTrue(move.Success, move.Message);

            b.RecordMoves(new[] { "a2a3" }, null, null);

            move = rules.CanMove(b, "a3a5", PlayerTypeEnum.White, null);
            Assert.IsFalse(move.Success, move.Message);

            move = rules.CanMove(b, "a3a4", PlayerTypeEnum.White, null);
            Assert.IsTrue(move.Success, move.Message);

            move = rules.CanMove(b, "a7a8", PlayerTypeEnum.White, null);
            Assert.IsTrue(move.Success, move.Message);

            move = rules.CanMove(b, "e7e6", PlayerTypeEnum.Black, null);
            Assert.IsTrue(move.Success, move.Message);

            move = rules.CanMove(b, "e7e8", PlayerTypeEnum.Black, null);
            Assert.IsFalse(move.Success, move.Message);
        }
Ejemplo n.º 18
0
        public void EnPassant()
        {
            ChessBoard b = new ChessBoard();
            (new EnPassantTestingBoardStager()).Stage(b);

            var rules = new TraditionalRulesOfChess();
            var moveResult = rules.CanMove(
                b, "a2a4", PlayerTypeEnum.White, null);

            Assert.IsTrue(moveResult.Success);

            b.RecordMoves(new[] { "a2a4" }, null, null);

            moveResult = rules.CanMove(
                b, "b4a3", PlayerTypeEnum.Black, "a2a4");

            Assert.IsTrue(moveResult.Success);
            Assert.AreEqual("a4", moveResult.TakenPiece, true);
        }
Ejemplo n.º 19
0
        public void White_Puts_Black_In_Check()
        {
            ChessBoard b = new ChessBoard();
            b.Set("e1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.King });
            b.Set("d1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Queen });

            b.Set("e8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.King });

            ChessGame g = new ChessGame(b, PlayerTypeEnum.White, null);
            var moveResult = g.PlayerMove(PlayerTypeEnum.White, "d1a4");

            Assert.IsTrue(moveResult.Success);
            Assert.IsTrue(moveResult.MoveType == MoveTypeEnum.Check);
        }
Ejemplo n.º 20
0
        public void Cannot_Castle_Out_Of_Check()
        {
            ChessBoard b = new ChessBoard();
            b.Set("e1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.King });
            b.Set("a1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Rook });

            b.Set("e8", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Queen });

            ChessGame g = new ChessGame(b, PlayerTypeEnum.White, null);
            var moveResult = g.PlayerMove(PlayerTypeEnum.White, "e1c1");

            Assert.IsFalse(moveResult.Success);

            moveResult = g.PlayerMove(PlayerTypeEnum.White, "e1f1");

            Assert.IsTrue(moveResult.Success);
        }
Ejemplo n.º 21
0
        public void Castle()
        {
            ChessBoard b = new ChessBoard();
            b.Set("e1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.King });
            b.Set("a1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Rook });

            ChessGame g = new ChessGame(b, PlayerTypeEnum.White, null);
            var moveResult = g.PlayerMove(PlayerTypeEnum.White, "e1c1");

            Assert.IsTrue(moveResult.Success);
            Assert.IsNotNull(moveResult.Moves);
            Assert.AreEqual(2, moveResult.Moves.Length);
            Assert.AreEqual("e1c1", moveResult.Moves[0]);
            Assert.AreEqual("a1d1", moveResult.Moves[1]);
            Assert.IsNotNull(g.ChessBoard.Get("d1"));
            Assert.AreEqual(PieceTypeEnum.Rook, g.ChessBoard.Get("d1").Type);
        }
Ejemplo n.º 22
0
 public ChessGame(ChessBoard b, PlayerTypeEnum player, Dictionary<PlayerTypeEnum, List<ChessPiece>> takenPieces)
     : this(b, player, takenPieces, new TraditionalRulesOfChess())
 {
 }
Ejemplo n.º 23
0
        public static bool IsPathClear(ChessBoard board, Tuple<int, int>[] path)
        {
            foreach (var move in path)
            {
                if (board.Get(move) != null)
                    return false;
            }

            return true;
        }
Ejemplo n.º 24
0
        static void InteractiveConsole()
        {
            ChessBoard chessBoard = new ChessBoard();
            //(new TraditionalBoardStager()).Stage(chessBoard);
            //(new RookTestingBoardStager()).Stage(chessBoard);
            //(new BishopTestingBoardStager()).Stage(chessBoard);
            //(new QueenTestingBoardStager()).Stage(chessBoard);
            //(new EnPassantTestingBoardStager()).Stage(chessBoard);
            //(new PawnSwapBoardStager()).Stage(chessBoard);
            (new KnightTestingBoardStager()).Stage(chessBoard);

            ChessGame chessGame = new ChessGame(
                chessBoard,
                PlayerTypeEnum.White,
                new Dictionary<PlayerTypeEnum, List<ChessPiece>>());

            ChessPiece[,] state = chessBoard.CreateStateCopy();
            (new ConsoleBoardPrinter()).PrintBoard(state, PlayerTypeEnum.White);

            PlayerTypeEnum playerTurn = PlayerTypeEnum.White;

            Console.WriteLine("Input: 1 square [a2] to show possible moves; 2 square [a1b1] to move");

            string move;
            Console.Write("> ");
            while (!string.IsNullOrWhiteSpace(move = Console.ReadLine()))
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(move))
                        break;

                    if (move.Length == 2)
                    {
                        var cpyb = new ChessBoard(chessBoard.CreateStateCopy());

                        var pm = (new PotentialMoveService()).GetPotentialMoves(chessGame, playerTurn);

                        List<string> moves;
                        pm.TryGetValue(move, out moves);
                        moves = moves ?? new List<string>();

                        (new ConsoleBoardPrinter()).PrintBoard(state, PlayerTypeEnum.White, new HashSet<string>(moves));
                    }
                    else if (move.Length == 4)
                    {
                        var moveResult = chessGame.PlayerMove(playerTurn, move);
                        playerTurn = moveResult.Turn;

                        state = chessBoard.CreateStateCopy();

                        (new ConsoleBoardPrinter()).PrintBoard(state, PlayerTypeEnum.White);
                        Console.WriteLine("{0} - {1} - {2} - {3} - {4}", moveResult.Success, moveResult.Error, moveResult.Taken, moveResult.MoveType, moveResult.Turn);
                    }
                    else
                        Console.WriteLine("Not implemented.");

                    Console.Write("> ");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
Ejemplo n.º 25
0
        public void Double_Check()
        {
            ChessBoard b = new ChessBoard();
            b.Set("h1", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.King });
            b.Set("h4", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Rook });
            b.Set("h5", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Pawn });
            b.Set("f4", new ChessPiece() { Player = PlayerTypeEnum.White, Type = PieceTypeEnum.Bishop });

            b.Set("h6", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.King });
            b.Set("g7", new ChessPiece() { Player = PlayerTypeEnum.Black, Type = PieceTypeEnum.Pawn });

            ChessGame g = new ChessGame(b, PlayerTypeEnum.Black, null);
            var moveResult = g.PlayerMove(PlayerTypeEnum.Black, "g7g5");
            Assert.IsTrue(moveResult.Success);

            moveResult = g.PlayerMove(PlayerTypeEnum.White, "h5g6");
            Assert.IsTrue(moveResult.Success);
        }