扫雷-运行时先输入行数列数雷数,再布雷算雷。 并且输入多少个雷就显示多少个雷。 java
时间: 2023-08-22 09:03:27 浏览: 43
以下是一个简单的实现扫雷游戏的 Java 代码:
```
import java.util.Scanner;
public class Minesweeper {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int cols = scanner.nextInt();
System.out.print("Enter the number of mines: ");
int mines = scanner.nextInt();
int[][] board = new int[rows][cols];
// Place mines randomly on the board
for (int i = 0; i < mines; i++) {
int row = (int) (Math.random() * rows);
int col = (int) (Math.random() * cols);
if (board[row][col] == -1) {
i--;
} else {
board[row][col] = -1;
}
}
// Calculate the number of mines around each cell
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (board[row][col] != -1) {
int count = 0;
if (row > 0 && col > 0 && board[row - 1][col - 1] == -1) count++;
if (row > 0 && board[row - 1][col] == -1) count++;
if (row > 0 && col < cols - 1 && board[row - 1][col + 1] == -1) count++;
if (col > 0 && board[row][col - 1] == -1) count++;
if (col < cols - 1 && board[row][col + 1] == -1) count++;
if (row < rows - 1 && col > 0 && board[row + 1][col - 1] == -1) count++;
if (row < rows - 1 && board[row + 1][col] == -1) count++;
if (row < rows - 1 && col < cols - 1 && board[row + 1][col + 1] == -1) count++;
board[row][col] = count;
}
}
}
// Print the board
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (board[row][col] == -1) {
System.out.print("* ");
} else {
System.out.print(board[row][col] + " ");
}
}
System.out.println();
}
}
}
```
运行时,程序会提示用户输入行数、列数和雷数。然后程序会在二维数组中随机布置指定数量的地雷,并计算每个方格周围地雷的数量。最后,程序会打印出整个游戏板。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)