#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <iomanip>
using namespace std;
// 常量定义
const int ROWS = 9;
const int COLS = 9;
const int MINES = 10;
// 方向数组(八邻域)
const int DIRS[8][2] = {
{-1, -1}, {-1, 0}, {-1, 1},
{0, -1}, {0, 1},
{1, -1}, {1, 0}, {1, 1}
};
// 游戏状态
enum GameState { PLAYING, WIN, LOSE };
vector<vector<int> > mineMap; // 注意:> > 中间加了空格,防C++98报错
vector<vector<char> > display; // 同上
GameState gameState = PLAYING;
int remainingSafe = ROWS * COLS - MINES;
// 函数声明
void initGame();
void placeMines();
void calcNumbers();
void printBoard();
bool isValidPos(int r, int c);
void reveal(int r, int c);
void toggleFlag(int r, int c);
bool checkWin();
void handleInput();
int main() {
srand((unsigned)time(NULL));
initGame();
printBoard();
}
void initGame() {
mineMap.assign(ROWS, vector<int>(COLS, 0));
display.assign(ROWS, vector<char>(COLS, '#'));
remainingSafe = ROWS * COLS - MINES;
gameState = PLAYING;
placeMines();
calcNumbers();
}
void placeMines() {
int placed = 0;
while (placed < MINES) {
int r = rand() % ROWS;
int c = rand() % COLS;
if (mineMap[r][c] != -1) {
mineMap[r][c] = -1;
placed++;
}
}
}
void calcNumbers() {
for (int r = 0; r < ROWS; ++r) {
for (int c = 0; c < COLS; ++c) {
if (mineMap[r][c] == -1) continue;
int count = 0;
// 遍历八个方向(改用下标循环)
for (int i = 0; i < 8; i) {
int nr = r + DIRS[i][0];
int nc = c + DIRS[i][1];
if (isValidPos(nr, nc) && mineMap[nr][nc] == -1)
count;
}
mineMap[r][c] = count;
}
}
}
bool isValidPos(int r, int c) {
return r >= 0 && r < ROWS && c >= 0 && c < COLS;
}
void printBoard() {
system("cls"); // Windows清屏
cout << " ";
for (int c = 0; c < COLS; ++c)
cout << setw(2) << c << ' ';
cout << endl;
}
void reveal(int r, int c) {
if (!isValidPos(r, c)) return;
if (display[r][c] == 'F' || display[r][c] != '#') return;
}
void toggleFlag(int r, int c) {
if (!isValidPos(r, c)) return;
if (display[r][c] == '#') {
display[r][c] = 'F';
} else if (display[r][c] == 'F') {
display[r][c] = '#';
}
}
void handleInput() {
int r, c;
char action;
cout << "请输入操作 (o 翻开, f 标记/取消标记) 和坐标,例如: o 3 5 或 f 2 4: ";
cin >> action >> r >> c;
}