Example #1
0
        /// <summary>Is the move legal. This move doesn't check multiple jumps.</summary>
        /// <param name="board">the board state</param>
        /// <param name="startRow">the start row</param>
        /// <param name="startCol">the start col</param>
        /// <param name="endRow">the end row</param>
        /// <param name="endCol">the end col</param>
        /// <param name="player">the player with the turn</param>
        /// <returns>LEGAL if the move is legal.  Illegal if the move is not legal.  INCOMPLETE if the move results in a jump.</returns>
        private static MoveStatus IsMoveLegal(IBoard board, int startRow, int startCol, int endRow, int endCol, Player player)
        {
            if (!InBounds(startRow, startCol, board) || !InBounds(endRow, endCol, board))
            {
                // out of board bounds
                return(MoveStatus.Illegal);
            }

            Piece startPosition = board[startRow, startCol];
            Piece endPosition   = board[endRow, endCol];

            if ((player == Player.Black && !BoardUtilities.IsBlack(startPosition)) || (player == Player.White && !BoardUtilities.IsWhite(startPosition)))
            {
                // wrong player attempting to make a move
                return(MoveStatus.Illegal);
            }
            else if (!BoardUtilities.IsEmpty(endPosition))
            {// destination is not empty
                return(MoveStatus.Illegal);
            }

            int forwardDirection  = (BoardUtilities.IsBlack(startPosition)) ? 1 : -1;
            int backwardDirection = (!BoardUtilities.IsKing(startPosition)) ? 0 : (BoardUtilities.IsBlack(startPosition)) ? -1 : 1;

            // check for single step along vertical axis
            if (Math.Abs(endRow - startRow) == 1)
            {//possible walk made
                // check if we took a walk when a jump was available
                if (CanJump(board, player))
                {
                    return(MoveStatus.Illegal);
                }

                // one step along the horizontal axis and proper vertical direction movement
                // men can't go backwards but kings can
                if ((Math.Abs(endCol - startCol) == 1) && (startRow + forwardDirection == endRow || startRow + backwardDirection == endRow))
                {
                    return(MoveStatus.Legal);
                }
            }
            else if (Math.Abs(endRow - startRow) == 2)
            {// possible jump made
                int jumpedRow = (endRow + startRow) / 2;
                int jumpedCol = (endCol + startCol) / 2;

                if (BoardUtilities.IsOpponentPiece(player, board[jumpedRow, jumpedCol]))
                {
                    // one step along the horizontal axis and proper vertical direction movement
                    // men can't go backwards but kings can
                    if ((Math.Abs(endCol - startCol) == 2) && (startRow + forwardDirection * 2 == endRow || startRow + backwardDirection * 2 == endRow))
                    {
                        return(MoveStatus.Incomplete);
                    }
                }
            }

            return(MoveStatus.Illegal);
        }
Example #2
0
        /// <summary>
        /// GetWalks - Получить прогулки
        /// Get available walks
        /// Получить доступные прогулки
        /// </summary>
        /// <param name="moves">
        /// Moves added to this collection
        /// Ходы добавлены в эту коллекцию
        /// </param>
        /// <param name="board">
        /// the board state
        /// состояние правления
        /// </param>
        /// <param name="row">
        /// the row the piece is on
        /// строка, на которой стоит произведение
        /// </param>
        /// <param name="col">
        /// the column the piece is on
        /// колонка, на которой находится произведение
        /// </param>
        /// <param name="verticalDirection">
        /// the vertical direction to move in
        /// вертикальное направление движения
        /// </param>
        /// <param name="horizontalDirection">
        /// the horizontal direction to move in
        /// горизонтальное направление движения
        /// </param>
        private static bool GetWalks(ICollection <Move> moves, IBoard board, int row, int col, int verticalDirection, int horizontalDirection)
        {
            int newRow = row + verticalDirection;
            int newCol = col + horizontalDirection;

            if ((InBounds(newRow, newCol, board)) && (BoardUtilities.IsEmpty(board[newRow, newCol])))
            {
                //space is empty
                moves.Add(new Move(Location.ToPosition(row, col), Location.ToPosition(newRow, newCol)));
            }

            return(false);
        }
Example #3
0
        /// <summary>
        /// CanWalk - Может ходить
        /// Check if piece can move
        /// Проверьте, может ли кусок двигаться
        /// </summary>
        /// <param name="board">
        /// the board state
        /// состояние правления
        /// </param>
        /// <param name="row">
        /// the row the piece is on
        /// строка, на которой стоит произведение
        /// </param>
        /// <param name="col">
        /// the column the piece is on
        /// колонка, на которой находится произведение
        /// </param>
        /// <param name="verticalDirection">
        /// the vertical direction to move in
        /// вертикальное направление движения
        /// </param>
        /// <param name="horizontalDirection">
        /// the horizontal direction to move in
        /// горизонтальное направление движения
        /// </param>
        /// <returns><code>true</code>
        /// if the piece can move
        /// если кусок может двигаться
        /// </returns>
        private static bool CanWalk(IBoard board, int row, int col, int verticalDirection, int horizontalDirection)
        {
            int newRow = row + verticalDirection;
            int newCol = col + horizontalDirection;

            if (!InBounds(newRow, newCol, board))
            {//not within board bounds
                return(false);
            }

            if (BoardUtilities.IsEmpty(board[newRow, newCol]))
            {//space is empty
                return(true);
            }

            return(false);
        }
Example #4
0
        /// <summary>
        /// CanJump - Может прыгать
        /// Check the piece at the postion can jump any pieces on the board
        /// Проверьте фигуру в позиции, можете прыгать любые фигуры на доске
        /// </summary>
        /// <param name="board">
        /// the board state
        /// состояние правления
        /// </param>
        /// <param name="row">
        /// the row the piece is on
        /// строка, на которой стоит произведение
        /// </param>
        /// <param name="col">
        /// the column the piece is on
        /// колонка, на которой находится произведение
        /// </param>
        /// <param name="verticalDirection">
        /// the vertical direction to move in
        /// вертикальное направление движения
        /// </param>
        /// <param name="horizontalDirection">
        /// the horizontal direction to move in
        /// горизонтальное направление движения
        /// </param>
        /// <returns><code>true</code>
        /// if the piece can make a jump
        /// если кусок может совершить прыжок
        /// </returns>
        private static bool CanJump(IBoard board, int row, int col, int verticalDirection, int horizontalDirection)
        {
            int   newRow = row + verticalDirection;
            int   newCol = col + horizontalDirection;
            Piece piece  = board[row, col];

            if (!InBounds(newRow, newCol, board))
            {//not within board bounds
                return(false);
            }

            if (BoardUtilities.AreOpponents(piece, board[newRow, newCol]))
            {// check if you can jump enemy
                int endRow = newRow + verticalDirection;
                int endCol = newCol + horizontalDirection;
                return(InBounds(endRow, endCol, board) && BoardUtilities.IsEmpty(board[endRow, endCol]));
            }

            return(false);
        }
Example #5
0
        /// <summary>
        /// GetCaptures - Получить захваты
        /// Generate captures list for the piece at the given location
        /// Создать список снимков для произведения в заданном месте
        /// </summary>
        /// <param name="moves">
        /// stores the list of moves generated
        /// сохраняет список сгенерированных ходов
        /// </param>
        /// <param name="locations">
        /// list of parent locations
        /// список родительских локаций
        /// </param>
        /// <param name="board">
        /// the board state
        ///  состояние правления
        /// </param>
        /// <param name="piece">
        /// the piece
        /// кусок
        /// </param>
        /// <param name="row">
        /// the row of the piece
        ///  строка произведения
        /// </param>
        /// <param name="col">
        /// the column of the piece
        /// столбец произведения
        /// </param>
        /// <param name="dx">
        /// the horizontal direction
        ///  горизонтальное направление
        /// </param>
        /// <param name="dy">
        /// the vertical direction
        /// вертикальное направление
        /// </param>
        /// <returns><c>true</c>
        /// if capture available
        /// если захват доступен
        /// </returns>
        private static bool GetCaptures(ICollection <Move> moves, IList <Location> locations, IBoard board, Piece piece, int row, int col, int dx, int dy)
        {
            int endRow  = row + dy * 2;
            int endCol  = col + dx * 2;
            int jumpRow = row + dy;
            int jumpCol = col + dx;

            // jump available
            // прыжок доступен
            if (InBounds(endRow, endCol, board) && BoardUtilities.AreOpponents(piece, board[jumpRow, jumpCol]) && BoardUtilities.IsEmpty(board[endRow, endCol]))
            {
                locations.Add(new Location(endRow, endCol));
                board[row, col]         = Piece.None;
                board[jumpRow, jumpCol] = Piece.None;
                board[endRow, endCol]   = piece;

                bool  captureAvailable = false;
                int[] DIRECTIONS       = { -1, 1 }; // {down/right, up/left} // {вниз / вправо, вверх / влево}
                int   Y_START_INDEX    = (BoardUtilities.IsKing(piece) || BoardUtilities.IsWhite(piece)) ? 0 : 1;
                int   Y_END_INDEX      = (BoardUtilities.IsKing(piece) || BoardUtilities.IsBlack(piece)) ? 1 : 0;

                for (int idxY = Y_START_INDEX; idxY <= Y_END_INDEX; idxY++)
                {
                    for (int idxX = 0; idxX < DIRECTIONS.Length; idxX++)
                    {
                        bool result = GetCaptures(
                            moves, new List <Location>(locations),
                            board.Copy(), piece,
                            endRow, endCol, DIRECTIONS[idxX], DIRECTIONS[idxY]
                            );
                        captureAvailable = captureAvailable || result;
                    }
                }


                if ((!captureAvailable) && (locations.Count > 1))
                {
                    Move move = new Move();
                    foreach (Location location in locations)
                    {
                        move.AddMoves(location);
                    }

                    moves.Add(move);
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #6
0
        /// <summary>
        /// IsMoveLegal - Это законно
        /// Is the move legal. This move doesn't check multiple jumps.
        /// Это законный ход. Этот ход не проверяет несколько прыжков.
        /// </summary>
        /// <param name="board">
        /// the board state
        /// состояние правления
        /// </param>
        /// <param name="startRow">
        /// the start row
        /// начальный ряд
        /// </param>
        /// <param name="startCol">
        /// the start col
        /// начальный столб
        /// </param>
        /// <param name="endRow">
        /// the end row
        /// конец строки
        /// </param>
        /// <param name="endCol">
        /// the end col
        /// конец колонки
        /// </param>
        /// <param name="player">
        /// the player with the turn
        /// игрок с поворотом
        /// </param>
        /// <returns>
        /// LEGAL if the move is legal.  Illegal if the move is not legal.  INCOMPLETE if the move results in a jump.
        /// ЗАКОННЫЙ, если движение законно. Незаконный, если движение не законно. НЕПОЛНЫЙ, если движение приводит к скачку.
        /// </returns>
        private static MoveStatus IsMoveLegal(IBoard board, int startRow, int startCol, int endRow, int endCol, Player player)
        {
            if (!InBounds(startRow, startCol, board) || !InBounds(endRow, endCol, board))
            {
                // out of board bounds
                //из границ правления
                return(MoveStatus.Illegal);
            }

            Piece startPosition = board[startRow, startCol];
            Piece endPosition   = board[endRow, endCol];

            if ((player == Player.Black && !BoardUtilities.IsBlack(startPosition)) || (player == Player.White && !BoardUtilities.IsWhite(startPosition)))
            {
                // wrong player attempting to make a move
                //неправильный игрок, пытающийся сделать движение
                return(MoveStatus.Illegal);
            }
            else if (!BoardUtilities.IsEmpty(endPosition))
            {// destination is not empty
             //место назначения не пусто
                return(MoveStatus.Illegal);
            }

            int forwardDirection  = (BoardUtilities.IsBlack(startPosition)) ? 1 : -1;
            int backwardDirection = (!BoardUtilities.IsKing(startPosition)) ? 0 : (BoardUtilities.IsBlack(startPosition)) ? -1 : 1;

            // check for single step along vertical axis
            //проверьте на единственный шаг вдоль вертикальной оси
            if (Math.Abs(endRow - startRow) == 1)
            {//possible walk made
             //возможная ходьба сделана
             // check if we took a walk when a jump was available
             //проверьте, прогулялись ли мы, когда скачок был доступен
                if (CanJump(board, player))
                {
                    return(MoveStatus.Illegal);
                }

                // one step along the horizontal axis and proper vertical direction movement
                // один шаг по горизонтальной оси и правильное вертикальное движение
                // men can't go backwards but kings can
                // люди не могут идти назад, но короли могут
                if ((Math.Abs(endCol - startCol) == 1) && (startRow + forwardDirection == endRow || startRow + backwardDirection == endRow))
                {
                    return(MoveStatus.Legal);
                }
            }
            else if (Math.Abs(endRow - startRow) == 2)
            {// possible jump made
             // возможный прыжок сделан
                int jumpedRow = (endRow + startRow) / 2;
                int jumpedCol = (endCol + startCol) / 2;

                if (BoardUtilities.IsOpponentPiece(player, board[jumpedRow, jumpedCol]))
                {
                    // one step along the horizontal axis and proper vertical direction movement
                    // один шаг по горизонтальной оси и правильное вертикальное движение
                    // men can't go backwards but kings can
                    // люди не могут идти назад, но короли могут
                    if ((Math.Abs(endCol - startCol) == 2) && (startRow + forwardDirection * 2 == endRow || startRow + backwardDirection * 2 == endRow))
                    {
                        return(MoveStatus.Incomplete);
                    }
                }
            }

            return(MoveStatus.Illegal);
        }
        /// <summary>Generate captures list for the piece at the given location</summary>
        /// <param name="moves">stores the list of moves generated</param>
        /// <param name="locations">list of parent locations</param>
        /// <param name="board">the board state</param>
        /// <param name="piece">the piece</param>
        /// <param name="row">the row of the piece</param>
        /// <param name="col">the column of the piece</param>
        /// <param name="dx">the horizontal direction</param>
        /// <param name="dy">the vertical direction</param>
        /// <returns><c>true</c> if capture available</returns>
        private static bool GetCaptures(ICollection <Move> moves, IList <Location> locations, IBoard board, Piece piece, int row, int col, int dx, int dy)
        {
            int endRow  = row + dy * 2;
            int endCol  = col + dx * 2;
            int jumpRow = row + dy;
            int jumpCol = col + dx;

            // jump available
            if (InBounds(endRow, endCol, board) && BoardUtilities.AreOpponents(piece, board[jumpRow, jumpCol]) && BoardUtilities.IsEmpty(board[endRow, endCol]))
            {
                locations.Add(new Location(endRow, endCol));
                board[row, col]         = Piece.None;
                board[jumpRow, jumpCol] = Piece.None;
                board[endRow, endCol]   = piece;

                bool  captureAvailable = false;
                int[] directions       = { -1, 1 }; // {down/right, up/left}
                int   yStartIndex      = (BoardUtilities.IsKing(piece) || BoardUtilities.IsWhite(piece)) ? 0 : 1;
                int   yEndIndex        = (BoardUtilities.IsKing(piece) || BoardUtilities.IsBlack(piece)) ? 1 : 0;

                for (int idxY = yStartIndex; idxY <= yEndIndex; idxY++)
                {
                    foreach (int t in directions)
                    {
                        bool result = GetCaptures(
                            moves, new List <Location>(locations),
                            board.Copy(), piece,
                            endRow, endCol, t, directions[idxY]
                            );
                        captureAvailable = captureAvailable || result;
                    }
                }


                if ((!captureAvailable) && (locations.Count > 1))
                {
                    Move move = new Move();
                    foreach (Location location in locations)
                    {
                        move.AddMoves(location);
                    }

                    moves.Add(move);
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }