Example #1
0
        /// <summary>
        /// Raises mouse down event
        /// </summary>
        /// <param name="e">The mouse event args</param>
        protected override void OnMouseDown(MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                int position = GetPosition(e.Location);
                if (position > 0)
                {
                    Piece piece = board[position];

                    if (!gameStarted)
                    {
                        Player humanPlayer    = BoardUtilities.GetPlayer(piece);
                        Player computerPlayer = BoardUtilities.GetOpponent(humanPlayer);
                        presenter.SetComputer(humanPlayer, false);
                        presenter.SetComputer(computerPlayer, true);
                        presenter.StartGame();
                    }

                    bool locked = ((blackLocked && BoardUtilities.IsBlack(piece)) || (whiteLocked && BoardUtilities.IsWhite(piece)));

                    if ((!locked) && (piece != Piece.None))
                    {
                        int offset = SquareSize / 2;
                        floatingPiece.X        = e.X - offset;
                        floatingPiece.Y        = e.Y - offset;
                        floatingPiece.Position = position;
                        Cursor = GrabCursor;
                        this.RefreshBoard();
                    }
                    System.Diagnostics.Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "clicked: {0}, piece={1}", position, piece));
                }
            }

            base.OnMouseClick(e);
        }
Example #2
0
        /// <summary>
        /// GetWalks - Получить прогулки
        /// Get availables walks
        /// Получить доступные прогулки
        /// </summary>
        /// <param name="moves">
        /// Walk moves will be added to the collection
        /// Ходовые ходы будут добавлены в коллекцию
        /// </param>
        /// <param name="board">
        /// the board state
        /// состояние правления
        /// </param>
        /// <param name="player">
        /// the player
        /// игрок
        /// </param>
        private static void GetWalks(ICollection <Move> moves, IBoard board, Player player)
        {
            for (int pos = 1; pos <= BoardConstants.LightSquareCount; pos++)
            {
                Piece    piece    = board[pos];
                Location location = Location.FromPosition(pos);
                int      row      = location.Row;
                int      col      = location.Col;

                if (BoardUtilities.IsOwner(player, piece))
                {
                    int forwardDirection  = (BoardUtilities.IsBlack(piece)) ? 1 : -1;
                    int backwardDirection = (!BoardUtilities.IsKing(piece)) ? 0 : (BoardUtilities.IsBlack(piece)) ? -1 : 1;

                    GetWalks(moves, board, row, col, forwardDirection, -1);
                    GetWalks(moves, board, row, col, forwardDirection, 1);

                    if (backwardDirection != 0)
                    {
                        GetWalks(moves, board, row, col, backwardDirection, -1);
                        GetWalks(moves, board, row, col, backwardDirection, 1);
                    }
                }
            }
        }
Example #3
0
    List <Unit[]> getSurroundingMatch4s(Unit u)
    {
        List <Unit[]> candidatesGroups = new List <Unit[]> ();

        Unit[] topRightGroup    = BoardUtilities.getmatch4Units_towards_onTable(u, new Vector2Int(1, 1), unitsTable);
        Unit[] topleftGroup     = BoardUtilities.getmatch4Units_towards_onTable(u, new Vector2Int(-1, 1), unitsTable);
        Unit[] bottomRightGroup = BoardUtilities.getmatch4Units_towards_onTable(u, new Vector2Int(1, -1), unitsTable);
        Unit[] bottomLeftGroup  = BoardUtilities.getmatch4Units_towards_onTable(u, new Vector2Int(-1, -1), unitsTable);

        if (topRightGroup != null)
        {
            candidatesGroups.Add(topRightGroup);
        }
        if (topleftGroup != null)
        {
            candidatesGroups.Add(topleftGroup);
        }
        if (bottomRightGroup != null)
        {
            candidatesGroups.Add(bottomRightGroup);
        }
        if (bottomLeftGroup != null)
        {
            candidatesGroups.Add(bottomLeftGroup);
        }

        return(candidatesGroups);
    }
Example #4
0
        //считает количество фигур на поле
        private static void NumberPiece(IBoard board, out int whiteKings, out int blackKings, out int whiteMen, out int blackMen)
        {
            whiteKings = 0;
            blackKings = 0;
            whiteMen   = 0;
            blackMen   = 0;
            for (int pos = 1; pos <= BoardConstants.LightSquareCount; pos++)
            {
                Piece piece = board[pos];

                if (BoardUtilities.IsPiece(piece))
                {
                    switch (piece)
                    {
                    case Piece.BlackMan:
                        blackMen++;
                        break;

                    case Piece.WhiteMan:
                        whiteMen++;
                        break;

                    case Piece.BlackKing:
                        blackKings++;
                        break;

                    case Piece.WhiteKing:
                        whiteKings++;
                        break;
                    }
                }
            }
        }
Example #5
0
        /// <summary>
        /// Raises MouseUp event
        /// </summary>
        /// <param name="e">The mouse event</param>
        protected override void OnMouseUp(MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (floatingPiece.Active)
                {
                    Piece piece  = board[floatingPiece.Position];
                    bool  locked = ((blackLocked && BoardUtilities.IsBlack(piece)) || (whiteLocked && BoardUtilities.IsWhite(piece)));

                    if (!locked)
                    {
                        Move move     = null;
                        int  position = GetPosition(e.Location);
                        if ((position > 0) && (board[position] == Piece.None))
                        {
                            board[position] = board[floatingPiece.Position];
                            board[floatingPiece.Position] = Piece.None;
                            move = new Move(floatingPiece.Position, position);
                        }

                        floatingPiece.Position = FloatingPiece.INVALID_POSITION;

                        Cursor = HandSelectCursor;
                        this.RefreshBoard();

                        if (move != null)
                        {
                            OnMoveInput(move);
                        }
                    }
                }
            }

            base.OnMouseUp(e);
        }
        /// <summary>
        ///  MakeMove - Сделать ход
        /// Attempt to make the specified move on the board starting at the given position if present
        /// Попытка сделать указанное движение на доске, начиная с заданной позиции, если присутствует
        /// </summary>
        /// <param name="move">
        /// The move
        /// Движение
        /// </param>
        /// <param name="startPosition">
        /// The starting position of the move if this move is a jump continuation
        /// Начальная позиция хода, если этот ход является продолжением прыжка
        /// </param>
        public void MakeMove(Move move, int?startPosition)
        {
            const int INVALID_POSITION = -1;
            int       origin           = move.Origin ?? INVALID_POSITION;

            if (origin == INVALID_POSITION)
            {
                HandleInvalidMove(move, "Move contains no steps");//ход не содержит шагов
            }
            else if ((startPosition.HasValue) && (origin != startPosition.Value))
            {
                HandleInvalidMove(move, "You must finish jump");//Вы должны закончить прыжок
            }
            else
            {
                Piece      piece      = board[origin];
                Player     player     = BoardUtilities.GetPlayer(piece);
                PlayerInfo playerInfo = GetPlayerInfo(player);
                MoveStatus moveStatus = MoveStatus.Illegal;
                move = boardRules.ResolveAmbiguousMove(board, move);

                if (piece == Piece.None)
                {
                    HandleInvalidMove(move, "No piece selected");//Не выбрано ни одного предмета
                }
                else if (playerInfo != turn)
                {
                    HandleInvalidMove(move, string.Format(CultureInfo.InvariantCulture, "Not {0}'s turn", playerInfo.Player.ToString()));//Не ход {0}
                }
                else if ((moveStatus = boardRules.IsValidMove(board, move, turn.Player)) == MoveStatus.Illegal)
                {
                    HandleInvalidMove(move, string.Format(CultureInfo.InvariantCulture, "Invalid move: {0}", move));//  Неверный ход: {0}
                }
                else if (!boardRules.ApplyMove(board, move))
                {
                    HandleInvalidMove(move, string.Format(CultureInfo.InvariantCulture, "Unable to apply move move: {0}", move));//     Невозможно применить ход перемещения: {0}
                }
                else
                {
                    view.SetBoardState(board.Copy());

                    // swap turn if the player has a complete move (no jumps)
                    // меняем ход, если у игрока полный ход (без прыжков)
                    if (moveStatus == MoveStatus.Incomplete)
                    {
                        // at this point the move was valid and hence must have a destination
                        // в этот момент перемещение было допустимым и, следовательно, должно иметь пункт назначения
                        view.SetMoveStartPosition(move.Destination.Value);
                    }
                    else
                    {
                        view.SetMoveStartPosition(null);
                        view.LockPlayer(turn.Player, true);
                        this.SwapTurn();
                    }
                    this.GameStep();
                }
            }
        }
Example #7
0
    void updateTableAndTotalCompletions(Unit u)
    {
        //		print (u);
        BoardUtilities.update_OneUnitCoord_onTable(u, originalTable);
//		updateCoord_onOriginalTable (u, originalTable);
        totalCompletions++;
        //		print (totalCompletions);
    }
Example #8
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);
        }
      /// <summary>
      /// Attempt to make the specified move on the board starting at the given position if present
      /// </summary>
      /// <param name="move">The move</param>
      /// <param name="startPosition">The starting position of the move if this move is a jump continuation</param>
      public void MakeMove(Move move, int? startPosition)
      {
         const int INVALID_POSITION = -1;
         int origin = move.Origin ?? INVALID_POSITION;

         if (origin == INVALID_POSITION)
         {
            HandleInvalidMove(move, "Move contains no steps");
         }
         else if ((startPosition.HasValue) && (origin != startPosition.Value))
         {
            HandleInvalidMove(move, "You must finish jump");
         }
         else
         {
            Piece piece = board[origin];
            Player player = BoardUtilities.GetPlayer(piece);
            PlayerInfo playerInfo = GetPlayerInfo(player);
            MoveStatus moveStatus = MoveStatus.Illegal;
            move = boardRules.ResolveAmbiguousMove(board, move);

            if (piece == Piece.None)
            {
               HandleInvalidMove(move, "No piece selected");
            }
            else if (playerInfo != turn)
            {
               HandleInvalidMove(move, string.Format(CultureInfo.InvariantCulture, "Not {0}'s turn", playerInfo.Player.ToString()));
            }
            else if ((moveStatus = boardRules.IsValidMove(board, move, turn.Player)) == MoveStatus.Illegal)
            {
               HandleInvalidMove(move, string.Format(CultureInfo.InvariantCulture, "Invalid move: {0}", move));
            }
            else if (!boardRules.ApplyMove(board, move))
            {
               HandleInvalidMove(move, string.Format(CultureInfo.InvariantCulture, "Unable to apply move move: {0}", move));
            }
            else
            {
               view.SetBoardState(board.Copy());

               // swap turn if the player has a complete move (no jumps)
               if (moveStatus == MoveStatus.Incomplete)
               {
                  // at this point the move was valid and hence must have a destination
                  view.SetMoveStartPosition(move.Destination.Value);
               }
               else
               {
                  view.SetMoveStartPosition(null);
                  view.LockPlayer(turn.Player, true);
                  this.SwapTurn();
               }
               this.GameStep();
            }
         }
      }
Example #10
0
        public virtual Move CanMove(BoardUtilities utils, Point origin, Point destination)
        {
            Move move = GetValidMove(origin, destination);

            if (utils.Obstructed(origin, destination))
            {
                move = null;
            }
            return(move);
        }
Example #11
0
    public void OnDrag(PointerEventData eventData)
    {
//		Debug.Log ("Dragging");
//		Debug.Log (eventData.pointerCurrentRaycast.worldPosition);
        pointerWorldPosition = eventData.pointerCurrentRaycast.worldPosition;
        insideBoardBoundary  = BoardUtilities.pointerInsideBoundary(pointerWorldPosition, gameBoardBoundary);
        if (onDragging != null && InputEnabled && insideBoardBoundary)
        {
            onDragging(pointerWorldPosition);
        }
    }
Example #12
0
 public static void GetCaptures(ICollection <Move> moves, IBoard board, Player player)
 {
     // Get captures
     for (int pos = 1; pos <= BoardConstants.LightSquareCount; pos++)
     {
         if (BoardUtilities.IsOwner(player, board[pos]))
         {
             Location location = Location.FromPosition(pos);
             GetCaptures(moves, board.Copy(), location.Row, location.Col);
         }
     }
 }
Example #13
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 #14
0
    private GameObject SetSpace(int x, int y)
    {
        GameObject spaceGo;

        try {
            spaceGo = Instantiate(spaceDictionary[boardLayout[x, y]], BoardUtilities.CoordToWorld(x, y), Quaternion.Euler(90, 0, 0));
        } catch {
            spaceGo = Instantiate(emptySpace, BoardUtilities.CoordToWorld(x, y), Quaternion.Euler(90, 0, 0));
        }
        spaceGo.GetComponent <ISpace>().Initialise(x, y);
        return(spaceGo);
    }
        /// <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);
            }
        }
Example #16
0
    /// <summary>
    /// Sets a space at the x and y values.
    /// </summary>
    /// <param name="space">The space prefab to set.</param>
    /// <param name="x">The x coordinate.</param>
    /// <param name="y">The y coordinate.</param>
    /// <returns>The set space.</returns>
    public GameObject SetSpace(GameObject space, int x, int y)
    {
        GameObject spaceGo;

        try {
            spaceGo = Instantiate(space, BoardUtilities.CoordToWorld(x, y), Quaternion.Euler(90, 0, 0));
            spaceGo.GetComponent <ISpace>().Initialise(x, y);
        } catch {
            spaceGo = Instantiate(emptySpace, BoardUtilities.CoordToWorld(x, y), Quaternion.Euler(90, 0, 0));
        }

        return(spaceGo);
    }
Example #17
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 #18
0
    public static Unit getSameIdUnit_Towards_onTable(Unit u1, Vector2Int direction, Unit[,] table)
    {
        Unit tempUnit = BoardUtilities.getUnitOnTable(u1.CurrentColumn + direction.x, u1.CurrentRow + direction.y, table);

        if (tempUnit)
        {
            if (BoardUtilities.hasSameID(u1, tempUnit))
            {
                return(tempUnit);
            }
        }
        return(null);
    }
 private void GameStep(int? startPosition)
 {
    if (!boardRules.IsGameOver(board, turn.Player))
    {
       view.LockPlayer(Player.Black, true);
       view.LockPlayer(Player.White, true);
       view.ShowPlayerChange(turn.Player);
       this.PromptMove(startPosition);
    }
    else
    {
       this.OnGameOver(BoardUtilities.GetOpponent(turn.Player), turn.Player);
    }
 }
Example #20
0
 void doDragStart(Vector3 v)
 {
     screenRay = Camera.main.ScreenPointToRay(v);
     Physics2D.GetRayIntersectionNonAlloc(screenRay, hitResults);
     //Debug.Log(hitResults[0].collider);
     if (hitResults[0].collider != null)
     {
         pointerWorldPosition = hitResults[0].point;
         insideBoardBoundary  = BoardUtilities.pointerInsideBoundary(pointerWorldPosition, gameBoardBoundary);
         if (insideBoardBoundary)
         {
             //Debug.Log("fire");
             fireOnDragStart(hitResults[0].collider.gameObject);
         }
     }
 }
Example #21
0
 public void OnBeginDrag(PointerEventData eventData)
 {
     if (InputEnabled)
     {
         //Debug.Log ("Drag Begin");
         pointerWorldPosition = eventData.pointerCurrentRaycast.worldPosition;
         insideBoardBoundary  = BoardUtilities.pointerInsideBoundary(pointerWorldPosition, gameBoardBoundary);
         if (insideBoardBoundary)
         {
             if (onDragStart != null)
             {
                 onDragStart(eventData.pointerCurrentRaycast.gameObject, pointerWorldPosition);
             }
         }
     }
 }
Example #22
0
        //TODO:
        private int MiniMax(ref Move bestMove, IBoard board, Player player, int ply, int depth, TimeSpan timeout, DateTime startTime)
        {
            if (depth <= 0)
            {
                // reached ply level
                // достиг уровня слоя
                return(Evaluate(board, player));
            }
            else if (forceMove)
            {
                return(int.MinValue);
            }

            ICollection <Move> moves = CheckerMoveRules.GetAvailableMoves(board, player);

            if ((moves == null) || (moves.Count == 0))
            {
                // reached leaf
                // достиг листа
                return(Evaluate(board, player));
            }


            int    bestScore = int.MinValue;
            Player opponent  = BoardUtilities.GetOpponent(player);
            IBoard boardCopy = board.Copy();

            foreach (Move move in moves)
            {
                CheckerMoveRules.UpdateBoard(boardCopy, move);
                int score = -MiniMax(ref bestMove, boardCopy, opponent, ply, depth - 1, timeout, startTime);
                boardCopy.Copy(board);// undo move //отменить движение

                if (depth == ply)
                {
                    System.Diagnostics.Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Move: {0}.  Score: {1}", move, score.ToString(CultureInfo.InvariantCulture)));
                    if ((bestMove == null) || (score > bestScore))
                    {
                        bestMove = move;
                    }
                }

                bestScore = Math.Max(bestScore, score);
            }

            return(bestScore);
        }
Example #23
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 #24
0
        /// <summary>
        /// Raises the MouseMove event
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseMove(MouseEventArgs e)
        {
            if ((!moveAnimator.Running) && (floatingPiece.Active))
            {
                Piece piece  = board[floatingPiece.Position];
                bool  locked = ((blackLocked && BoardUtilities.IsBlack(piece)) || (whiteLocked && BoardUtilities.IsWhite(piece)));

                if (!locked)
                {
                    int offset = SquareSize / 2;
                    floatingPiece.X = e.X - offset;
                    floatingPiece.Y = e.Y - offset;
                    this.RefreshBoard();
                }
            }

            base.OnMouseMove(e);
        }
Example #25
0
        /// <summary>Generate captures list for the piece at the given location</summary>
        /// <param name="moves">capture moves will be added to the collection</param>
        /// <param name="board">the board state</param>
        /// <param name="row">the row of the piece</param>
        /// <param name="col">the column of the piece</param>
        private static void GetCaptures(ICollection <Move> moves, IBoard board, int row, int col)
        {
            Piece            piece     = board[row, col];
            IList <Location> locations = new List <Location>();

            locations.Add(new Location(row, col));

            if (BoardUtilities.IsKing(piece) || BoardUtilities.IsBlack(piece))
            {                                                                                             // go up
                GetCaptures(moves, new List <Location>(locations), board.Copy(), piece, row, col, -1, 1); // right
                GetCaptures(moves, new List <Location>(locations), board.Copy(), piece, row, col, 1, 1);  // left
            }
            if (BoardUtilities.IsKing(piece) || BoardUtilities.IsWhite(piece))
            {                                                                                              // go down
                GetCaptures(moves, new List <Location>(locations), board.Copy(), piece, row, col, -1, -1); // right
                GetCaptures(moves, new List <Location>(locations), board, piece, row, col, 1, -1);         // left
            }
        }
Example #26
0
        /// <summary>
        /// CanJump - Может прыгать
        /// Check the player jump any pieces on the board
        /// Проверьте игрока, прыгайте любые фигуры на доске
        /// </summary>
        /// <param name="board">
        /// the board state
        /// состояние правления
        /// </param>
        /// <param name="player">
        /// the player with the turn
        /// игрок с терном
        /// </param>
        /// <returns><code>true</code>
        /// if the player can make a jump
        /// если игрок может сделать прыжок
        /// </returns>
        static bool CanJump(IBoard board, Player player)
        {
            for (int row = 0; row < board.Rows; row++)
            {
                for (int col = 0; col < board.Cols; col++)
                {
                    if (BoardUtilities.IsPiece(board[row, col]) &&
                        (BoardUtilities.GetPlayer(board[row, col]) == player) &&
                        CanJump(board, row, col)
                        )
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Example #27
0
    void switchUnit_Towards(Vector2Int direction)
    {
        Unit targetUnit = BoardUtilities.getUnitOnTable(cueUnit.thisUnit.CurrentColumn + direction.x, cueUnit.thisUnit.CurrentRow + direction.y, unitsTable);

        if (targetUnit == null)
        {
            //Debug.Log("out!");
            throw new System.Exception("invalid unit to switch towards");
        }
        else
        {
            /*only need to move the target unit, the cue unit is following the pointer*/
            targetUnit.moveTo(new Vector2Int(-direction.x, -direction.y));
            //BoardUtilities.switchUnitsCoord(cueUnit.thisUnit, targetUnit, unitsTable);//+++++++++++

            //          tryMakeBlock (cueUnit);
            //          tryMakeBlock (targetUnit);
        }
    }
Example #28
0
 void doDragging(Vector3 v)
 {
     if (hitResults[0].collider != null)
     {
         //Debug.Log(hitResults[0].collider);
         pointerWorldPosition = Camera.main.ScreenToWorldPoint(v);
         /*update z, so it is the same as the boundary and the units on board*/
         pointerWorldPosition.z = tableUnitZ;
         insideBoardBoundary    = BoardUtilities.pointerInsideBoundary(pointerWorldPosition, gameBoardBoundary);
         if (insideBoardBoundary)
         {
             fireOnDragging(pointerWorldPosition);
         }
         else
         {
             //Debug.Log("out of boundary");
             doDragEnd();
         }
     }
 }
Example #29
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 #30
0
        /// <summary>
        /// CanJump - Может прыгать
        /// Check if piece at position can jump
        /// Проверьте, может ли кусок в положении прыгать
        /// </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>
        /// <returns><code>true</code>
        /// if the piece can jump
        /// если кусок может прыгать
        /// </returns>
        static bool CanJump(IBoard board, int row, int col)
        {
            Piece piece = board[row, col];

            if (!BoardUtilities.IsPiece(piece))
            {
                return(false);
            }

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

            return(CanJump(board, row, col, forwardDirection, -1) ||
                   CanJump(board, row, col, forwardDirection, 1) ||
                   (backwardDirection != 0 &&
                    (
                        CanJump(board, row, col, backwardDirection, -1) ||
                        CanJump(board, row, col, backwardDirection, 1)
                    )
                   ));
        }