用Java写扫雷小游戏
时间: 2023-08-14 20:07:19 浏览: 104
JAVA写的扫雷小游戏
4星 · 用户满意度95%
好的,下面是一个简单的Java扫雷小游戏示例代码:
```java
import java.util.Random;
import java.util.Scanner;
public class MineSweeper {
private final int ROWS = 10;
private final int COLS = 10;
private final int MINES = 10;
private int[][] board;
private boolean[][] revealed;
private boolean gameOver;
public MineSweeper() {
board = new int[ROWS][COLS];
revealed = new boolean[ROWS][COLS];
gameOver = false;
initializeBoard();
}
private void initializeBoard() {
Random random = new Random();
int count = 0;
while(count < MINES) {
int row = random.nextInt(ROWS);
int col = random.nextInt(COLS);
if(board[row][col] == 0) {
board[row][col] = -1;
count++;
}
}
for(int i = 0; i < ROWS; i++) {
for(int j = 0; j < COLS; j++) {
if(board[i][j] != -1) {
int countMines = 0;
if(i > 0 && j > 0 && board[i-1][j-1] == -1) countMines++;
if(i > 0 && board[i-1][j] == -1) countMines++;
if(i > 0 && j < COLS-1 && board[i-1][j+1] == -1) countMines++;
if(j > 0 && board[i][j-1] == -1) countMines++;
if(j < COLS-1 && board[i][j+1] == -1) countMines++;
if(i < ROWS-1 && j > 0 && board[i+1][j-1] == -1) countMines++;
if(i < ROWS-1 && board[i+1][j] == -1) countMines++;
if(i < ROWS-1 && j < COLS-1 && board[i+1][j+1] == -1) countMines++;
board[i][j] = countMines;
}
}
}
}
private void reveal(int row, int col) {
if(row < 0 || row >= ROWS || col < 0 || col >= COLS || revealed[row][col]) return;
revealed[row][col] = true;
if(board[row][col] == -1) {
gameOver = true;
return;
}
if(board[row][col] == 0) {
reveal(row-1, col-1);
reveal(row-1, col);
reveal(row-1, col+1);
reveal(row, col-1);
reveal(row, col+1);
reveal(row+1, col-1);
reveal(row+1, col);
reveal(row+1, col+1);
}
}
private void displayBoard(boolean showMines) {
System.out.print(" ");
for(int j = 0; j < COLS; j++) {
System.out.print(" " + (j+1));
}
System.out.println();
for(int i = 0; i < ROWS; i++) {
System.out.print((char)('A' + i));
for(int j = 0; j < COLS; j++) {
if(revealed[i][j] || showMines) {
if(board[i][j] == -1) {
System.out.print(" *");
} else {
System.out.print(" " + board[i][j]);
}
} else {
System.out.print(" -");
}
}
System.out.println();
}
}
public void play() {
Scanner scanner = new Scanner(System.in);
while(!gameOver) {
displayBoard(false);
System.out.print("Enter row (A-J) and column (1-10): ");
String input = scanner.nextLine();
if(input.length() != 2) {
System.out.println("Invalid input, try again.");
continue;
}
int row = input.charAt(0) - 'A';
int col = input.charAt(1) - '1';
reveal(row, col);
}
displayBoard(true);
System.out.println("Game over!");
scanner.close();
}
public static void main(String[] args) {
MineSweeper game = new MineSweeper();
game.play();
}
}
```
该示例代码中包含了以下功能:
- 随机生成雷区,并计算每个方格周围的雷数。
- 支持玩家揭示方格,如果揭示到雷则游戏结束。
- 在控制台中显示当前的雷区状态,包括已揭示的方格和未揭示的方格。
- 当游戏结束时,显示全部雷区的状态。
可以根据需要对该示例代码进行修改和扩展,例如增加计时器、记录最高分等功能。
阅读全文