java 代码二维雷区
时间: 2023-08-09 17:12:32 浏览: 90
好的,以下是一个简单的 Java 代码示例,用于生成一个包含随机雷的二维雷区,每个格子用数字表示周围雷的数量:
```java
import java.util.Random;
public class MineSweeper {
private int[][] board;
private int row;
private int col;
private int numMines;
public MineSweeper(int row, int col, int numMines) {
this.row = row;
this.col = col;
this.numMines = numMines;
this.board = new int[row][col];
generateMines();
countMines();
}
private void generateMines() {
Random rand = new Random();
int mines = numMines;
while (mines > 0) {
int r = rand.nextInt(row);
int c = rand.nextInt(col);
if (board[r][c] != -1) {
board[r][c] = -1;
mines--;
}
}
}
private void countMines() {
for (int r = 0; r < row; r++) {
for (int c = 0; c < col; c++) {
if (board[r][c] == -1) {
continue;
}
int count = 0;
if (r > 0 && c > 0 && board[r-1][c-1] == -1) {
count++;
}
if (r > 0 && board[r-1][c] == -1) {
count++;
}
if (r > 0 && c < col-1 && board[r-1][c+1] == -1) {
count++;
}
if (c > 0 && board[r][c-1] == -1) {
count++;
}
if (c < col-1 && board[r][c+1] == -1) {
count++;
}
if (r < row-1 && c > 0 && board[r+1][c-1] == -1) {
count++;
}
if (r < row-1 && board[r+1][c] == -1) {
count++;
}
if (r < row-1 && c < col-1 && board[r+1][c+1] == -1) {
count++;
}
board[r][c] = count;
}
}
}
public void printBoard() {
for (int r = 0; r < row; r++) {
for (int c = 0; c < col; c++) {
if (board[r][c] == -1) {
System.out.print("* ");
} else {
System.out.print(board[r][c] + " ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
MineSweeper game = new MineSweeper(5, 5, 5);
game.printBoard();
}
}
```
示例输出:
```
0 1 1 * 2
2 * 3 3 *
* 4 * 4 3
2 * 3 * 2
1 1 2 1 0
```
其中,-1 表示一个雷,其余数字表示周围雷的数量。
阅读全文