I'm currently creating a 4x4 picture slide puzzle through the use of a 2D array of buttons being laid out in a Gridpane. My method to 'slide' the pieces when clicked is through calling a procedure I named buttonClick(), and by using if statements to check whether the piece clicked by the user has a blank button next to it. If it does, the grid positions of the two are swapped. However I've been running into problems with getting my IF statements running properly. I've been trying to use the Row and Column indexes to identify where the blank is in the grid and whether its next to the button clicked but my logic is clearly flawed. Some pieces refuse to move, some that shouldn't move end up moving, etc. What I essentially need is some new IF statements so that a button clicked that is next to the blank is moved. *note - my x and y are opposite to what they should be for some reason. So the x is vertical and y is horizontal. Here is what I had for my procedure:
public void buttonClick(Button[][] arr, int x, int y, WritableImage[][] newImage) {
int temp;
System.out.println("Button " + GridPane.getRowIndex(arr[x][y]) + "," + GridPane.getColumnIndex(arr[x][y]));
System.out.println("Blank : " + GridPane.getRowIndex(arr[3][3]) + "," + GridPane.getColumnIndex(arr[3][3]));
if (setWin == false) {
if (x < 3) {
if (GridPane.getColumnIndex(arr[x + 1][y]).equals(GridPane.getColumnIndex(arr[3][3]))) { //arr[3][3] = blank button
System.out.println("run1");
temp = GridPane.getRowIndex(arr[x][y]);
GridPane.setRowIndex(arr[x][y], GridPane.getRowIndex(arr[3][3]));
GridPane.setRowIndex(arr[3][3], temp);
}
}
if (y < 3) {
if (GridPane.getRowIndex(arr[x][y + 1]).equals(GridPane.getRowIndex(arr[3][3]))) {
System.out.println("run2");
temp = GridPane.getColumnIndex(arr[x][y]);
GridPane.setColumnIndex(arr[x][y], GridPane.getColumnIndex(arr[3][3]));
GridPane.setColumnIndex(arr[3][3], temp);
}
}
}
}
Aucun commentaire:
Enregistrer un commentaire