用java写个扫雷游戏
时间: 2023-03-24 11:04:57 浏览: 66
当然可以!下面是一份简单的 Java 代码,实现了一个扫雷游戏的基本功能:
```
import java.util.Scanner;
public class MineSweeper {
static int n = 10;
static int m = 10;
static int[][] mine = new int[n][m];
static boolean[][] open = new boolean[n][m];
static int[][] around = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
public static void main(String[] args) {
// 初始化地图
initMap();
// 游戏主循环
while (true) {
// 显示地图
showMap();
// 玩家输入
System.out.print("请输入您要打开的格子的坐标(格式为 x y):");
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y = sc.nextInt();
// 检查输入是否合法
if (x < 0 || x >= n || y < 0 || y >= m) {
System.out.println("输入的坐标不合法,请重新输入!");
continue;
}
// 打开格子
open(x, y);
// 判断是否踩到地雷
if (mine[x][y] == 9) {
System.out.println("很不幸,您踩到了地雷!游戏结束!");
break;
}
// 判断是否胜利
if (checkWin()) {
System.out.println("恭喜您,您赢得了游戏!");
break;
}
}
}
// 初始化地图
public static void initMap() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
mine[i][j] = (int) (Math.random() * 10 % 10);
if (mine[i][j] == 9) {
mine[i][j] = 9;
} else {
int count = 0;
for (int k = 0; k < around.length; k++) {
相关推荐
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![apk](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)