写一个java扫雷游戏
时间: 2023-10-30 19:09:21 浏览: 32
好的,下面是一个简单的 Java 扫雷游戏的实现:
```java
import java.util.Random;
import java.util.Scanner;
public class Minesweeper {
private static final int ROWS = 10;
private static final int COLS = 10;
private static final int MINES = 10;
public static void main(String[] args) {
boolean[][] revealed = new boolean[ROWS][COLS];
boolean[][] mines = new boolean[ROWS][COLS];
Scanner scanner = new Scanner(System.in);
Random random = new Random();
// Place mines randomly
int placedMines = 0;
while (placedMines < MINES) {
int row = random.nextInt(ROWS);
int col = random.nextInt(COLS);
if (!mines[row][col]) {
mines[row][col] = true;
placedMines++;
}
}
// Game loop
boolean gameOver = false;
while (!gameOver) {
// Print board
System.out.println(" 0 1 2 3 4 5 6 7 8 9");
System.out.println(" ---------------------");
for (int row = 0; row < ROWS; row++) {
System.out.print(row + "| ");
for (int col = 0; col < COLS; col++) {
if (!revealed[row][col]) {
System.out.print(". ");
} else if (mines[row][col]) {
System.out.print("* ");
} else {
int count = countAdjacentMines(mines, row, col);
System.out.print(count + " ");
}
}
System.out.println("|");
}
System.out.println(" ---------------------");
// Get user input
System.out.print("Enter row and column (e.g. '3 4'): ");
int row = scanner.nextInt();
int col = scanner.nextInt();
// Check if user hit a mine
if (mines[row][col]) {
gameOver = true;
revealed[row][col] = true;
System.out.println("Game over! You hit a mine.");
} else {
// Reveal square and check if game is won
revealed[row][col] = true;
boolean gameWon = true;
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
if (!revealed[r][c] && !mines[r][c]) {
gameWon = false;
break;
}
}
}
if (gameWon) {
gameOver = true;
System.out.println("Congratulations, you won!");
}
}
}
}
private static int countAdjacentMines(boolean[][] mines, int row, int col) {
int count = 0;
for (int r = row - 1; r <= row + 1; r++) {
for (int c = col - 1; c <= col + 1; c++) {
if (r >= 0 && r < ROWS && c >= 0 && c < COLS && mines[r][c]) {
count++;
}
}
}
return count;
}
}
```
这个游戏没有图形界面,只是通过命令行进行交互。玩家输入行和列的坐标,然后程序会检查该位置是否是地雷。如果是地雷,游戏结束,玩家输了。如果不是地雷,程序会展示该位置周围的地雷数量并继续等待玩家的输入。如果所有非地雷的方块都被揭露,游戏结束,玩家赢了。