给我一个使用了Java swing的扫雷游戏Java源码
时间: 2024-02-04 10:03:08 浏览: 24
好的,下面是一个使用Java Swing实现的扫雷游戏的源码示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class MineSweeper implements ActionListener {
private JFrame mainFrame;
private JPanel mainPanel, buttonPanel;
private JButton[][] buttonArray;
private int[][] mineArray;
private boolean[][] clickedArray;
private int size, numMines;
private Random random;
public MineSweeper(int size, int numMines) {
this.size = size;
this.numMines = numMines;
this.random = new Random();
this.mineArray = new int[size][size];
this.clickedArray = new boolean[size][size];
mainFrame = new JFrame("Mine Sweeper");
mainPanel = new JPanel();
buttonPanel = new JPanel();
buttonArray = new JButton[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
buttonArray[i][j] = new JButton();
buttonArray[i][j].setPreferredSize(new Dimension(25, 25));
buttonArray[i][j].addActionListener(this);
buttonPanel.add(buttonArray[i][j]);
}
}
mainPanel.add(buttonPanel);
mainFrame.add(mainPanel);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.pack();
mainFrame.setVisible(true);
generateMines(numMines);
}
private void generateMines(int numMines) {
int count = 0;
while (count < numMines) {
int x = random.nextInt(size);
int y = random.nextInt(size);
if (mineArray[x][y] == 0) {
mineArray[x][y] = 1;
count++;
}
}
}
public void actionPerformed(ActionEvent event) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (event.getSource() == buttonArray[i][j]) {
if (mineArray[i][j] == 1) {
buttonArray[i][j].setText("M");
JOptionPane.showMessageDialog(mainFrame, "You lose!");
System.exit(0);
} else {
int count = countMines(i, j);
buttonArray[i][j].setText("" + count);
clickedArray[i][j] = true;
if (count == 0) {
expand(i, j);
}
if (checkWin()) {
JOptionPane.showMessageDialog(mainFrame, "You win!");
System.exit(0);
}
}
}
}
}
}
private int countMines(int x, int y) {
int count = 0;
for (int i = x - 1; i <= x + 1; i++) {
for (int j = y - 1; j <= y + 1; j++) {
if (i >= 0 && i < size && j >= 0 && j < size) {
if (mineArray[i][j] == 1) {
count++;
}
}
}
}
return count;
}
private void expand(int x, int y) {
for (int i = x - 1; i <= x + 1; i++) {
for (int j = y - 1; j <= y + 1; j++) {
if (i >= 0 && i < size && j >= 0 && j < size) {
if (!clickedArray[i][j]) {
int count = countMines(i, j);
buttonArray[i][j].setText("" + count);
clickedArray[i][j] = true;
if (count == 0) {
expand(i, j);
}
}
}
}
}
}
private boolean checkWin() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (!clickedArray[i][j]) {
if (mineArray[i][j] != 1) {
return false;
}
}
}
}
return true;
}
public static void main(String[] args) {
new MineSweeper(10, 10);
}
}
```
这个扫雷游戏的源码使用了Java Swing库来实现图形界面,使用了JButton来表示每个格子,使用了JOptionPane来弹出游戏胜利或失败的提示框。游戏开始时,程序会生成一个size * size的二维数组,其中1表示雷,0表示非雷。玩家需要点击每个格子来揭示其内容,如果揭示到了雷则游戏失败,如果揭示到的格子周围有雷,则格子上会显示雷的数量。当玩家已经揭示了所有非雷格子时,游戏胜利。