用java编写扫雷的代码
时间: 2024-10-14 12:15:56 浏览: 28
编写扫雷游戏的基本步骤包括创建一个二维数组表示雷区、随机生成地雷位置、显示初始雷区状态、处理用户的点击操作以及判断是否胜利或失败等。这里是一个简单的示例,展示如何用Java创建基本的游戏框架:
```java
import java.util.Random;
public class Minesweeper {
private int[][] board;
private int rows;
private int cols;
private int mines;
public Minesweeper(int size, int numMines) {
this.rows = size;
this.cols = size;
this.mines = numMines;
// 初始化雷区
Random random = new Random();
for (int i = 0; i < mines; ) {
int x = random.nextInt(rows);
int y = random.nextInt(cols);
if (!isMine(x, y)) { // 确保不在已放雷的位置上
board[x][y] = MINE;
i++;
}
}
// 初始化非雷格子为0
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (board[i][j] != MINE) {
board[i][j] = 0;
}
}
}
}
private boolean isMine(int x, int y) {
return x >= 0 && x < rows && y >= 0 && y < cols && board[x][y] == MINE;
}
public void reveal(int x, int y) {
if (board[x][y] == MINE) {
System.out.println("哎呀,踩到雷了!");
} else if (board[x][y] == COUNT) {
System.out.println(board[x][y]);
// 如果周围有雷,递归揭示周围的数字
for (int dx = -1; dx <= 1; dx++) {
for (int dy = -1; dy <= 1; dy++) {
if (dx != 0 || dy != 0) {
reveal(x + dx, y + dy);
}
}
}
} else {
board[x][y] = countAdjacentMines(x, y);
}
}
private int countAdjacentMines(int x, int y) {
int count = 0;
for (int dx = -1; dx <= 1; dx++) {
for (int dy = -1; dy <= 1; dy++) {
if (dx != 0 || dy != 0) {
if (isMine(x + dx, y + dy)) {
count++;
}
}
}
}
return count;
}
public static void main(String[] args) {
Minesweeper game = new Minesweeper(10, 10);
for (int[] row : game.board) {
for (int cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
// 用户开始探索
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("请输入行和列(例如 5 7): ");
try {
int x = scanner.nextInt();
int y = scanner.nextInt();
game.reveal(x, y);
} catch (Exception e) {
System.out.println("输入错误,请再次尝试!");
}
}
}
}
// 定义常量如雷(MINE)和计数器(COUNT)
private static final int MINE = 9; // 表示地雷
```
这个例子展示了如何初始化雷区、揭示数字并检测用户是否踩雷。实际游戏中还需要添加更多的交互性和错误处理。
阅读全文