以下是使用 C++ 实现的一个简单的,支持自定义地图大小和地雷总数。代码包括地雷生成、数字计算和揭示功能。
#include
#include
#include
#include
#include
class Minesweeper {
public:
Minesweeper(int width, int height, int num_mines)
: width(width), height(height), num_mines(num_mines),
board(height, std::vector(width, 0)),
revealed(height, std::vector(width, false)) {
generate_mines();
calculate_numbers();
}
bool reveal(int x, int y) {
if (mines.find({x, y}) != mines.end()) {
return false; // 踩到地雷,游戏结束
}
if (!revealed[y][x]) {
revealed[y][x] = true;
if (board[y][x] == 0) {
for (int dx = -1; dx <= 1; ++dx) {
for (int dy = -1; dy <= 1; ++dy) {
int nx = x + dx, ny = y + dy;
if (nx >= 0 && nx < width && ny >= 0 && ny < height) {
reveal(nx, ny);
}
}
}
}
}
return true;
}
void print_board() const {
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
if (revealed[y][x]) {
if (mines.find({x, y}) != mines.end()) {
std::cout << "* "; // 地雷
} else {
std::cout << board[y][x] << " "; // 数字
}
} else {
std::cout << ". "; // 未揭示
}
}
std::cout << "\n";
}
}
private:
int width, height, num_mines;
std::vector> board;
std::vector> revealed;
std::set> mines;
void generate_mines() {
srand(time(0));
int mines_placed = 0;
while (mines_placed < num_mines) {
int x = rand() % width;
int y = rand() % height;
if (mines.insert({x, y}).second) {
mines_placed++;
}
}
}
void calculate_numbers() {
for (const auto& mine : mines) {
int mx = mine.first, my = mine.second;
for (int dx = -1; dx <= 1; ++dx) {
for (int dy = -1; dy <= 1; ++dy) {
int x = mx + dx, y = my + dy;
if (x >= 0 && x < width && y >= 0 && y < height && mines.find({x, y}) == mines.end()) {
board[y][x]++;
}
}
}
}
}
};
int main() {
int width, height, num_mines;
std::cout << "输入地图宽度: ";
std::cin >> width;
std::cout << "输入地图高度: ";
std::cin >> height;
std::cout << "输入地雷总数: ";
std::cin >> num_mines;
Minesweeper game(width, height, num_mines);
std::cout << "初始地图:\n";
game.print_board();
while (true) {
int x, y;
std::cout << "输入要揭示的格子坐标 (x y): ";
std::cin >> x >> y;
if (!game.reveal(x, y)) {
std::cout << "你踩到地雷了!游戏结束。\n";
game.print_board();
break;
}
std::cout << "当前地图:\n";
game.print_board();
}
return 0;
}
代码说明:
Minesweeper
类:- 构造函数:初始化地图大小、地雷总数,并生成地雷和计算数字。
generate_mines
:随机生成地雷。calculate_numbers
:计算每个格子周围的地雷数量。reveal
:揭示格子,如果是空白格,则递归揭示周围格子。-
print_board
:打印当前棋盘状态。 -
主函数:
- 从用户输入获取地图宽度、高度和地雷总数。
- 创建
Minesweeper
实例。 - 循环提示用户输入要揭示的格子坐标,直到踩到地雷。
示例运行:
输入地图宽度: 5
输入地图高度: 5
输入地雷总数: 5
初始地图:
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
输入要揭示的格子坐标 (x y): 2 2
当前地图:
. . . . .
. 1 1 1 .
. 1 0 1 .
. 1 1 1 .
. . . . .
输入要揭示的格子坐标 (x y): 0 0
你踩到地雷了!游戏结束。
* . . . .
. 1 1 1 .
. 1 0 1 .
. 1 1 1 .
. . . . .