用java开发一个扫雷游戏,需要源代码
时间: 2023-02-09 12:37:32 浏览: 72
扫雷游戏是一个经典的游戏,在 Java 中可以使用 Swing 或 JavaFX 等图形界面工具包来开发。
下面是一个简单的扫雷游戏的示例代码,使用了 Swing 来实现图形界面。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MineSweeper extends JFrame {
private int rows;
private int cols;
private int mines;
private JButton[][] buttons;
private boolean[][] minesMap;
private boolean[][] revealed;
public MineSweeper(int rows, int cols, int mines) {
this.rows = rows;
this.cols = cols;
this.mines = mines;
this.buttons = new JButton[rows][cols];
this.minesMap = new boolean[rows][cols];
this.revealed = new boolean[rows][cols];
// Generate mines map
for (int i = 0; i < mines; i++) {
int row = (int) (Math.random() * rows);
int col = (int) (Math.random() * cols);
if (!minesMap[row][col]) {
minesMap[row][col] = true;
} else {
i--;
}
}
// Create buttons
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
JButton button = new JButton();
button.addMouseListener(new ButtonListener(i, j));
buttons[i][j] = button;
add(button);
}
}
setTitle("Mine Sweeper");
setLayout(new GridLayout(rows, cols));
setSize(cols * 50, rows * 50);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new MineSweeper(10, 10, 10);
}
private class ButtonListener extends MouseAdapter {
private int row;
private int col;
public ButtonListener(int row, int col) {
this.row = row;
this.col = col;
}
@Override
public void mouseClicked(MouseEvent e) {
JButton button = (JButton) e.getSource();
if (e.getButton() == MouseEvent.BUTTON1) {
if (minesMap[row][col]) {
button.setText("X");
} else {
button.setText(Integer.toString(countAdjacentMines(row, col)));
}
revealed[row][col] = true;
} else