Example #1
0
        public string ToTextBoard()
        {
            var sb = new StringBuilder();

            for (var rank = 7; rank >= 0; rank--)
            {
                for (var file = 0; file < 8; file++)
                {
                    var  loc    = BoardLocation.At(file + 1, rank + 1);
                    var  entity = GetItem(loc)?.Item;
                    char chr;
                    if (entity == null)
                    {
                        chr = '.';
                    }
                    else
                    {
                        chr = ChessPieceNameMapper.ToChar(entity.EntityType, entity.Owner);

                        var epY = char.IsUpper(chr) ? 5 : 4;
                        if (chr == 'p' || chr == 'P' && loc.Y == epY && entity.LocationHistory.Count() == 2)
                        {
                            chr = chr == 'p' ? 'e' : 'E';
                        }
                    }

                    sb.Append(chr == '\0' ? '.' : chr);
                }

                sb.AppendLine();
            }

            return(sb.ToString());
        }
            public void SetupPieces(BoardEngine <ChessPieceEntity> engine)
            {
                for (var rank = 7; rank >= 0; rank--)
                {
                    for (var file = 0; file < 8; file++)
                    {
                        var chr = _board[file, rank];

                        if (_chessPieceEntityFactory.ValidPieces.Contains(chr.ToString().ToUpper()))
                        {
                            var entity = _chessPieceEntityFactory.Create(
                                ChessPieceNameMapper.FromChar(chr),
                                char.IsUpper(chr) ? Colours.White : Colours.Black
                                );

                            var location = BoardLocation.At(file + 1, rank + 1);

                            engine.AddPiece(entity, location);
                            if (chr.ToString().ToUpper() == "E")
                            {
                                ((PawnEntity)entity).TwoStep = true;
                            }
                        }
                        else if (chr != ' ' && chr != '.' && chr != '\0')
                        {
                            Throw.InvalidPiece(chr);
                        }
                    }
                }
            }
        public void Should_return_true_for_move_to_enemy_piece()
        {
            var move = BoardMove.Create(BoardLocation.At(1, 1), BoardLocation.At(1, 8), (int)DefaultActions.MoveOrTake);

            SetupFromEntity(move, new TestBoardEntity());
            SetupToEntity(move, new TestBoardEntity(Enemy));
            _validator.ValidateMove(move, RoBoardStateMock.Object).ShouldBeTrue();
        }
        public void Should_return_false_for_move_to_own_piece()
        {
            var move = BoardMove.Create(BoardLocation.At(1, 1), BoardLocation.At(5, 1), (int)DefaultActions.MoveOnly);

            SetupFromEntity(move, new TestBoardEntity());
            SetupToEntity(move, new TestBoardEntity());
            _validator.ValidateMove(move, RoBoardStateMock.Object).ShouldBeFalse();
        }
        public void Should_return_true_for_move_to_empty_space()
        {
            var move = BoardMove.Create(BoardLocation.At(5, 1), BoardLocation.At(5, 2), (int)ChessMoveTypes.CastleKingSide);

            SetupToEntity(move);

            _validator.ValidateMove(move, RoBoardStateMock.Object).ShouldBeTrue();
        }
Example #6
0
        public void Should_return_true_for_square_under_no_attack()
        {
            var move = BoardMove.Create(BoardLocation.At(5, 1), BoardLocation.At(5, 2), (int)DefaultActions.MoveOrTake);

            SetupFromEntity(move, new TestBoardEntity());
            SetupGetNonOwnerEntitiesReturnsNone();

            _validator.ValidateMove(move, RoBoardStateMock.Object).ShouldBeTrue();
        }
Example #7
0
        public void Should_return_true_for_valid_update()
        {
            var move = new BoardMove(BoardLocation.At(1, 7), BoardLocation.At(1, 8), (int)DefaultActions.UpdatePiece, new TestBoardEntity());

            SetupFromEntity(move, new TestBoardEntity(1));
            SetupToEntity(move);


            _validator.ValidateMove(move, RoBoardStateMock.Object).ShouldBeTrue();
        }
Example #8
0
        public void Should_return_false_when_destination_is_empty()
        {
            var move = BoardMove.Create(BoardLocation.At(5, 8), BoardLocation.At(7, 8),
                                        (int)DefaultActions.MoveOrTake);

            SetupFromEntity(move, new TestBoardEntity());
            SetupToEntity(move);

            _validator.ValidateMove(move, RoBoardStateMock.Object).ShouldBeFalse();
        }
        public BoardMove Find(StandardAlgebraicNotation san, Colours forPlayer)
        {
            var t = san.ToNotation();

            if (san.CastleMove != StandardAlgebraicNotation.CastleSide.None)
            {
                return(FindCastleMove(san, forPlayer));
            }

            var destination = BoardLocation.At(san.ToFileX, san.ToRankY);

            if (san.HaveFrom)
            {
                var exact = FindExactMove(san, destination);

                if (exact == null)
                {
                    Throw.MoveNotFound($"Move not found: {san.ToNotation()}");
                }

                return(exact);
            }

            var items = _boardState
                        .GetItems((int)forPlayer, (int)san.Piece)
                        .ThatCanMoveTo(destination);

            if (TryFindMove(items, destination, san, out var move))
            {
                return(move);
            }

            if (san.FromFileX.HasValue)
            {
                items = items.Where(i => i.Paths.FlattenMoves().Any(m => m.From.X == san.FromFileX.Value));
                if (TryFindMove(items, destination, san, out move))
                {
                    return(move);
                }
            }

            if (san.FromRankY.HasValue)
            {
                items = items.Where(i => i.Paths.FlattenMoves().Any(m => m.From.Y == san.FromRankY.Value));
                if (TryFindMove(items, destination, san, out move))
                {
                    return(move);
                }
            }


            Throw.MoveNotFound($"Couldn't disambiguate move: {san.ToNotation()}");
            return(null);
        }
Example #10
0
 private void AddPawns(BoardEngine <ChessPieceEntity> engine)
 {
     foreach (var colour in new[] { Colours.White, Colours.Black })
     {
         for (int x = 1; x <= engine.Width; x++)
         {
             engine.AddPiece(CreatePawn(colour),
                             BoardLocation.At(x, colour == Colours.White ? 2 : 7));
         }
     }
 }
        private static BoardLocation SafeCreate(int x, int y)
        {
            if (ChessGame.OutOfBounds(y))
            {
                return(null);
            }
            if (ChessGame.OutOfBounds(x))
            {
                return(null);
            }

            return(BoardLocation.At(x, y));
        }
Example #12
0
        private BoardMove FindExactMove(StandardAlgebraicNotation san, BoardLocation destination)
        {
            var from = BoardLocation.At(san.FromFileX.Value, san.FromRankY.Value);
            var item = _boardState.GetItem(@from);
            var mv   = item.Paths.FindMove(@from, destination);

            var moveList = item.Paths.FlattenMoves().Select(m => m.ToChessCoords()).Aggregate((s, v) => s += $"{v},");

            if (mv == null)
            {
                Throw.MoveNotFound($"Cannot find move matching '{san.ToNotation()}', destination '{destination.ToChessCoord()}', moveList '{moveList}");
            }

            return(mv);
        }
        public void Setup()
        {
            _playerStateServiceMock = ChessTestFactory.ChessGameStateServiceMock();
            _boardStateMock         = new Mock <IBoardState <ChessPieceEntity> >();
            _boardStateMock.Setup(mb => mb.Clone()).Returns(_boardStateMock.Object);
            _kingItem = new LocatedItem <ChessPieceEntity>(
                BoardLocation.At(1, 1),
                new PawnEntity(Colours.White),
                null);
            _boardStateMock.Setup(mb => mb.GetItems(It.IsAny <int>(), It.IsAny <int>()))
            .Returns(new List <LocatedItem <ChessPieceEntity> >
            {
                _kingItem
            }.AsEnumerable());

            _moveServiceMock = ChessTestFactory.BoardMoveServiceMock();
        }
Example #14
0
        public static BoardLocation ToBoardLocation(this string s)
        {
            if (s.Length != 2)
            {
                Throw.InvalidBoardLocation(s);
            }

            if (!Enum.TryParse(s[0].ToString().ToUpper(), out ChessFile x))
            {
                Throw.InvalidBoardLocation(s);
            }
            if (!int.TryParse(s[1].ToString(), out var y))
            {
                Throw.InvalidBoardLocation(s);
            }

            return(BoardLocation.At((int)x, y));
        }
        private string buildChessLocation(int?fromFile, int?fromRank)
        {
            var file = "";
            var rank = "";

            if (fromFile.HasValue)
            {
                var tmp = BoardLocation.At(fromFile.Value, 1);
                file = tmp.ToChessCoord()[0].ToString().ToLower();
            }

            if (fromRank.HasValue)
            {
                var tmp = BoardLocation.At(1, fromRank.Value);
                rank = tmp.ToChessCoord()[1].ToString().ToLower();
            }

            return($"{file}{rank}");
        }
        protected void SetupGetNonOwnerEntities(BoardMove move, TestBoardEntity entity)
        {
            var from = BoardLocation.At(1, 1);
            var itemAttackingMoveToLocation = new LocatedItem <TestBoardEntity>(
                from,
                entity,
                new Paths
            {
                new Path
                {
                    new BoardMove(from, move.To, (int)DefaultActions.MoveOrTake)
                }
            });

            RoBoardStateMock.Setup(b => b.GetItems())
            .Returns(new List <LocatedItem <TestBoardEntity> >
            {
                itemAttackingMoveToLocation
            });
        }
Example #17
0
        private BoardMove FindCastleMove(StandardAlgebraicNotation san, Colours forPlayer)
        {
            var king = _boardState.GetItem(King.StartPositionFor(forPlayer));

            if (king == null)
            {
                Throw.MoveNotFound($"King not found: {san.ToNotation()}");
            }

            var y = forPlayer == Colours.White ? 1 : 8;

            var from = BoardLocation.At(san.FromFileX.Value, y);
            var to   = BoardLocation.At(san.ToFileX, y);
            var move = king.Paths.FindMove(@from, to);

            if (move == null)
            {
                Throw.MoveNotFound($"No valid castle move found: {from}{to}");
            }

            return(move);
        }
        public void Check_returns_valid_check_states(PlayerState whiteState, PlayerState blackState, GameCheckState expectedGameState)
        {
            var service = new CheckDetectionService(
                _playerStateServiceMock.Object,
                ChessFactory.BoardMoveService(ChessFactory.ChessBoardActionProvider()),
                ChessFactory.FindAttackPaths(),
                ChessFactory.PathsValidator()
                );

            if (expectedGameState != GameCheckState.BlackCheckmated &&
                expectedGameState != GameCheckState.WhiteCheckmated)
            {
                // give the king a get out move
                var kingPaths = new Paths();
                kingPaths.Add(new Path {
                    new BoardMove(BoardLocation.At(1, 1), BoardLocation.At(1, 2), 1)
                });
                _kingItem.UpdatePaths(kingPaths);
            }
            SetupCheckState(whiteState, Colours.White);
            SetupCheckState(blackState, Colours.Black);

            service.Check(_boardStateMock.Object).ShouldBe(expectedGameState);
        }
Example #19
0
 public Path Build()
 {
     return(new PathDestinationsBuilder(BoardLocation.At(4, 2))
            .To(BoardLocation.At(4, 4), (int)DefaultActions.MoveOnly)
            .Build());
 }