Java图形与事件处理,应用键盘事件,编写一个“拼图”游戏程序。
时间: 2024-02-03 11:15:32 浏览: 20
好的,下面是一个简单的拼图游戏程序示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PuzzleGame extends JFrame implements ActionListener {
private JButton[][] puzzleButtons;
private JButton newGameButton;
private JPanel puzzlePanel, controlPanel;
private int emptyRow, emptyCol;
public PuzzleGame() {
setTitle("Puzzle Game");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// 创建拼图面板
puzzlePanel = new JPanel(new GridLayout(4, 4));
puzzleButtons = new JButton[4][4];
for (int row = 0; row < 4; row++) {
for (int col = 0; col < 4; col++) {
puzzleButtons[row][col] = new JButton("" + (row * 4 + col + 1));
puzzlePanel.add(puzzleButtons[row][col]);
puzzleButtons[row][col].addActionListener(this);
}
}
emptyRow = 3;
emptyCol = 3;
puzzleButtons[emptyRow][emptyCol].setVisible(false);
add(puzzlePanel, BorderLayout.CENTER);
// 创建控制面板
controlPanel = new JPanel(new FlowLayout());
newGameButton = new JButton("New Game");
newGameButton.addActionListener(this);
controlPanel.add(newGameButton);
add(controlPanel, BorderLayout.SOUTH);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// 点击拼图按钮
for (int row = 0; row < 4; row++) {
for (int col = 0; col < 4; col++) {
if (e.getSource() == puzzleButtons[row][col]) {
if ((row == emptyRow && Math.abs(col - emptyCol) == 1) ||
(col == emptyCol && Math.abs(row - emptyRow) == 1)) {
// 移动拼图
puzzleButtons[emptyRow][emptyCol].setText(puzzleButtons[row][col].getText());
puzzleButtons[row][col].setVisible(false);
puzzleButtons[emptyRow][emptyCol].setVisible(true);
emptyRow = row;
emptyCol = col;
}
}
}
}
// 点击新游戏按钮
if (e.getSource() == newGameButton) {
shufflePuzzle();
}
}
// 洗牌拼图
private void shufflePuzzle() {
for (int i = 0; i < 100; i++) {
int random = (int)(Math.random() * 4);
int row = emptyRow, col = emptyCol;
if (random == 0 && emptyRow > 0) {
row--;
} else if (random == 1 && emptyRow < 3) {
row++;
} else if (random == 2 && emptyCol > 0) {
col--;
} else if (random == 3 && emptyCol < 3) {
col++;
}
if (row != emptyRow || col != emptyCol) {
puzzleButtons[emptyRow][emptyCol].setText(puzzleButtons[row][col].getText());
puzzleButtons[row][col].setVisible(false);
puzzleButtons[emptyRow][emptyCol].setVisible(true);
emptyRow = row;
emptyCol = col;
}
}
}
public static void main(String[] args) {
new PuzzleGame();
}
}
```
这个程序创建了一个4x4的拼图面板,每个拼图按钮上面有一个数字。点击拼图按钮会把它与空白按钮交换位置,从而移动拼图。点击“New Game”按钮会洗牌拼图。