现成的扫雷游戏java 代码
时间: 2023-07-09 14:30:19 浏览: 102
基于java的扫雷游戏-源代码.zip
好的,以下是一个简单的扫雷游戏 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.print("请输入雷区的边长:");
int n = scanner.nextInt();
System.out.print("请输入雷的数量:");
int m = scanner.nextInt();
int[][] minefield = new int[n][n];
int[][] showfield = new int[n][n];
// 初始化雷区
for (int i = 0; i < m; i++) {
int x = random.nextInt(n);
int y = random.nextInt(n);
if (minefield[x][y] != -1) {
minefield[x][y] = -1;
} else {
i--;
}
}
// 计算每个格子周围的雷的数量
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (minefield[i][j] != -1) {
int count = 0;
for (int k = i - 1; k <= i + 1; k++) {
for (int l = j - 1; l <= j + 1; l++) {
if (k >= 0 && k < n && l >= 0 && l < n && minefield[k][l] == -1) {
count++;
}
}
}
minefield[i][j] = count;
}
}
}
// 打印雷区
System.out.println("雷区:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (minefield[i][j] == -1) {
System.out.print("*");
} else {
System.out.print(minefield[i][j]);
}
System.out.print(" ");
}
System.out.println();
}
// 游戏开始
boolean gameOver = false;
while (!gameOver) {
System.out.print("请输入您要翻开的格子的坐标(x,y):");
int x = scanner.nextInt();
int y = scanner.nextInt();
if (minefield[x][y] == -1) {
System.out.println("您翻开了一颗雷,游戏结束!");
gameOver = true;
} else {
showfield[x][y] = minefield[x][y];
printShowfield(showfield);
if (checkWin(minefield, showfield)) {
System.out.println("您已经成功扫除了所有雷,游戏胜利!");
gameOver = true;
}
}
}
}
// 打印展示区
public static void printShowfield(int[][] showfield) {
System.out.println("展示区:");
for (int[] row : showfield) {
for (int cell : row) {
if (cell == 0) {
System.out.print("_");
} else {
System.out.print(cell);
}
System.out.print(" ");
}
System.out.println();
}
}
// 检查游戏是否胜利
public static boolean checkWin(int[][] minefield, int[][] showfield) {
for (int i = 0; i < minefield.length; i++) {
for (int j = 0; j < minefield[0].length; j++) {
if (minefield[i][j] != -1 && showfield[i][j] == 0) {
return false;
}
}
}
return true;
}
}
```
这个示例代码实现了一个简单的控制台扫雷游戏,您可以根据需要进行修改和扩展。
阅读全文