用c++写一段扫雷代码
时间: 2024-03-13 20:20:15 浏览: 76
扫雷代码(C++).pdf
以下是一个简单的C++扫雷游戏代码,实现了基本的游戏逻辑,但没有图形界面。
```c++
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
// 雷区类
class MineSweeper {
private:
int row; // 行数
int col; // 列数
int mineNum; // 雷数
vector<vector<bool>> mines; // 雷区
vector<vector<int>> counts; // 数字区
// 计算某格周围雷数
int countMines(int r, int c) {
int count = 0;
for (int i = r - 1; i <= r + 1; i++) {
if (i < 0 || i >= row) continue;
for (int j = c - 1; j <= c + 1; j++) {
if (j < 0 || j >= col) continue;
if (mines[i][j]) count++;
}
}
return count;
}
public:
MineSweeper(int r, int c, int m) : row(r), col(c), mineNum(m) {
// 初始化雷区和数字区
mines.resize(row, vector<bool>(col));
counts.resize(row, vector<int>(col, -1));
// 随机生成雷区
srand(time(NULL));
int count = 0;
while (count < mineNum) {
int r = rand() % row;
int c = rand() % col;
if (!mines[r][c]) {
mines[r][c] = true;
count++;
}
}
// 计算数字区
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (mines[i][j]) counts[i][j] = -2; // -2 表示当前格是雷
else counts[i][j] = countMines(i, j);
}
}
}
// 翻开某格
void uncover(int r, int c) {
if (counts[r][c] != -1) return; // 已经翻开过或标记过的格子不能再翻开
counts[r][c] = countMines(r, c);
if (counts[r][c] == 0) {
// 如果是空格,递归翻开周围的格子
for (int i = r - 1; i <= r + 1; i++) {
if (i < 0 || i >= row) continue;
for (int j = c - 1; j <= c + 1; j++) {
if (j < 0 || j >= col) continue;
uncover(i, j);
}
}
}
}
// 标记某格为雷或取消标记
void mark(int r, int c) {
if (counts[r][c] != -1) return; // 已经翻开过或标记过的格子不能再标记
if (counts[r][c] == -1) counts[r][c] = -3; // -3 表示当前格已标记为雷
else if (counts[r][c] == -3) counts[r][c] = -1; // 恢复当前格
}
// 判断是否胜利
bool isWin() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (mines[i][j] && counts[i][j] != -3) return false; // 有雷没被标记
if (!mines[i][j] && counts[i][j] == -1) return false; // 有空格没被翻开
}
}
return true;
}
// 打印当前地图
void print() {
cout << " ";
for (int j = 0; j < col; j++) cout << j << " ";
cout << endl;
for (int i = 0; i < row; i++) {
cout << i << " ";
for (int j = 0; j < col; j++) {
if (counts[i][j] == -1) cout << ". ";
else if (counts[i][j] == -2) cout << "* ";
else if (counts[i][j] == -3) cout << "F ";
else cout << counts[i][j] << " ";
}
cout << endl;
}
}
};
int main() {
int row, col, mineNum;
cout << "请输入行数、列数和雷数:";
cin >> row >> col >> mineNum;
MineSweeper game(row, col, mineNum);
game.print();
while (true) {
int r, c;
cout << "请输入要翻开的行号和列号,中间用空格隔开:";
cin >> r >> c;
game.uncover(r, c);
game.print();
if (game.isWin()) {
cout << "恭喜你,扫雷成功!" << endl;
break;
}
}
return 0;
}
```
阅读全文