如何做幻灯片拼图中的代码。关于JAVA

如何做幻灯片拼图中的代码。关于JAVA,java,slide,sliding-tile-puzzle,Java,Slide,Sliding Tile Puzzle,*首先,我的英语不好,请试着理解我。 我想创建幻灯片益智游戏,但我不了解滑动块的方法和单击幻灯片事件的方法。我是说鼠标器 现在我只有GUI了 public PGWindow() { JFrame frame = new JFrame("SlidePuzzle"); JPanel Board = new JPanel(); Board.setLayout(new GridLayout(3, 3)); Font fn = new Font("Tahoma", Font

*首先,我的英语不好,请试着理解我。 我想创建幻灯片益智游戏,但我不了解滑动块的方法和单击幻灯片事件的方法。我是说鼠标器 现在我只有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);
}

谢谢您的帮助。

我不习惯使用Java GUI,但希望这些提示能帮助您实现所需

假设有人点击第8块。单击事件将被触发,它应该调用有效滑动块的方法

您必须构建一些方法slideBlockint 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
 }
希望这有帮助

这意味着您的变量行将从0变为gridLength-1,即forint row=0;行<网格长度-1;划船++