java编译一个扫雷游戏程序
时间: 2023-10-31 19:05:01 浏览: 92
以下是一个简单的Java扫雷游戏程序的代码示例:
```java
import java.util.Random;
import java.util.Scanner;
public class Minesweeper {
private char[][] board;
private boolean[][] revealed;
private int rows, cols;
private int remaining;
public Minesweeper(int rows, int cols, int mines) {
this.rows = rows;
this.cols = cols;
this.board = new char[rows][cols];
this.revealed = new boolean[rows][cols];
this.remaining = rows * cols - mines;
// initialize board with empty cells
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
board[i][j] = '.';
revealed[i][j] = false;
}
}
// randomly place mines on the board
Random random = new Random();
int count = 0;
while (count < mines) {
int i = random.nextInt(rows);
int j = random.nextInt(cols);
if (board[i][j] != '*') {
board[i][j] = '*';
count++;
}
}
}
public void play() {
Scanner scanner = new Scanner(System.in);
while (true) {
// print board
System.out.println(getBoardString());
// get user input
System.out.print("Enter row and column (e.g. 3 4): ");
int row = scanner.nextInt() - 1;
int col = scanner.nextInt() - 1;
// check if cell is valid and not already revealed
if (row < 0 || row >= rows || col < 0 || col >= cols) {
System.out.println("Invalid cell, try again.");
continue;
}
if (revealed[row][col]) {
System.out.println("Cell already revealed, try again.");
continue;
}
// reveal cell and update remaining count
revealed[row][col] = true;
if (board[row][col] == '*') {
System.out.println("Boom! Game over.");
return;
} else {
remaining--;
if (remaining == 0) {
System.out.println("Congratulations! You win!");
return;
}
}
// update adjacent cells
if (board[row][col] == '.') {
updateAdjacentCells(row, col);
}
}
}
private void updateAdjacentCells(int row, int col) {
int[][] directions = {
{-1, -1}, {-1, 0}, {-1, 1},
{0, -1}, {0, 1},
{1, -1}, {1, 0}, {1, 1}
};
for (int[] dir : directions) {
int r = row + dir[0];
int c = col + dir[1];
if (r >= 0 && r < rows && c >= 0 && c < cols && board[r][c] == '*') {
board[row][col]++;
}
}
}
private String getBoardString() {
StringBuilder sb = new StringBuilder();
sb.append(" ");
for (int j = 0; j < cols; j++) {
sb.append(j + 1);
}
sb.append("\n");
for (int i = 0; i < rows; i++) {
sb.append((char) ('A' + i)).append(" ");
for (int j = 0; j < cols; j++) {
if (revealed[i][j]) {
sb.append(board[i][j]);
} else {
sb.append(".");
}
}
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
Minesweeper game = new Minesweeper(8, 8, 10);
game.play();
}
}
```
这个程序使用了一个二维字符数组来表示扫雷的棋盘,其中`.`表示未翻开的空格,`*`表示地雷,数字表示该格周围地雷的数量。使用一个二维布尔数组来表示哪些格子已经被翻开了。程序会随机放置指定数量的地雷,然后让用户逐步翻开格子,直到所有非地雷格子都被翻开为止。如果翻开了地雷格子,游戏结束。如果所有非地雷格子都被翻开了,用户获胜。
阅读全文
相关推荐


















