*首先我的英语不好请尝试理解我。 我想创建幻灯片拼图游戏,但我不了解滑块的方法和方法点击幻灯片事件。(我的意思是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);
}
感谢您的帮助。
答案 0 :(得分: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
}
希望这有帮助!