扫雷游戏是一种经典的计算机游戏,它要求玩家在一个网格中清除所有非地雷方块,同时避开地雷。下面是一个简单的Java实现,包括游戏界面、逻辑和用户交互。
int[][] grid
:表示游戏网格boolean[][] visited
:表示方块是否被访问过Random random
:用于生成随机地雷import java.util.Random;
import javax.swing.*;
public class Minesweeper {
private static final int SIZE = 10;
private static final int MINES = 10;
private int[][] grid;
private boolean[][] visited;
private Random random;
private JLabel[][] displayGrid;
private JButton[] buttons;
public Minesweeper() {
grid = new int[SIZE][SIZE];
visited = new boolean[SIZE][SIZE];
random = new Random();
displayGrid = new JLabel[SIZE][SIZE];
buttons = new JButton[SIZE * SIZE];
initializeGrid();
initializeDisplay();
initializeButtons();
}
private void initializeGrid() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
grid[i][j] = random.nextInt(SIZE * SIZE) < MINES ? -1 : 0;
}
}
}
private void initializeDisplay() {
JFrame frame = new JFrame("Minesweeper");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(SIZE, SIZE));
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
displayGrid[i][j] = new JLabel();
displayGrid[i][j].setPreferredSize(new Dimension(50, 50));
displayGrid[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK));
frame.add(displayGrid[i][j]);
}
}
frame.pack();
frame.setVisible(true);
}
private void initializeButtons() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(SIZE * SIZE, 1));
for (int i = 0; i < SIZE * SIZE; i++) {
buttons[i] = new JButton();
buttons[i].addActionListener(e -> onClick(i / SIZE, i % SIZE));
buttonPanel.add(buttons[i]);
}
JFrame frame = (JFrame) displayGrid[0][0].getParent();
frame.add(buttonPanel, BorderLayout.SOUTH);
}
private void onClick(int row, int col) {
if (grid[row][col] == -1) {
JOptionPane.showMessageDialog(null, "Game Over!");
return;
}
visited[row][col] = true;
displayGrid[row][col].setText(String.valueOf(countAdjacentMines(row, col)));
if (countAdjacentMines(row, col) == 0 && grid[row][col] == 0) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (!visited[i][j] && grid[i][j] == 0) {
onClick(i, j);
}
}
}
}
}
private int countAdjacentMines(int row, int col) {
int count = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (i == 0 && j == 0) continue;
int newRow = row + i;
int newCol = col + j;
if (newRow >= 0 && newRow < SIZE && newCol >= 0 && newCol < SIZE && grid[newRow][newCol] == -1) {
count++;
}
}
}
return count;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Minesweeper());
}
}
initializeGrid()
:随机生成地雷和非地雷方块。initializeDisplay()
:创建游戏界面,包括网格和按钮。initializeButtons()
:初始化按钮并添加点击事件监听器。onClick(int row, int col)
:处理玩家点击事件,更新显示并递归清除非地雷方块。countAdjacentMines(int row, int col)
:计算指定位置的相邻地雷数量。将上述代码保存为Minesweeper.java
,然后使用以下命令编译和运行:
javac Minesweeper.java
java Minesweeper
这将启动一个简单的扫雷游戏窗口,玩家可以通过点击方块来清除它们,并显示周围地雷的数量。