Example #1
0
  /**
   * Moves this piece to a new position on the board.
   *
   * @param newRow The destination row.
   * @param newColumn The destination column.
   * @return <code>false</code> if the destination is not a legal board position, or if the piece is
   *     already moving.
   */
  public boolean moveTo(int newRow, int newColumn) {
    if (!board.isLegalPosition(newRow, newColumn)) return false;
    if (moving) return false;
    int startX = board.columnToX(column);
    int startY = board.rowToY(row);
    int finishX = board.columnToX(newColumn);
    int finishY = board.rowToY(newRow);
    int changeInX = finishX - startX;
    int changeInY = finishY - startY;
    Rectangle oldRect = getRectangle();
    Rectangle newRect = new Rectangle(oldRect);

    // compensate for squares being slightly different sizes
    oldRect.width += 2;
    newRect.width += 2;
    oldRect.height += 2;
    newRect.height += 2;

    // Move smoothly towards new position
    moving = true;
    board.moveToTop(this);
    int deltaRow = Math.abs(row - newRow);
    int deltaColumn = Math.abs(column - newColumn);
    int distance = Math.max(deltaRow, deltaColumn) + Math.min(deltaRow, deltaColumn) / 2;
    int numberOfSteps = distance * FRAME_RATE / getSpeed();

    for (int i = 1; i <= numberOfSteps; i++) {
      oldRect.x = x;
      oldRect.y = y;
      x = startX + (i * changeInX) / numberOfSteps;
      y = startY + (i * changeInY) / numberOfSteps;
      newRect.x = x;
      newRect.y = y;
      board.getJPanel().paintImmediately(oldRect.union(newRect));
      //            redraw(oldRect.union(newRect));

      try {
        Thread.sleep(PAUSE_MS);
      } catch (InterruptedException e) {
        /* Deliberately empty */
      }
    }
    moving = false;
    if (canMoveTo(newRow, newColumn)) {
      changePosition(newRow, newColumn);
    }
    redraw(oldRect.union(newRect));
    return true;
  }
Example #2
0
 /**
  * When the mouse button is pressed over a draggable piece, begins the dragging process. Only
  * one piece can be dragged at a time.
  *
  * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
  */
 @Override
 public void mousePressed(MouseEvent e) {
   board.setSelectedSquare(board.yToRow(e.getY()), board.xToColumn(e.getX()));
   Piece chosenPiece = board.findPiece(e.getX(), e.getY());
   if (chosenPiece == null) {
     return;
   }
   if (chosenPiece.isSelectable()) {
     board.setSelectedPiece(chosenPiece);
   }
   if (pieceBeingDragged != null) {
     return; // can only drag one piece at a time
   }
   if (!chosenPiece.draggable) {
     return;
   }
   pieceBeingDragged = chosenPiece;
   board = pieceBeingDragged.board;
   pieceBeingDragged.moving = true;
   board.moveToTop(pieceBeingDragged);
 }
Example #3
0
 /**
  * Ensures that this piece will be drawn on top of any other pieces in the same location on the
  * board.
  */
 public void moveToTop() {
   if (board != null) {
     board.moveToTop(this);
   }
 }