Reputation: 147
I've gotten an assignment to create a 15 puzzle game. Where the player only can swap a tile of number if the blank tile is next to it horizontally or vertically. I believed that my solution to this was to create a Gridlayout 4x4. And a 2d array to find the location of a specific Button so I then can swap the buttons locations with each other if that makes any sense...
The problem is when I use panel.add(button0, row, col)
. It doesn't have x and y locations like a 2d array has, which I thought it did. It caused the button to end up on wrong places.
How can I use what I have so far to solve my problem or do I have to start over?
Thanks in advance!
class GameTest extends JFrame implements ActionListener{
JPanel panel = new JPanel();
JButton[][] buttons = new JButton[4][4];
JButton button0 = new JButton("EMPTY");
public GameTest() {
add(panel);
setBackground(Color.RED);
panel.setLayout(new GridLayout(4,4));
int i = 1;
for (int row = 0; row < buttons.length; row++) {
for (int col = 0; col < buttons.length; col++ ) {
if (row == 3 && col == 3) {
buttons[row][col] = button0;
panel.add(buttons[row][col]);
buttons[row][col].setBackground(Color.WHITE);
buttons[row][col].setName("button0");
}
else{
buttons[row][col] = new JButton(i + "");
panel.add(buttons[row][col]);
buttons[row][col].addActionListener(this);
buttons[row][col].setBackground(Color.RED);
buttons[row][col].setName("button" + i);
buttons[row][col].setFont(new Font("Arial", Font.PLAIN, 30));
i++;
}
}
}
setCursor(new Cursor(Cursor.HAND_CURSOR));
setResizable(false);
setLocation(500,200);
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public boolean isSwappable(JButton button) {
for (int row = 0; row < buttons.length; row++) {
for (int col = 0; col < buttons.length; col++ ) {
if (buttons[row][col] == button) {
if (row != 3 ) {
if (buttons[row+1][col] == button0){
return true;
}
}
else if (col != 3){
if (buttons[row][col+1] == button0){
return true;
}
}
else if (row != 0) {
if (buttons[row-1][col] == button0) {
return true;
}
}
else if (col != 0) {
if ( buttons[row][col-1] == button0){
return true;
}
}
}
}
}
return false;
}
@Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton)e.getSource();
if (isSwappable(source)) {
int x = 0;
int y = 0;
JButton buttonTemp = null;
JButton buttonTemp0 = null;
for (int row = 0; row < buttons.length; row++) {
for (int col = 0; col < buttons.length; col++) {
if (buttons[row][col] == source) {
buttonTemp = source;
buttonTemp0 = button0;
x = row;
y = col;
}
if (buttons[row][col] == button0) {
buttons[row][col] = buttonTemp;
buttons[x][y] = buttonTemp0;
}
}
}
}
}
}
Upvotes: 1
Views: 331
Reputation: 324118
It doesn't have x and y locations like a 2d array has,
Correct, it is a 1D array.
So you need to calculate the index using the 2D information.
So for example if you want to swap location of row = 1 and column = 2
The index would be:
int index = (row * 4) + column;
Upvotes: 2