MineSweeper Java游戏代码示例325


扫雷是一款经典而令人沉迷的益智游戏,目标是清理一块雷区,而不触碰到隐藏其中的地雷。您可以使用 Java 轻松创建扫雷游戏。

以下代码示例演示了如何使用 Java 创建扫雷游戏:
```java
import ;
import ;
public class MineSweeper {
private int[][] minefield;
private int numMines;
private int numRows;
private int numCols;
private Scanner scanner;
public MineSweeper(int numRows, int numCols, int numMines) {
= numRows;
= numCols;
= numMines;
minefield = new int[numRows][numCols];
scanner = new Scanner();
}
public void generateMinefield() {
Random random = new Random();
for (int i = 0; i < numMines; i++) {
int row = (numRows);
int col = (numCols);
minefield[row][col] = -1;
}
}
public int countMines(int row, int col) {
int count = 0;
for (int i = row - 1; i = 0 && j < numCols && minefield[i][j] == -1) {
count++;
}
}
}
return count;
}
public void printMinefield() {
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
if (minefield[i][j] == -1) {
("X ");
} else {
int count = countMines(i, j);
(count + " ");
}
}
();
}
}
public boolean playGame() {
while (true) {
("Enter row and column (e.g. 0 0): ");
int row = ();
int col = ();
if (minefield[row][col] == -1) {
("Game over! You hit a mine.");
return false;
} else {
int count = countMines(row, col);
minefield[row][col] = count;
printMinefield();
if (isGameWon()) {
("Congratulations! You won the game.");
return true;
}
}
}
}
public boolean isGameWon() {
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
if (minefield[i][j] == -1) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
int numRows = 10;
int numCols = 10;
int numMines = 10;
MineSweeper game = new MineSweeper(numRows, numCols, numMines);
();
();
();
}
}
```

在以上示例中,我们创建了一个具有指定行数、列数和地雷数的扫雷游戏。主函数 `main` 调用 `MineSweeper` 类创建游戏,并逐步生成、打印和播放游戏。

如果您想自定义游戏的特性,可以调整以下参数:* `numRows`:雷区的行数
* `numCols`:雷区的列数
* `numMines`:地雷的数量

通过调整这些参数,您可以创建不同难度的游戏。

请注意,示例代码使用控制台输入/输出。您可以根据需要修改它以使用图形用户界面 (GUI) 或其他输入/输出方法。扫雷游戏的核心算法仍然适用。

2024-10-13


上一篇:数组初始化在 Java 中

下一篇:Java 数组类详解:了解数组的强大功能