dinsdag 16 december 2014

How to copy and compare 2D TextureRegion Arrays ?

I am working on a "simple" shuffle puzzle in which a pictures gets divided into pieces and the pieces get shuffled.
The puzzle is solved when the player manages the shuffle all the pieces back into their original position.

I divided the original image into pieces depending on the amount of rows & columns I'd wanted to give the puzzle - that is amount of puzzle pieces horizontal and vertical - and stored each puzzle piece in a 2D TextureRegion[][] array.

Then tried to make a copy of this array, so that I could shuffle up the pieces of the original array and then compare them to check whether my puzzle pieces matched the original array (hence the puzzle would be solved).

Trying to do this I ran into two issues:
(*I have 2 2D-TexureRegion Arrays: puzzlePiecesInArray & puzzlePiecesInArrayCopy)

1. Copy an arrays content can't be done with a simple statement like:

  1.    puzzlePiecesInArrayCopy = puzzlePiecesInArray;

After I added all the puzzle pieces to my puzzlePiecesInArray this is what I tried to do, but now both pointers (array names) actually point to the same array and comparing puzzlePiecesInArrayCopy to puzzlePiecesInArray would always return true as a result.

Thus in order to create 2 identical arrays i used a for loop to get the content of each array index and store it in the array 's copy like this:
  1. for (int j = 0; j < row; j++) {
  2.         for (int i = 0; i < col; i++) {
  3.         puzzlePiecesInArrayCopy[i][j] = puzzlePiecesInArray[i][j];
  4.         }
  5. }
(later i found out I could have also done it by using Arrays.copyOf)

2. Comparing two arrays like:

  1. if (puzzlePiecesInArray == puzzlePiecesInArrayCopy) {
  2.       // puzzle is solved code here
  3.    }

doesn't work.

But i could compare individual array indexes like:

  1. if (puzzlePiecesInArray[1][2] == puzzlePiecesInArrayCopy[1][2]) {
  2.            // do something
  3.    }

But now i had to figure out a way of how to compare all the indexes AND check if ALL results would be true AND only then run the code for the puzzle being solved.

Comparing all the indexes could easily be done with a for loop, but then somehow I had to think of a way to keep track of all the result so that at the end I could check if all results where true (this is puzzle is solved!).

I look around on the web to see if I could find a way to do this more easily and i found that java has a class called Arrays that has a method "equals" that is able to check if the content of arrays are the same.
This actually didn't work, but there was another method .deepEquals(array1,array2) and this actually does the trick.

So now i could do my array comparison with a simple line of code:

  1. if (Arrays.deepEquals(puzzlePiecesInArray, puzzlePiecesInArrayCopy)){
  2.          // puzzle solved!
  3.      }


Geen opmerkingen:

Een reactie posten