用java编写一个华容道程序,要求使用swing
时间: 2024-02-15 15:02:10 浏览: 88
以下是一个简单的华容道程序示例,使用了 Java 的 Swing 框架:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class HuarongDao extends JFrame implements ActionListener {
private JButton[][] buttons;
private JPanel boardPanel;
private JButton resetButton;
private int[][] board;
public HuarongDao() {
super("华容道");
// 初始化界面
boardPanel = new JPanel(new GridLayout(4, 5));
buttons = new JButton[4][5];
board = new int[4][5];
resetButton = new JButton("重新开始");
// 添加按钮和监听器
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
buttons[i][j] = new JButton();
buttons[i][j].addActionListener(this);
boardPanel.add(buttons[i][j]);
}
}
resetButton.addActionListener(this);
// 布局界面
setLayout(new BorderLayout());
add(boardPanel, BorderLayout.CENTER);
add(resetButton, BorderLayout.SOUTH);
// 初始化游戏状态
resetGame();
// 设置窗口属性
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
// 重新开始游戏
private void resetGame() {
board[0][0] = 1;
board[0][1] = 1;
board[0][2] = 1;
board[0][3] = 2;
board[0][4] = 2;
board[1][0] = 3;
board[1][1] = 3;
board[1][2] = 4;
board[1][3] = 5;
board[1][4] = 2;
board[2][0] = 3;
board[2][1] = 3;
board[2][2] = 4;
board[2][3] = 5;
board[2][4] = 2;
board[3][0] = 6;
board[3][1] = 6;
board[3][2] = 7;
board[3][3] = 7;
board[3][4] = 8;
updateBoard();
}
// 更新游戏面板
private void updateBoard() {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
if (board[i][j] == 0) {
buttons[i][j].setText("");
} else {
buttons[i][j].setText("" + board[i][j]);
}
}
}
}
// 处理按钮点击事件
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
// 重新开始游戏
if (source == resetButton) {
resetGame();
return;
}
// 查找点击的按钮
int row = -1, col = -1;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
if (source == buttons[i][j]) {
row = i;
col = j;
break;
}
}
}
// 移动棋子
if (row >= 0 && col >= 0) {
int val = board[row][col];
if (val == 0) {
return;
}
// 向左移动
if (col > 0 && board[row][col - 1] == 0) {
board[row][col] = 0;
board[row][col - 1] = val;
}
// 向右移动
else if (col < 4 && board[row][col + 1] == 0) {
board[row][col] = 0;
board[row][col + 1] = val;
}
// 向上移动
else if (row > 0 && board[row - 1][col] == 0) {
board[row][col] = 0;
board[row - 1][col] = val;
}
// 向下移动
else if (row < 3 && board[row + 1][col] == 0) {
board[row][col] = 0;
board[row + 1][col] = val;
}
// 更新界面
updateBoard();
}
}
public static void main(String[] args) {
new HuarongDao();
}
}
```
这个示例程序创建了一个 4 行 5 列的按钮面板,用于模拟华容道游戏的棋盘。每个按钮上显示了对应的棋子编号,按钮的点击事件被用于实现棋子的移动。在程序中,使用了 Java 的 Swing 框架来实现界面的布局和按钮的响应。
阅读全文