public void IsChecking_NoPiecesTest()
    {
        var bs = TestUtils.CreateBoardState(Array.Empty <(Index, Team, Piece)>());

        Assert.False(MoveValidator.IsChecking(Team.White, bs, null));
        Assert.False(MoveValidator.IsChecking(Team.Black, bs, null));
    }
Exemple #2
0
        /*
         * The King can move in any direction by 1 space, unless it is Castling.
         * The King asks the Move Validator if it is allowed to Castle.
         * It is only a valid move if it can Castle, or if the square it's moving from has a piece and it is not
         * moving to itself. Also need to check if the space it's moving to is not occupied by it's own colored pieces.
         */
        public bool IsValidMove(GameBoard gb, Square fromSquare, Square toSquare)
        {
            int  fromRow    = fromSquare.RowID;
            int  fromCol    = fromSquare.ColID;
            int  toRow      = toSquare.RowID;
            int  toCol      = toSquare.ColID;
            bool isOccupied = MoveValidator.IsOccupied(toSquare);
            bool isEnemy    = MoveValidator.IsEnemy(fromSquare, toSquare);

            if (fromSquare.Piece == null || fromSquare.Piece == toSquare.Piece)
            {
                return(false);
            }

            bool isCastle = MoveValidator.IsCastle(gb, fromSquare, toSquare);

            if (isCastle)
            {
                return(true);
            }

            if (((toRow == fromRow + 1 && toCol == fromCol) || (toCol == fromCol + 1 && toRow == fromRow) ||
                 (toRow == fromRow - 1 && toCol == fromCol) || (toCol == fromCol - 1 && toRow == fromRow) ||
                 (toRow == fromRow + 1 && toCol == fromCol + 1) || (toRow == fromRow - 1 && toCol == fromCol - 1) ||
                 (toRow == fromRow + 1 && toCol == fromCol - 1) || (toRow == fromRow - 1 && toCol == fromCol + 1)) &&
                (!isOccupied || isEnemy))
            {
                return(true);
            }

            return(false);
        }
Exemple #3
0
        private static void TestMove()
        {
            var board = MakeBoard("rnbqkbnr/pppppppp/8/8/8/3P4/PPP1PPPP/RNBQKBNR b KQkq -");

            //board.DoMove2(new Move(ChessPosition.D2, ChessPosition.D3, ChessPiece.WhitePawn));
            //board.UndoMove();
            Console.WriteLine(board.Print());
            var slidingMoveGenerator = new MagicBitboardsService();
            //var evaluationService = new EvaluationService();
            //Console.WriteLine(evaluationService.Evaluate(board));

            var attacksService = new AttacksService(slidingMoveGenerator);
            var pinDetector    = new PinDetector(slidingMoveGenerator);
            var validator      = new MoveValidator(attacksService, slidingMoveGenerator, pinDetector);
            var movesService   = new MoveGenerator(attacksService, slidingMoveGenerator, pinDetector, validator);
            var forWhite       = true;
            var moves          = new Move[218];
            var moveCount      = 0;

            movesService.GetAllLegalMoves(board, moves, ref moveCount);
            //var dests = moves.Select(x => x.To);
            //var toMoveBoard = fact.PositionsToBitBoard(dests);
            //var attacked = attacksService.GetAllAttacked(board);

            //var newMove = new Move(4,2,ChessPiece.WhiteKing);
            //board.DoMove2(newMove);

            //Debugging.ShowBitBoard(board.BitBoard[ChessPiece.WhiteKing], board.BitBoard[ChessPiece.WhiteRook]);
        }
        public void MoveIsValidWhenCheckingToPlaceSymbolOnVacantSpot()
        {
            var board = new Board(3);
            var move  = new Move(1, 1);

            Assert.True(MoveValidator.IsValidMove(move, board));
        }
 private void ValidateButton_Click(object sender, RoutedEventArgs e)
 {
     //UpdateBoard();
     if (MoveValidator.Validate(game.gs, BoardCharView, game.movementRecorder) != -1 && !game.GameEnd())
     {
         ListingWords(game.gs.CorrectWords);
         game.UpdateState(BoardCharView);
         GetNewTiles();
         LogBoardWriter(game.gs.ListOfPlayers[PlayerNow].ToString());
         PlayerNow = game.NextPlayer();
         UpdatePlayerInfoLbl(PlayerNow);
         Console.WriteLine("PlayerNow:" + PlayerNow);
         //gs.Update(bc, PlayerNow, sum);
         LoadBoardView();
         LoadRackView();
     }
     else
     {
         LogBoardWriter("Game Judge: \"You didn't score. Please try again!\"");
         LoadBoardView();
         Retry();
     }
     if (game.GameEnd())
     {
         foreach (Player p in game.gs.ListOfPlayers)
         {
             LogBoardWriter(game.gs.ListOfPlayers[PlayerNow].ToString());
         }
         game.gs.ListOfPlayers.Sort();
         LogBoardWriter("Game Winner is Player " + (game.gs.ListOfPlayers[0].Id + 1) + " with scores" + (game.gs.ListOfPlayers[0].Score) + "!!!");
     }
 }
Exemple #6
0
    /// <summary>
    /// Picks up a piece on the board
    /// </summary>
    void TryPickup()
    {
        RaycastHit hit;
        Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit) && hit.transform.tag == "chessPiece")
        {
            heldPiece = hit.transform.GetComponent <PieceScript>();

            if (heldPiece.team == GameManager.Instance.playerTeam)
            {
                ClearValidMoves();
                List <int> moves = MoveValidator.FindValidMoves(BoardManager.PositionToBoardIndex(hit.transform.position), BoardManager.BoardToCharArray(board));
                for (int i = 0; i < moves.Count; i++)
                {
                    validMoves.Add(board[moves[i]]);
                }
                ApplyHighlight();
            }
            else
            {
                heldPiece = null;
            }
        }
    }
        public void MoveIsInvalidWhenCheckingToPlaceSymbolOnSpotOutsideOfBoundaries()
        {
            var board = new Board(3);
            var move  = new Move(4, 4);

            Assert.False(MoveValidator.IsValidMove(move, board));
        }
        public async Task ValidateMoveAsync_FirstMove_CorrectMoveNumber()
        {
            // arrange
            var moveRepositoryMock = new Mock <IMoveRepository>();

            moveRepositoryMock
            .Setup(m => m.GetMovesForGame(It.IsAny <string>(), CancellationToken.None))
            .Returns(() => Task.FromResult(new List <Move>()))
            .Verifiable();

            var gameManager = new MoveValidator(moveRepositoryMock.Object);

            // act
            MoveResult result = await gameManager.ValidateMoveAsync(
                new Move
            {
                GameId        = "abc",
                BoardPosition = new Position
                {
                    X = 0,
                    Y = 0
                },
                TilePosition = new Position
                {
                    X = 0,
                    Y = 0
                },
                Player = Player.Cross
            }, CancellationToken.None);

            // assert
            result.Move.MoveNumber.Should().Be(1);
        }
Exemple #9
0
        public void Coordinate_Is_Invalid_When_Placing_Move_On_Spot_Outside_Of_Boundaries()
        {
            var board      = new Board(4);
            var coordinate = new Coordinate(4, 4);

            Assert.False(MoveValidator.IsValidMove(coordinate, board));
        }
        public void WhenPromotionIsRequiredAndPromotionMoveWasGivenPromoteAndReturnTrue()
        {
            var boardMock             = new Mock <IChessBoard>(MockBehavior.Strict);
            var promotionDetectorMock = new Mock <IPromotionDetector>(MockBehavior.Strict);
            var movementMock          = new Mock <ILegalMovement>(MockBehavior.Strict);

            var currentPlayer    = ChessColor.White;
            var piecePosition    = new Position(0, 1);
            var pieceDestination = new Position(0, 3);

            var chessMove = new ChessMove(piecePosition, pieceDestination,
                                          pawnPromotion: ChessPieceType.Queen);

            boardMock
            .Setup(b => b.Move(chessMove));

            promotionDetectorMock
            .Setup(c => c.IsPromotionRequired())
            .Returns(true);

            var moveValidator = new MoveValidator(boardMock.Object, movementMock.Object,
                                                  promotionDetectorMock.Object);

            var result = moveValidator.ValidateAndMove(chessMove, currentPlayer);

            Assert.AreEqual(true, result);
            boardMock
            .Verify(b => b.Move(chessMove));
        }
Exemple #11
0
        public void Coordinate_Is_Invalid_When_It_Is_Negative()
        {
            var board      = new Board(4);
            var coordinate = new Coordinate(-2, 0);

            Assert.False(MoveValidator.IsValidMove(coordinate, board));
        }
        public void WhenTryingToMoveEmptySpaceReturnFalse()
        {
            var boardMock             = new Mock <IChessBoard>(MockBehavior.Strict);
            var promotionDetectorMock = new Mock <IPromotionDetector>(MockBehavior.Strict);
            var movementMock          = new Mock <ILegalMovement>(MockBehavior.Strict);
            var examplePieceMock      = new Mock <IReadOnlyChessPiece>(MockBehavior.Strict);

            var currentPlayer    = ChessColor.Black;
            var piecePosition    = new Position(0, 1);
            var pieceDestination = new Position(0, 3);

            var chessMove = new ChessMove(new Position(1, 6), pieceDestination);

            examplePieceMock
            .SetupGet(p => p.Position)
            .Returns(piecePosition);

            boardMock
            .SetupGet(b => b.Pieces)
            .Returns(new List <IReadOnlyChessPiece>()
            {
                examplePieceMock.Object
            });

            promotionDetectorMock
            .Setup(c => c.IsPromotionRequired())
            .Returns(false);

            var moveValidator = new MoveValidator(boardMock.Object, movementMock.Object,
                                                  promotionDetectorMock.Object);

            var result = moveValidator.ValidateAndMove(chessMove, currentPlayer);

            Assert.AreEqual(false, result);
        }
Exemple #13
0
        private void SetMoveIndicator(SelectionDetails s, Tile tile)
        {
            if (tile == null)
            {
                moveIndicator.enabled = false;
                return;
            }

            moveIndicator.enabled = true;
            var color = MoveValidator.IsValidMove(s.selectedPawn, tile) ? Color.white : Color.red;

            moveIndicator.SetPositions(new Vector3[]
            {
                s.selectedPawn.transform.position + Vector3.up * 0.5f,
                tile.transform.position + Vector3.up * 0.5f
            });
            var gradient = moveIndicator.colorGradient;

            gradient.SetKeys(
                new GradientColorKey[1] {
                new GradientColorKey(color, 0f)
            },
                new GradientAlphaKey[1] {
                new GradientAlphaKey(1f, 0f)
            }
                );
            moveIndicator.colorGradient = gradient;
        }
Exemple #14
0
        public void Coordinate_Is_Valid_When_Placing_Move_On_Vacant_Spot()
        {
            var board      = new Board(4);
            var coordinate = new Coordinate(1, 1);

            Assert.True(MoveValidator.IsValidMove(coordinate, board));
        }
Exemple #15
0
        private bool IsThroughCheck(Move move, BoardState boardState)
        {
            var color = boardState.PiecePositions[move.StartPosition.X, move.StartPosition.Y].Color;

            if (MoveValidator.IsSquareAttacked(move.StartPosition, color, boardState))
            {
                return(true);
            }

            for (int x = move.StartPosition.X;
                 x != move.EndPosition.X;
                 x += Math.Sign(move.EndPosition.X - move.StartPosition.X))
            {
                var position = new Coordinate
                {
                    X = x,
                    Y = move.StartPosition.Y
                };

                if (MoveValidator.IsSquareAttacked(position, color, boardState))
                {
                    return(true);
                }
            }

            return(false);
        }
    /// <summary>
    /// Generates the next possible moves on the current board. There is no depth or ply to these moves
    /// </summary>
    /// <param name="currentBoard">board to analize</param>
    /// <param name="AiTurn">Whether it is the AI's turn or the players</param>
    /// <returns>A list of moves which are possible this turn</returns>
    public static List <Move> GenerateNextMoves(char[] currentBoard, bool AiTurn)
    {
        List <Move> movesQueue = new List <Move>();

        List <int> myPieces;

        if (AiTurn)
        {
            myPieces = BoardManager.GetTeamPieceIndexes(currentBoard, GameManager.Instance.aiTeam);
        }
        else
        {
            myPieces = BoardManager.GetTeamPieceIndexes(currentBoard, GameManager.Instance.playerTeam);
        }

        foreach (int pieceIndex in myPieces)
        {
            List <int> possibleMoves = MoveValidator.FindValidMoves(pieceIndex, currentBoard);

            foreach (int move in possibleMoves)
            {
                movesQueue.Add(new Move(currentBoard, pieceIndex, move));
            }
        }
        return(movesQueue = Prioritize(movesQueue, AiTurn));
    }
        public void MoveIsInvalidWhenCheckingToPlaceSymbolOnSpotWithNegativeCoordinates()
        {
            var board = new Board(3);
            var move  = new Move(-1, -2);

            Assert.False(MoveValidator.IsValidMove(move, board));
        }
