java扫雷代码
时间: 2023-07-02 12:13:45 浏览: 72
java 扫雷代码
以下是一个简单的 Java 扫雷游戏代码示例:
```java
import java.util.Random;
import java.util.Scanner;
public class Minesweeper {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
System.out.println("欢迎来到扫雷游戏!");
// 设置雷区大小
System.out.print("请输入雷区的行数:");
int rows = scanner.nextInt();
System.out.print("请输入雷区的列数:");
int cols = scanner.nextInt();
// 设置雷数
System.out.print("请输入雷数:");
int mines = scanner.nextInt();
// 初始化雷区
int[][] board = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
board[i][j] = 0;
}
}
// 随机布雷
int count = 0;
while (count < mines) {
int x = random.nextInt(rows);
int y = random.nextInt(cols);
if (board[x][y] == 0) {
board[x][y] = -1;
count++;
}
}
// 计算每个格子周围的雷数
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (board[i][j] == -1) {
continue;
}
int numMines = 0;
for (int k = i - 1; k <= i + 1; k++) {
for (int l = j - 1; l <= j + 1; l++) {
if (k < 0 || k >= rows || l < 0 || l >= cols) {
continue;
}
if (board[k][l] == -1) {
numMines++;
}
}
}
board[i][j] = numMines;
}
}
// 开始游戏
int[][] revealed = new int[rows][cols];
boolean gameover = false;
while (!gameover) {
// 打印当前状态
System.out.println("当前状态:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (revealed[i][j] == 0) {
System.out.print("# ");
} else if (revealed[i][j] == 1) {
System.out.print(board[i][j] + " ");
} else if (revealed[i][j] == 2) {
System.out.print("* ");
}
}
System.out.println();
}
// 输入下一步操作
System.out.print("请输入操作(格式:x y r/l):");
int x = scanner.nextInt();
int y = scanner.nextInt();
String op = scanner.next();
// 执行操作
if (op.equals("r")) {
if (board[x][y] == -1) {
System.out.println("你输了!");
gameover = true;
} else {
revealed[x][y] = 1;
}
} else if (op.equals("l")) {
if (board[x][y] == -1) {
revealed[x][y] = 2;
} else {
System.out.println("你输了!");
gameover = true;
}
} else {
System.out.println("无效操作!");
}
// 判断是否胜利
int countRevealed = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (revealed[i][j] == 1) {
countRevealed++;
}
}
}
if (countRevealed == rows * cols - mines) {
System.out.println("你赢了!");
gameover = true;
}
}
scanner.close();
}
}
```
该代码实现了一个简单的扫雷游戏,包括设置雷区大小和雷数、随机布雷、计算每个格子周围的雷数、开始游戏、执行操作、判断胜负等功能。其中,用二维数组 `board` 存储雷区,-1 表示有雷,其他数字表示周围的雷数;用二维数组 `revealed` 存储已经揭开的格子,0 表示未揭开,1 表示已揭开,2 表示已标记为雷。
阅读全文