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() {

        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();
        center = square[2][2];

        player = square[4][4];

        obstical1 = square[0][0];

        obstical2 = square[1][3];

        obstical3 = square[3][1];

        add(p, BorderLayout.CENTER);

        setSize(200, 240);

    public static void main(String[] args) {
        new project1();
5 Years
Discussion Span
Last Post by JamesCherrill

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.