Exemple #18
0
 public Games(Board b, BoardPresenter bp, MoveValidator mv, MoveExecutor me)
 {
     Board          = b;
     BoardPresenter = bp;
     MoveValidator  = mv;
     MoveExecutor   = me;
     ActivePlayer   = EPlayer.White;
 }
        public IChessGame Create()
        {
            var piecesFactory   = new PiecesFactory();
            var movementHistory = new MovementHistory();
            var piecePromoter   = new PiecePromoter(movementHistory);
            var castlingMover   = new CastlingMover(movementHistory);
            var enPassantMover  = new EnPassantMover(movementHistory);
            var pieceMover      = new PieceMover(movementHistory, piecePromoter,
                                                 castlingMover, enPassantMover);
            var chessBoard = new ChessBoard(piecesFactory, pieceMover);

            List <IMovement> movements = new();
            var pawnMovement           = new PawnMovement(chessBoard);
            var enPassantMovement      = new EnPassantMovement(chessBoard);
            var kingMovement           = new KingMovement(chessBoard);
            var horizontalMovement     = new HorizontalMovement(chessBoard);
            var verticalMovement       = new VerticalMovement(chessBoard);
            var pdiagonalMovement      = new PositiveDiagonalMovement(chessBoard);
            var ndiagonalMovement      = new NegativeDiagonalMovement(chessBoard);
            var knightMovement         = new KnightMovement(chessBoard);

            movements.Add(pawnMovement);
            movements.Add(enPassantMovement);
            movements.Add(kingMovement);
            movements.Add(horizontalMovement);
            movements.Add(verticalMovement);
            movements.Add(pdiagonalMovement);
            movements.Add(ndiagonalMovement);
            movements.Add(knightMovement);
            var movementComposite = new MovementComposite(movements);

            List <IMovement> movementsWithCastling = new();
            var queensideCastlingMovement          =
                new QueensideCastlingMovement(chessBoard, movementComposite);
            var kingsideCastlingMovement =
                new KingsideCastlingMovement(chessBoard, movementComposite);

            movementsWithCastling.Add(movementComposite);
            movementsWithCastling.Add(queensideCastlingMovement);
            movementsWithCastling.Add(kingsideCastlingMovement);
            var movementCompositeWithCastling = new MovementComposite(movementsWithCastling);

            var promotionDetector = new PromotionDetector(chessBoard);

            var checkDetector = new CheckDetector(chessBoard, movementCompositeWithCastling);

            var legalMovement = new LegalMovement(chessBoard,
                                                  movementCompositeWithCastling, checkDetector);

            var moveValidator = new MoveValidator(chessBoard,
                                                  legalMovement, promotionDetector);

            var gameFinishedDetector = new GameFinishedDetector(checkDetector,
                                                                legalMovement);

            return(new ChessGame(chessBoard, moveValidator,
                                 promotionDetector, gameFinishedDetector, legalMovement));
        }
Exemple #20
0
    public static MoveValidator Create(Board board)
    {
        MoveValidator validator = new MoveValidator()
        {
            _board = board
        };

        return(validator);
    }
        [Fact] public void MoveIsInvalidWhenCheckingToPlaceSymbolOnFilledSpot()
        {
            var board       = new Board(3);
            var validMove   = new Move(1, 1);
            var invalidMove = new Move(1, 1);

            board.PlaceSymbolToCoordinates(Symbol.Cross, validMove);

            Assert.False(MoveValidator.IsValidMove(invalidMove, board));
        }
        private void CreateValidator()
        {
            board    = new Board(5, 5);
            troopMap = new TroopMap(board);
            player0  = PlayerSide.Red;
            wb       = new WavesBuilder();

            validator = new MoveValidator(troopMap, board, player0);
            validator.ToggleActivePlayer();
        }
