简体   繁体   中英

Having trouble making tiles swap positions - bejeweled

I'm fairly new to Java and I'm having a problem with arrays in a game I am creating, which is similar to Bejeweled.

In this game, I have one class called Tile, which represents one colored tile on the board, along with its column and row (integers)on the board. I have another class for the board, called Board, that manages these tiles in a 2D array of integers, organized by column and row.

My problem occurs I swap two tiles on the screen. When this happens, their columns and rows are swapped, but the array that they are saved in does not recognize this change. On the screen, everything looks fine. The two tiles will switch positions.

For instance, if I have two adjacent tiles that I want to switch, at (column0, row0) and (column1, row0) . In my array of tiles, these are tiles array[0][0] and array[1][0] . When I switch them, the first tile is now at the second tile's old position, and the second tile is now at the first tile's old position. However, the first tile is still recognized as array[0][0] , even though it should now be array[1][0] .

The significance of this is that my program will not recognize three consecutive tiles with the same color, and therefore it will not clear them from the board. Is there anything I can do to fix this?

If you have any suggestions at all, that would be great. Thank you.

Not sure what exactly is wrong from your description. The code should look similar to this:

class Tile {
  int col;
  int row;
  void setPos(int newCol, int newRow) {
    col = newCol;
    row = newRow;
}

class Board {
  Tile[][] array;

  void swap(int col0, int row0, int col1, int row1) {
    // Get hold of the tile objects to swap
    Tile tile0 = array[col0][row0];
    Tile tile1 = array[col1][row1];

    // Swap the positions stored in the tile objects
    tile0.setPos(col1, row1);
    tile1.setPos(col0, row0); 

    // Swap the tile objects in the array
    array[col0][row0] = tile1;
    array[col1][row1] = tile0;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM