我用java写一个最基本的拼图游戏 姐妹
时间: 2023-05-20 16:00:58 浏览: 100
非常好的问题!您可以使用 Java Swing 库来创建一个基本的拼图游戏。以下是一个简单的示例代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PuzzleGame extends JFrame {
private JPanel panel;
private JButton[][] buttons;
private int[][] puzzle;
private int emptyRow, emptyCol;
public PuzzleGame() {
setTitle("拼图游戏");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel(new GridLayout(3, 3));
buttons = new JButton[3][3];
puzzle = new int[3][3];
// 初始化拼图
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
puzzle[i][j] = i * 3 + j + 1;
if (i == 2 && j == 2) {
puzzle[i][j] = 0;
emptyRow = i;
emptyCol = j;
}
}
}
// 创建按钮并添加到面板
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
buttons[i][j] = new JButton(String.valueOf(puzzle[i][j]));
buttons[i][j].addActionListener(new ButtonListener(i, j));
panel.add(buttons[i][j]);
}
}
add(panel);
setVisible(true);
}
private class ButtonListener implements ActionListener {
private int row, col;
public ButtonListener(int row, int col) {
this.row = row;
this.col = col;
}
public void actionPerformed(ActionEvent e) {
if (row == emptyRow && col == emptyCol) {
return;
}
if (row == emptyRow) {
int diff = col - emptyCol;
int step = diff / Math.abs(diff);
for (int i = emptyCol + step; i != col + step; i += step) {
puzzle[row][i - step] = puzzle[row][i];
buttons[row][i - step].setText(String.valueOf(puzzle[row][i - step]));
}
puzzle[row][col] = 0;
emptyCol = col;
} else if (col == emptyCol) {
int diff = row - emptyRow;
int step = diff / Math.abs(diff);
for (int i = emptyRow + step; i != row + step; i += step) {
puzzle[i - step][col] = puzzle[i][col];
buttons[i - step][col].setText(String.valueOf(puzzle[i - step][col]));
}
puzzle[row][col] = 0;
emptyRow = row;
}
if (isSolved()) {
JOptionPane.showMessageDialog(null, "恭喜你,拼图完成!");
}
}
}
private boolean isSolved() {
int count = 1;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (puzzle[i][j] != count % 9) {
return false;
}
count++;
}
}
return true;
}
public static void main(String[] args) {
new PuzzleGame();
}
}
```
这个程序创建了一个 3x3 的面板,每个按钮上显示一个数字。当用户点击一个按钮时,程序会检查该按钮是否与空白按钮相邻,如果是,则交换它们的位置。当所有按钮都按照正确的顺序排列时,程序会弹出一个恭喜消息。
希望这个示例能够帮助您开始编写自己的拼图游戏!
阅读全文