-2

*首先我的英语不好,请试着理解我。我想创建 Slide Puzzle 游戏,但我不了解滑动块的方法和单击滑动事件的方法。(我的意思是 MouseLister)现在我只有 GUI

public PGWindow() {
    JFrame frame = new JFrame("SlidePuzzle");
    JPanel Board = new JPanel();
    Board.setLayout(new GridLayout(3, 3));
    Font fn = new Font("Tahoma", Font.BOLD, 60);
    int Num = 1;

    for (int row = 0; row < 3; row++) {
        for (int col = 0; col < 3; col++) {
            if (Num == 9) {
                break;
            }
            else {
                Board.add(new JButton(String.valueOf(+Num))).setFont(fn);
            }
            Num++;
        }
    }

    frame.add(Board);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(600, 600);
    frame.setLocation(600, 90);
    frame.setVisible(true);
}

感谢您的帮助。

4

1 回答 1

0

我不习惯 Java GUI,但希望这些提示可以帮助您实现您想要的。

想象一下,有人点击了第 8 块,会触发一个点击事件,它应该调用有效滑动该块的方法。

您必须构建一些方法slideBlock(int blockId)来检查块是否可以移动,并且还必须在某处定义一个保存游戏状态的矩阵。

它应该开始排序,并且您必须定义一些正确打乱拼图的方法,以便存在一种用户重新排序拼图的方法。让我们看一些伪代码:

//The matrix initial state:
int[][] grid = new int[gridLength][gridLength];
int piece = 1;

//Fill the grid with the puzzle ordered:
for(0<=row<gridLength) {
        for(0<=col<gridLength) {
            if(row != gridLength - 1 && col != gridLength - 1) { //Leave last block empty
                grid[row][col] = piece
                piece++
            }
        }
 }

public void shuffle() {
        //Some shuffle that makes sense
 }

public void slideBlock(int blockId) {
        //Get the indexes where the block is, e.g. getPositions() and hold them on some vars, e.g. row, col
        boolean moved = false;

        if(row - 1 > 0 && grid[row - 1][col] == 0){  // Move block up
            grid[row - 1][col] = blockId
            moved = true;
        }
        else if(row + 1 < gridLength - 1 && grid[row + 1][col] == 0) { // Move block down
            grid[row + 1][col] = blockId
            moved = true;
        }
        else if(col - 1 > 0 && grid[row][col - 1] == 0) {  // Move block left
            grid[row][col - 1] = blockId
            moved = true;
        }
        else if(col + 1 < gridLength - 1 && grid[row][col + 1] == 0) { // Move block right
            grid[row][col + 1] = blockId
            moved = true;
        }

        if moved
            grid[row][col] = 0 // Delete the piece from old position
 }

希望这有帮助!

于 2017-11-27T18:02:28.133 回答