Exemple #23
0
        public MoveTest()
        {
            _move = new Move()
            {
                BeerId      = "1",
                NewLocation = "T",
                UserName    = "******"
            };

            _validator = new MoveValidator();
        }
Exemple #24
0
 public bool Validate(char[,] bc)
 {
     if (MoveValidator.Validate(gs, bc, moveRecorder) != -1 && !GameEnd())
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Exemple #25
0
        public void Coordinate_Is_Invalid_When_Placing_Move_On_Revealed_Spot()
        {
            var board             = new Board(4);
            var validCoordinate   = new Coordinate(1, 1);
            var invalidCoordinate = new Coordinate(1, 1);
            var square            = board.GetSquare(validCoordinate);

            square.IsRevealed = true;

            Assert.False(MoveValidator.IsValidMove(invalidCoordinate, board));
        }
        public void IsOccupiedTest()
        {
            GameBoard gb = new GameBoard(8, 8);

            bool actual = MoveValidator.IsOccupied(gb.squares[1, 0]);

            Assert.AreEqual(true, actual);

            actual = MoveValidator.IsOccupied(gb.squares[2, 0]);
            Assert.AreEqual(false, actual);
        }
        public void IsEnemyTest()
        {
            GameBoard gb = new GameBoard(8, 8);

            bool actual = MoveValidator.IsEnemy(gb.squares[6, 0], gb.squares[1, 0]);

            Assert.AreEqual(true, actual);

            actual = MoveValidator.IsEnemy(gb.squares[1, 1], gb.squares[1, 0]);
            Assert.AreEqual(false, actual);
        }
Exemple #28
0
        /*
         * Since a Queen can move like either a Rook or a Bishop, reuses their ValidMove
         * code in the MoveValidator
         */
        public bool IsValidMove(GameBoard gb, Square fromSquare, Square toSquare)
        {
            bool rookValid   = MoveValidator.RookMove(gb, fromSquare, toSquare);
            bool bishopValid = MoveValidator.BishopMove(gb, fromSquare, toSquare);

            if (rookValid || bishopValid)
            {
                return(true);
            }

            return(false);
        }
Exemple #29
0
 void Awake()
 {
     if (moveGenerator == null)
     {
         moveGenerator = GetComponent <MoveGenerator>();
     }
     if (moveValidator == null)
     {
         moveValidator = GetComponent <MoveValidator>();
     }
     move = GetComponent <Move>();
     SetReturning(false);
 }
Exemple #30
0
        /*
         * The knight moves in horizontally or vertically 2 spaces, then the other direction
         * 1 space. It is only a valid move if the square it's moving from has a piece and it is not moving to
         * itself. Also need to check if the space it's moving to is not occupied by it's own colored pieces.
         */
        public bool IsValidMove(GameBoard gb, Square fromSquare, Square toSquare)
        {
            int  fromRow    = fromSquare.RowID;
            int  fromCol    = fromSquare.ColID;
            int  toRow      = toSquare.RowID;
            int  toCol      = toSquare.ColID;
            bool isOccupied = MoveValidator.IsOccupied(toSquare);
            bool isEnemy    = MoveValidator.IsEnemy(fromSquare, toSquare);

            if (fromSquare.Piece == null || fromSquare.Piece == toSquare.Piece)
            {
                return(false);
            }

            if (toRow == fromRow + 1 && fromCol == toCol + 2 && (!isOccupied || isEnemy))
            {
                return(true);
            }
            else if (toRow == fromRow + 1 && fromCol == toCol - 2 && (!isOccupied || isEnemy))
            {
                return(true);
            }
            else if (toRow == fromRow - 1 && fromCol == toCol + 2 && (!isOccupied || isEnemy))
            {
                return(true);
            }
            else if (toRow == fromRow - 1 && fromCol == toCol - 2 && (!isOccupied || isEnemy))
            {
                return(true);
            }
            else if (toRow == fromRow + 2 && fromCol == toCol + 1 && (!isOccupied || isEnemy))
            {
                return(true);
            }
            else if (toRow == fromRow - 2 && fromCol == toCol + 1 && (!isOccupied || isEnemy))
            {
                return(true);
            }
            else if (toRow == fromRow + 2 && fromCol == toCol - 1 && (!isOccupied || isEnemy))
            {
                return(true);
            }
            else if (toRow == fromRow - 2 && fromCol == toCol - 1 && (!isOccupied || isEnemy))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }