/// <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); }
/// <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(); } } }
/// <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(); } } }
/// <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); }
/// <summary> /// HasMovesAvailable - Есть фильмы в наличии /// Check if the player has any more moves /// Проверьте, есть ли у игрока больше ходов /// </summary> /// <param name="board"> /// the state of the board /// состояние правления /// </param> /// <param name="player"> /// the player with the turn /// игрок с терном /// </param> /// <returns><code>true</code> /// if the player can make a move /// если игрок может сделать ход /// </returns> public static bool HasMovesAvailable(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]) && (player == BoardUtilities.GetPlayer(board[row, col]))) { if (CanWalk(board, row, col)) { return(true); } else if (CanJump(board, row, col)) { return(true); } } } } return(false); }
/// <summary> /// PerformMove - Выполнить движение /// Perform a single move /// Выполнить один ход /// </summary> /// <param name="board"> /// the board state /// состояние правления /// </param> /// <param name="startRow"> /// the start row /// начальный ряд /// </param> /// <param name="startCol"> /// the start column /// начальный столбец /// </param> /// <param name="endRow"> /// the end row /// конец строки /// </param> /// <param name="endCol"> /// the end column /// конец столбца /// </param> private static MoveStatus PerformMove(IBoard board, int startRow, int startCol, int endRow, int endCol) { MoveStatus moveStatus = IsMoveLegal(board, startRow, startCol, endRow, endCol, BoardUtilities.GetPlayer(board[startRow, startCol])); if (moveStatus != MoveStatus.Illegal) { if (Math.Abs(endRow - startRow) == 1) {//walk // ходить board[endRow, endCol] = board[startRow, startCol]; board[startRow, startCol] = Piece.None; } else {// jump piece // прыжок int jumpedRow = (startRow + endRow) / 2; int jumpedCol = (startCol + endCol) / 2; board[jumpedRow, jumpedCol] = Piece.None; board[endRow, endCol] = board[startRow, startCol]; board[startRow, startCol] = Piece.None; } if ((moveStatus == MoveStatus.Incomplete) && (!CanJump(board, endRow, endCol))) { moveStatus = MoveStatus.Legal; } // check if the piece is now a king // проверяем, является ли фигура королем if ((board[endRow, endCol] == Piece.BlackMan) && (endRow == BoardConstants.Rows - 1)) { board[endRow, endCol] = Piece.BlackKing; } else if ((board[endRow, endCol] == Piece.WhiteMan) && (endRow == 0)) { board[endRow, endCol] = Piece.WhiteKing; } } return(moveStatus); }