Exemple #1
0
  public void move(int direction) {
    saveUndoState();
    aGrid.cancelAnimations();
    // 0: up, 1: right, 2: down, 3: left
    if (lose || won) {
      return;
    }
    Cell vector = getVector(direction);
    List<Integer> traversalsX = buildTraversalsX(vector);
    List<Integer> traversalsY = buildTraversalsY(vector);
    boolean moved = false;

    prepareTiles();

    for (int xx : traversalsX) {
      for (int yy : traversalsY) {
        Cell cell = new Cell(xx, yy);
        Tile tile = grid.getCellContent(cell);

        if (tile != null) {
          Cell[] positions = findFarthestPosition(cell, vector);
          Tile next = grid.getCellContent(positions[1]);

          if (next != null && next.getValue() == tile.getValue() && next.getMergedFrom() == null) {
            Tile merged = new Tile(positions[1], tile.getValue() * 2);
            Tile[] temp = {tile, next};
            merged.setMergedFrom(temp);

            grid.insertTile(merged);
            grid.removeTile(tile);

            // Converge the two tiles' positions
            tile.updatePosition(positions[1]);

            int[] extras = {xx, yy};
            aGrid.startAnimation(
                merged.getX(),
                merged.getY(),
                MOVE_ANIMATION,
                MOVE_ANIMATION_TIME,
                0,
                extras); // Direction: 0 = MOVING MERGED
            aGrid.startAnimation(
                merged.getX(),
                merged.getY(),
                MERGE_ANIMATION,
                SPAWN_ANIMATION_TIME,
                MOVE_ANIMATION_TIME,
                null);

            // Update the score
            score = score + merged.getValue();
            highScore = Math.max(score, highScore);

            // The mighty 2048 tile
            if (merged.getValue() == 2048) {
              won = true;
              endGame();
            }
          } else {
            moveTile(tile, positions[0]);
            int[] extras = {xx, yy, 0};
            aGrid.startAnimation(
                positions[0].getX(),
                positions[0].getY(),
                MOVE_ANIMATION,
                MOVE_ANIMATION_TIME,
                0,
                extras); // Direction: 1 = MOVING NO MERGE
          }

          if (!positionsEqual(cell, tile)) {
            moved = true;
          }
        }
      }
    }

    if (moved) {
      addRandomTile();
      checkLose();
    }
    mView.resyncTime();
    mView.postInvalidate();
  }