java扫雷小游戏源代码
时间: 2023-11-10 14:03:14 浏览: 146
以下是简单的 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();
int rows, columns, bombs;
System.out.print("Enter number of rows: ");
rows = scanner.nextInt();
System.out.print("Enter number of columns: ");
columns = scanner.nextInt();
System.out.print("Enter number of bombs: ");
bombs = scanner.nextInt();
boolean[][] board = new boolean[rows][columns];
int[][] counts = new int[rows][columns];
// randomly place bombs
for (int i = 0; i < bombs; i++) {
int row, column;
do {
row = random.nextInt(rows);
column = random.nextInt(columns);
} while (board[row][column]);
board[row][column] = true;
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
if (dr != 0 || dc != 0) {
int r = row + dr;
int c = column + dc;
if (r >= 0 && r < rows && c >= 0 && c < columns) {
counts[r][c]++;
}
}
}
}
}
boolean[][] revealed = new boolean[rows][columns];
int remaining = rows * columns - bombs;
while (remaining > 0) {
// print the board
for (int c = 0; c < columns; c++) {
System.out.print(" " + c);
}
System.out.println();
for (int r = 0; r < rows; r++) {
System.out.print(r);
for (int c = 0; c < columns; c++) {
if (revealed[r][c]) {
if (board[r][c]) {
System.out.print("* ");
} else {
System.out.print(counts[r][c] + " ");
}
} else {
System.out.print(". ");
}
}
System.out.println();
}
// ask for the next move
int row, column;
do {
System.out.print("Enter row and column: ");
row = scanner.nextInt();
column = scanner.nextInt();
} while (row < 0 || row >= rows || column < 0 || column >= columns || revealed[row][column]);
revealed[row][column] = true;
remaining--;
// handle the move
if (board[row][column]) {
System.out.println("Boom! Game over.");
break;
} else if (counts[row][column] == 0) {
// reveal all neighbors
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
if (dr != 0 || dc != 0) {
int r = row + dr;
int c = column + dc;
if (r >= 0 && r < rows && c >= 0 && c < columns && !revealed[r][c]) {
revealed[r][c] = true;
remaining--;
}
}
}
}
}
}
if (remaining == 0) {
System.out.println("Congratulations! You win!");
}
scanner.close();
}
}
```
阅读全文