基于JAVA写一个扫雷小游戏
时间: 2023-12-06 15:05:33 浏览: 97
JAVA写的扫雷小游戏
4星 · 用户满意度95%
好的,下面是一个简单的基于Java的扫雷小游戏示例代码,供您参考。
```java
import java.util.Scanner;
import java.util.Random;
public class Minesweeper {
private int[][] board; // 存储格子状态和雷的位置
private boolean[][] visible; // 存储格子是否被翻开
private int n; // 游戏区域大小
private int mines; // 雷的数量
private int remaining; // 剩余未翻开的格子数
// 初始化游戏
public Minesweeper(int n, int mines) {
this.n = n;
this.mines = mines;
remaining = n * n - mines;
board = new int[n][n];
visible = new boolean[n][n];
// 初始化雷的位置
Random rand = new Random();
for (int i = 0; i < mines; i++) {
int x = rand.nextInt(n);
int y = rand.nextInt(n);
if (board[x][y] != -1) {
board[x][y] = -1;
} else {
i--;
}
}
// 计算每个方格周围雷的数量
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] != -1) {
int count = 0;
for (int di = -1; di <= 1; di++) {
for (int dj = -1; dj <= 1; dj++) {
int ni = i + di;
int nj = j + dj;
if (ni >= 0 && ni < n && nj >= 0 && nj < n && board[ni][nj] == -1) {
count++;
}
}
}
board[i][j] = count;
}
}
}
}
// 根据坐标翻开格子
public boolean reveal(int x, int y) {
if (board[x][y] == -1) {
return false;
}
visible[x][y] = true;
remaining--;
if (board[x][y] == 0) {
for (int di = -1; di <= 1; di++) {
for (int dj = -1; dj <= 1; dj++) {
int ni = x + di;
int nj = y + dj;
if (ni >= 0 && ni < n && nj >= 0 && nj < n && !visible[ni][nj]) {
reveal(ni, nj);
}
}
}
}
return true;
}
// 打印游戏状态
public void print() {
System.out.print(" ");
for (int j = 0; j < n; j++) {
System.out.print(j + " ");
}
System.out.println();
for (int i = 0; i < n; i++) {
System.out.print(i + " ");
for (int j = 0; j < n; j++) {
if (visible[i][j]) {
if (board[i][j] == -1) {
System.out.print("* ");
} else {
System.out.print(board[i][j] + " ");
}
} else {
System.out.print(". ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入游戏区域大小: ");
int n = scanner.nextInt();
System.out.print("请输入雷的数量: ");
int mines = scanner.nextInt();
Minesweeper game = new Minesweeper(n, mines);
game.print();
while (game.remaining > 0) {
System.out.print("请输入要翻开的格子坐标(x y): ");
int x = scanner.nextInt();
int y = scanner.nextInt();
if (!game.reveal(x, y)) {
System.out.println("你输了!");
return;
}
game.print();
}
System.out.println("你赢了!");
}
}
```
这个示例代码实现了一个基于控制台的扫雷小游戏,玩家可以输入坐标来翻开格子,并且会打印出当前游戏状态。还有很多可以改进的地方,比如添加计时、排行榜等功能。
阅读全文