예제 #1
0
파일: King.cs 프로젝트: AJLeuer/Chess.NET
            public override List <Move> FindAllPossibleLegalMoves()
            {
                List <Move> movesPotentiallyAvailable = base.FindAllPossibleLegalMoves();
                var         safeMoves = new List <Move>();

                foreach (var move in movesPotentiallyAvailable)
                {
                    var   gameState      = move.CommitInSimulation();
                    IKing kingAfterMove  = (IKing)gameState.Piece;
                    var   opponentPieces = gameState.Game.FindOpponentPlayer(gameState.Piece.Player).Pieces;

                    bool destinationIsSafe = true;

                    foreach (var piece in opponentPieces)
                    {
                        var opponentPiece = (Piece)piece;
                        //In this extreme edge case and highly unusual scenario, we will need to call the base implementation
                        //of CanMoveTo() in order to avoid the infinite recursion that would result from a King needing to know if another King can
                        //potentially move to a certain square before *it* can know whether it itself can legally move there
                        if (opponentPiece.canMoveTo(kingAfterMove.Square))
                        {
                            destinationIsSafe = false;
                            break;
                        }
                    }

                    if (destinationIsSafe)
                    {
                        safeMoves.Add(move);
                    }
                }

                return(safeMoves);
            }
예제 #2
0
    static void Main(string[] args)
    {
        IKing  king   = SetUpKing();
        Engine engine = new Engine(king);

        engine.Run();
    }
예제 #3
0
    public static void Main()
    {
        IKing  king  = SetupKing();
        string input = Console.ReadLine();

        while (input != "End")
        {
            string[] tokens = input.Split();

            string command = tokens[0];

            if (command == "Attack")
            {
                king.GetAttacked();
            }
            else if (command == "Kill")
            {
                string subordinateName = tokens[1];

                ISubordinate subordinate = king.Subordinates.First(s => s.Name == subordinateName);
                subordinate.Die();
            }

            input = Console.ReadLine();
        }
    }
예제 #4
0
        /// <summary>
        ///     Retrieves a list of positions that are between the castling Rook and King.
        /// </summary>
        /// <param name="king"></param>
        /// <param name="rook"></param>
        /// <returns></returns>
        public List <ChessPosition> GetPositionsBetweenCastle(IKing king, IRook rook)
        {
            var locationsInBetween = new List <ChessPosition>();

            // add all locations to check based on where the king and rook are located
            switch (king.Location)
            {
            case ChessPosition.E1 when rook.Location == ChessPosition.A1:
                locationsInBetween.Add(ChessPosition.D1);
                locationsInBetween.Add(ChessPosition.C1);
                locationsInBetween.Add(ChessPosition.B1);
                break;

            case ChessPosition.E1 when rook.Location == ChessPosition.H1:
                locationsInBetween.Add(ChessPosition.F1);
                locationsInBetween.Add(ChessPosition.G1);
                break;

            case ChessPosition.E8 when rook.Location == ChessPosition.A8:
                locationsInBetween.Add(ChessPosition.D8);
                locationsInBetween.Add(ChessPosition.C8);
                locationsInBetween.Add(ChessPosition.B8);
                break;

            case ChessPosition.E8 when rook.Location == ChessPosition.H8:
                locationsInBetween.Add(ChessPosition.F8);
                locationsInBetween.Add(ChessPosition.G8);
                break;
            }

            return(locationsInBetween);
        }
 public CommandInterpreter(IReader reader, IWriter writer, IKing king, IDictionary <string, IUnit> military)
 {
     this.reader   = reader;
     this.writer   = writer;
     this.king     = king;
     this.military = military;
 }
        public void should_create_orc_king()
        {
            IKingdomFactory kingdomFactory = FactoryMaker.Create(KingdomType.ORC);

            IKing king = kingdomFactory.CreateKing();

            Assert.Equal("This is Orc king", king.Description);
        }
예제 #7
0
        private bool CausesMate()
        {
            Move   simulation   = CommitInSimulation();
            Player opponent     = simulation.Game.FindOpponentPlayer(this.Player);
            IKing  opponentKing = (IKing)opponent.Pieces.First((IPiece piece) => { return(piece.IsOfType <IKing>()); });

            return(opponentKing.CanMove() == false);
        }
        public void should_create_elven_king()
        {
            IKingdomFactory kingdomFactory = FactoryMaker.Create(KingdomType.ELF);

            IKing king = kingdomFactory.CreateKing();

            Assert.Equal("This is Elven king", king.Description);
        }
예제 #9
0
    public void DecreaseHealth(IKing king)
    {
        this.Health -= 1;

        if (this.Health <= MIN_HEALTH)
        {
            this.Die(king);
        }
    }
예제 #10
0
 private void SubordinatesAct(IKing king)
 {
     foreach (var subject in king.Subjects.Where(x => x.GetType().Name == "Guard" && x.IsAlive))
     {
         System.Console.WriteLine($"Royal Guard {subject.Name} is defending!");
     }
     foreach (var subject in king.Subjects.Where(x => x.GetType().Name == "Footman" && x.IsAlive))
     {
         System.Console.WriteLine($"Footman {subject.Name} is panicking!");
     }
 }
예제 #11
0
        public IKing Initialize()
        {
            var nameOfKing = this.reader.ReadLine();

            this.king = new King(this.writer, nameOfKing);

            this.Initialize("RoyalGuard");
            this.Initialize("Footman");

            return(this.king);
        }
예제 #12
0
        /// <summary>
        ///     Updates board for Castle. Does not check legality.
        /// </summary>
        /// <param name="king"></param>
        /// <param name="move"></param>
        /// <param name="rook"></param>
        private void UpdateBoardForCastle(IKing king, IMove move, IRook rook)
        {
            ChessPosition newRookLocation = ModelLocator.CastlingHelper.GetEndingPositionForCastlingRook(king, rook);

            GameBoard.Remove(king.Location);    // remove King from board
            king.MoveTo(move.EndingPosition);   // move King, update location
            GameBoard.Add(move.EndingPosition); // place King on board at update location

            GameBoard.Remove(rook.Location);    // remove Rook from board
            rook.MoveTo(newRookLocation);       // move Rook, update location
            GameBoard.Add(rook.Location);       // place Rook on board at updated location

            MoveHistory.Add(king, move);
        }
예제 #13
0
        /// <summary>
        ///     Determines the position where a castling Rook will end at.
        /// </summary>
        /// <param name="king"></param>
        /// <param name="rook"></param>
        /// <returns></returns>
        public ChessPosition GetEndingPositionForCastlingRook(IKing king, IRook rook)
        {
            switch (king.Location)
            {
            case ChessPosition.E1 when rook.Location == ChessPosition.A1: return(ChessPosition.D1);

            case ChessPosition.E1 when rook.Location == ChessPosition.H1: return(ChessPosition.F1);

            case ChessPosition.E8 when rook.Location == ChessPosition.A8: return(ChessPosition.D8);

            case ChessPosition.E8 when rook.Location == ChessPosition.H8: return(ChessPosition.F8);

            default: return(rook.Location);
            }
        }
예제 #14
0
        /// <summary>
        ///     Returns all pieces that are threatening the passed in King
        /// </summary>
        /// <param name="king"></param>
        /// <returns></returns>
        private List <IPiece> GetPiecesThreateningKing(IKing king)
        {
            var piecesThreateningKing = new List <IPiece>();

            InactivePlayerPieces.ForEach(p =>
            {
                p.GenerateThreatened(GameBoard.State, InactivePlayerBoardState);

                if (p.IsThreateningAt(king.Location))
                {
                    piecesThreateningKing.Add(p);
                }
            });

            return(piecesThreateningKing);
        }
예제 #15
0
        public void On_King_GetSomeOneKilled(IKing king, string name)
        {
            if (!nameHits.ContainsKey(name))
            {
                nameHits[name] = 0;
            }
            nameHits[name]++;

            var subject             = king.Subjects.FirstOrDefault(x => x.Name == name);
            int subjectHitTolerance = subject.GetType().Name == "Footman" ? FootmenHitTolerance : GuardHitTolerance;

            if (subjectHitTolerance == nameHits[name])
            {
                king.Subjects.FirstOrDefault(x => x.Name == name).Die();
            }
        }
예제 #16
0
    private static void Run(IKing king, IList <ISoldier> soldiers)
    {
        string[] commandArgs;

        while ((commandArgs = Console.ReadLine().Split(' '))[0] != "End")
        {
            if (commandArgs[0] == "Attack")
            {
                king.BeAttacked();
            }
            else if (commandArgs[0] == "Kill")
            {
                soldiers.First(x => x.Name == commandArgs[1]).DecreaseHealth(king);
            }
        }
    }
예제 #17
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);
        }
        private static void ProcessCommand(IKing king, string[] inputTokens)
        {
            switch (inputTokens[0])
            {
            case "Attack":
                king.GetAttacked();
                break;

            case "Kill":
                var subordinateName = inputTokens[1];
                var subordinate     = king.Subordinates.FirstOrDefault(s => s.Name == subordinateName);
                subordinate.Die();
                break;

            default:
                throw new ArgumentException();
            }
        }
예제 #19
0
        /// <summary>
        ///     Generates the two-space moves that a king can make to initiate a castle.
        /// </summary>
        /// <param name="king"></param>
        /// <returns></returns>
        public IEnumerable <ChessPosition> GetCastleMovesForKing(IKing king)
        {
            var positions = new List <ChessPosition>();

            if (king.HasMoved)
            {
                return(positions);
            }

            if (king.Color == ChessColor.White)
            {
                positions.Add(ChessPosition.G1);
                positions.Add(ChessPosition.C1);
            }
            else
            {
                positions.Add(ChessPosition.G8);
                positions.Add(ChessPosition.C8);
            }

            return(positions);
        }
