Hi I am trying to create a GUI game where you slide your player to obsticals in order to get to the middle. The basic assignment rules are as follows

The world should be represented using a 5 x 5 grid. Empty spaces, obstacles, the destination, and the player should be easily identifiable. You can use different colors or images for each one of them.

The player should be able to move using both buttons and keyboard input. Also, there should be a “retry” option to reset the level back to the initial configuration.

There should be at least three sample levels.

How do I move the player button?

import javax.swing.*;
import java.awt.*;

public class project1 extends JFrame {

    JButton[][] square = new JButton[5][5];
    private JButton player, obstical1, obstical2, obstical3, center;


    project1() {
        super("Maze");

        JPanel p = new JPanel(new GridLayout(5,5));
        for(int i = 0; i < 5; i++) {
            for(int j = 0; j < 5; j++) {
                square[i][j] = new JButton();
                p.add(square[i][j]);
            }
        }
        center = square[2][2];
        center.setBackground(Color.RED);

        player = square[4][4];
        player.setBackground(Color.BLUE);

        obstical1 = square[0][0];
        obstical1.setBackground(Color.ORANGE);

        obstical2 = square[1][3];
        obstical2.setBackground(Color.ORANGE);

        obstical3 = square[3][1];
        obstical3.setBackground(Color.ORANGE);

        add(p, BorderLayout.CENTER);

        setSize(200, 240);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new project1();
    }
}

There's no easy way to move the actual JButtons in a grid. What you can do is to keep a track of the x,y coordinates of the player (etc) so you can change the text or icon of the appropriate JButton as the player moves. In pseudo code, for example

player moves right:
   set text of button[x][y] to "empty" // player is not here any more
   add 1 to x
   set text of button[x][y] to "player" // this is where the player is now

Thanks james. I was able to get it moving but I am not sure how I am going to make it so the player can only slide to an obstical like lunar lockout.

You didn't show all your code, so I don't know what else you have done. Ideally you would have a [5][5] array of data somewhere that contains the current state of the puzzle and which allows you to see where the empty square is etc. YOur GUI button[5][5] should just display the data - if you try to combine the data, logic, and the GUI in one GUI array it will get much more complicated and dfficult.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.