用java代码写一个扫雷小游戏,并写出源码
时间: 2023-03-09 12:43:52 浏览: 164
我可以帮助你写一个简单的Java扫雷游戏,游戏细节决定于你,如果你想,我可以写出完整的源码。 以下是一个简单的扫雷游戏的源码:import java.util.Scanner;public class MineSweeper {
public static void main(String[] args) {
// 初始化
int rows = 8;
int cols = 8;
int[][] board = new int[rows][cols];
boolean[][] revealed = new boolean[rows][cols];
int numMines = 10; // 随机放置地雷
while (numMines > 0) {
int row = (int) (Math.random() * rows);
int col = (int) (Math.random() * cols);
if (board[row][col] != -1) {
board[row][col] = -1;
numMines--;
}
} // 计算每个单元格的地雷数量
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (board[r][c] == -1) {
continue;
}
int numAdjacentMines = 0;
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
if (dr == 0 && dc == 0) {
continue;
}
int adjR = r + dr;
int adjC = c + dc;
if (adjR >= 0 && adjR < rows && adjC >= 0 && adjC < cols) {
if (board[adjR][adjC] == -1) {
numAdjacentMines++;
}
}
}
}
board[r][c] = numAdjacentMines;
}
} // 开始游戏
boolean gameOver = false;
Scanner scanner = new Scanner(System.in);
while (!gameOver) {
// 打印棋盘
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (revealed[r][c]) {
if (board[r][c] == -1) {
System.out.print("X");
} else {
System.out.print(board[r][c]);
}
} else {
System.out.print("-");
}
}
System.out.println();
} // 读取用户输入
System.out.println("请输入行号和列号,以空格分隔");
int row = scanner.nextInt();
int col = scanner.nextInt();
revealed[row][col] = true; // 检查是否踩中地雷
if (board[row][col] == -1) {
gameOver = true;
}
}
System.out.println("你输了!");
}
}
阅读全文