java写一个扫雷程序
时间: 2023-12-21 19:04:29 浏览: 189
java编写的一个扫雷程序
好的,下面是 Java 实现的扫雷程序的基本思路:
1. 创建一个 n×n 的二维数组作为雷区,并将所有格子的值设为 0。
2. 随机生成 m 个雷的位置,并将这些位置在雷区中的格子的值设为 -1。
3. 对于每个不是雷的格子,计算它周围 8 个格子中雷的个数,并将该格子的值设为雷的个数。
4. 监听用户点击事件,如果用户点击到了雷,游戏结束;如果用户点击到了非雷的格子,将该格子的状态改为已点开,并展开该格子周围 8 个没有被点开的格子;如果所有非雷的格子都被点开,游戏胜利。
5. 显示雷区和用户点击情况,直到游戏结束。
下面是具体的代码实现:
```java
import java.util.Random;
import java.util.Scanner;
public class Minesweeper {
private int[][] board;
private int n, m;
private boolean[][] opened;
private boolean gameOver = false;
public Minesweeper(int n, int m) {
this.n = n;
this.m = m;
board = new int[n][n];
opened = new boolean[n][n];
// 初始化雷区
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
board[i][j] = 0;
opened[i][j] = false;
}
}
// 随机生成 m 个雷
Random rand = new Random();
for (int i = 0; i < m; i++) {
int x = rand.nextInt(n);
int y = rand.nextInt(n);
if (board[x][y] == -1) {
i--;
} else {
board[x][y] = -1;
}
}
// 计算每个非雷格子周围的雷数
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == -1) {
continue;
}
int count = 0;
for (int k = i - 1; k <= i + 1; k++) {
for (int l = j - 1; l <= j + 1; l++) {
if (k >= 0 && k < n && l >= 0 && l < n && board[k][l] == -1) {
count++;
}
}
}
board[i][j] = count;
}
}
}
public void play() {
Scanner scanner = new Scanner(System.in);
while (!gameOver) {
printBoard();
System.out.print("请输入要扫描的格子的横坐标: ");
int x = scanner.nextInt();
System.out.print("请输入要扫描的格子的纵坐标: ");
int y = scanner.nextInt();
if (x < 0 || x >= n || y < 0 || y >= n) {
System.out.println("坐标不合法,请重新输入!");
continue;
}
if (board[x][y] == -1) {
gameOver = true;
System.out.println("很遗憾,你点到雷了,游戏结束!");
} else {
openCell(x, y);
if (checkWin()) {
gameOver = true;
System.out.println("恭喜,你赢了!");
}
}
}
printBoard();
}
private void openCell(int x, int y) {
if (opened[x][y]) {
return;
}
opened[x][y] = true;
if (board[x][y] == 0) {
for (int i = x - 1; i <= x + 1; i++) {
for (int j = y - 1; j <= y + 1; j++) {
if (i >= 0 && i < n && j >= 0 && j < n) {
openCell(i, j);
}
}
}
}
}
private boolean checkWin() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (!opened[i][j] && board[i][j] != -1) {
return false;
}
}
}
return true;
}
private void printBoard() {
System.out.print(" ");
for (int j = 0; j < n; j++) {
System.out.print(" " + j);
}
System.out.println();
for (int i = 0; i < n; i++) {
System.out.print(i);
for (int j = 0; j < n; j++) {
if (!opened[i][j]) {
System.out.print(" -");
} else if (board[i][j] == -1) {
System.out.print(" x");
} else {
System.out.print(" " + board[i][j]);
}
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
Minesweeper game = new Minesweeper(10, 10);
game.play();
}
}
```
你可以根据需要对代码进行修改和扩展,以实现更高级的扫雷游戏。
阅读全文