예제 #20
0
    private static IList <ISoldier> GetSoldiers(IKing king)
    {
        string[] royalGuardsNames = Console.ReadLine().Split(' ');
        string[] footmanNames     = Console.ReadLine().Split(' ');

        IList <ISoldier> soldiers = new List <ISoldier>();

        foreach (var name in royalGuardsNames)
        {
            ISoldier soldier = new RoyalGuard(name);
            king.Attacked += soldier.OnKingAttacked;
            soldiers.Add(soldier);
        }
        foreach (var name in footmanNames)
        {
            ISoldier soldier = new Footman(name);
            king.Attacked += soldier.OnKingAttacked;
            soldiers.Add(soldier);
        }

        return(soldiers);
    }
예제 #21
0
        public void Run()
        {
            string input    = Console.ReadLine();
            string kingName = input;

            this.newKing = new King(kingName, new List <ISubordinateble>());

            string[] rouyalGuards = Console.ReadLine().Split(" ");
            foreach (var item in rouyalGuards)
            {
                ISubordinateble subordinate = new RoyalGuard(item);
                this.newKing.AddSubordinate(subordinate);
            }

            string[] footsman = Console.ReadLine().Split(" ");
            foreach (var item in footsman)
            {
                ISubordinateble subordinate = new Footman(item);
                this.newKing.AddSubordinate(subordinate);
            }

            input = Console.ReadLine();
            while (!input.Equals("End"))
            {
                string[] tokens = input.Split();

                if (tokens[0].Equals("Attack"))
                {
                    this.newKing.GetAttack();
                }
                else if (tokens[0].Equals("Kill"))
                {
                    this.newKing.Subordinates.First(x => x.Name == tokens[1]).TakeDamage();
                }

                input = Console.ReadLine();
            }
            Console.WriteLine();
        }
        static void Main(string[] args)
        {
            IKing king = KingSetter();

            string input = String.Empty;

            while ((input = Console.ReadLine()) != "End")
            {
                string[] tokens = input.Split();
                string   cmd    = tokens[0];

                if (cmd == "Attack")
                {
                    king.BeingAttacked();
                }
                else if (cmd == "Kill")
                {
                    string       name = tokens[1];
                    ISubordinate unit = king.Army.First(u => u.Name == name);
                    unit.Die();
                }
            }
        }
예제 #23
0
        /// <summary>
        ///     Is the board in a checkmate state?
        /// </summary>
        /// <param name="king"></param>
        /// <param name="piecesThreateningKing"></param>
        /// <returns></returns>
        private bool IsBoardStateInCheckmate(IKing king, IReadOnlyList <IPiece> piecesThreateningKing)
        {
            bool isKingInCheckFromMultiplePieces = piecesThreateningKing.Count > 1; // king must capture a piece or move

            king.GenerateThreatened(GameBoard.State, ActivePlayerBoardState);
            bool isCheckMateAvoidable = CanKingMoveOrCaptureOutOfCheck(king, GameBoard.State);

            if (isCheckMateAvoidable)
            {
                return(false);
            }
            // if king is attacked by multiple pieces, it must either move or capture to avoid checkmate.
            if (isKingInCheckFromMultiplePieces)
            {
                return(true);
            }

            Debug.Assert(piecesThreateningKing.Count == 1);

            isCheckMateAvoidable |= CanThreateningPieceBeCaptured(piecesThreateningKing[0]);
            isCheckMateAvoidable |= CanFriendlyPieceMoveBetweenKingAndAttacker(piecesThreateningKing[0], GameBoard.State);

            return(!isCheckMateAvoidable);
        }
예제 #24
0
 public void Die(IKing king)
 {
     king.Attacked -= this.OnKingAttacked;
 }
예제 #25
0
 public Engine(IKing king)
 {
     this.king = king;
 }
예제 #26
0
 public void createKingdom(IKingdomFactory factory)
 {
     king   = factory.createKing();
     castle = factory.createCastle();
     army   = factory.createArmy();
 }
예제 #27
0
 private void setKing(IKing king) => this.king = king;
예제 #28
0
 private void Die(IKing king)
 {
     king.Attacked -= this.OnKingAttacked;
 }
예제 #29
0
 public void On_King_GetSomeOneKilled(IKing king, string name)
 {
     king.Subjects.FirstOrDefault(x => x.Name == name).Die();
 }
예제 #30
0
 public void On_King_GotAttacked(IKing king)
 {
     System.Console.WriteLine($"King {king.Name} is under attack!");
     SubordinatesAct(king);
 }