Exemple #1
0
        /// <summary>
        ///     Can any friendly piece block the attacker?
        /// </summary>
        /// <param name="threateningPiece"></param>
        /// <returns></returns>
        private bool CanFriendlyPieceMoveBetweenKingAndAttacker(IPiece threateningPiece, IBoardState boardState)
        {
            switch (threateningPiece)
            {
            // all cases fall through
            case IKnight _:   // knights jump pieces, cannot move between
            case IPawn _:     // pawns attack in an adjacent square, cannot move between
            case IKing _:     // king will never be checking another king.
                return(false);
            }

            foreach (IPiece piece in ActivePlayerPieces.Where(p => !(p is IKing) && p.Location != ChessPosition.None))
            {
                piece.GenerateMoves(boardState);

                // use a copy of the MoveSet to prevent the collection from being modified in the following loop
                IBoardState copyOfMoveSet = ModelLocator.BoardState;
                copyOfMoveSet.Add(piece.MoveSet);

                foreach (ChessPosition location in copyOfMoveSet)
                {
                    var move = ModelLocator.CreateMove(piece.Location, location);

                    var isMoveLegal            = IsMoveLegal(piece, move, boardState);
                    var isKingInCheckAfterMove = DoesPotentialMoveLeaveKingInCheck(move);

                    if (isMoveLegal && !isKingInCheckAfterMove)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Exemple #2
0
        /// <summary>
        ///     Determine if the king can move out of check by capturing a piece or simply moving.
        /// </summary>
        private bool CanKingMoveOrCaptureOutOfCheck(IKing king, IBoardState gameBoardState)
        {
            var canKingMoveOutOfCheck    = false;
            var canKingCaptureOutOfCheck = false;

            // 1.) Can the king move or capture out of check?

            foreach (ChessPosition position in king.ThreatenSet)
            {
                IMove    move    = ModelLocator.CreateMove(king.Location, position);
                ICapture capture = ModelLocator.CreateCapture(king.Location, position);

                canKingMoveOutOfCheck    |= IsMoveLegal(king, move, gameBoardState);
                canKingCaptureOutOfCheck |= IsCaptureLegal(king, capture, gameBoardState);
            }

            return(canKingMoveOutOfCheck || canKingCaptureOutOfCheck);
        }