專案架構
MyHead.h:介面宣告、全域常數、結構體定義
- 主程式:遊戲邏輯、渲染、輸入處理、記憶體管理
- Windows Console API:顏色、視窗控制、游標定位
核心資料結構
// 地圖單元值定義
enum CellValue {
EMPTY = 0, // 空地
COVERED = 10, // 未揭開
BORDER = -10, // 邊框
HIDDEN_MINE= 20, // 隱藏地雷
REVEALED_MINE=30, // 爆炸地雷
FLAG_TRUE = 40, // 正確標記
FLAG_FALSE = 50 // 錯誤標記
};
// 八方向偏移
const int Go_x[8] = {-1,-1,-1, 0, 0, 1, 1, 1};
const int Go_y[8] = {-1, 0, 1,-1, 1,-1, 0, 1};
// 動態二維陣列
int** pMap; // 遊戲地圖
int** pFlag; // 揭開標記 (0=已揭開, 1=未揭開)
關鍵功能模組
記憶體管理
void GetMap(int*** pMap, int h, int w) {
*pMap = (int**)malloc(sizeof(int*) * h);
for (int i=0; i
地雷佈放與洗牌
void SetBoom(int*** pMap, int h, int w, int cnt) {
for (int i=1; i
遞迴揭開 (洪水填充)
void RunGame(int*** pMap, int*** pFlag, int x, int y, int h, int w) {
int cnt = GetCurrentBoomCount(pMap, x, y, h, w);
if (cnt == 0) {
(*pMap)[x][y] = EMPTY;
(*pFlag)[x][y] = 0;
for (int d=0; d<8; ++d) {
int nx = x + Go_x[d], ny = y + Go_y[d];
if (nx>=1 && nx=1 && ny
遊戲主迴圈
// 登入驗證
bool LoginWin() { /* 輸入帳密,比對 "root"/"root" */ }
// 主流程
int main() {
setWindows();
if (!LoginWin()) return 0;
LoginSuc();
int mapH, mapW, boomCnt;
scanf("%d%d%d", &mapH, &mapW, &boomCnt);
GetMap(&pMap, mapH, mapW);
GetFlag(&pFlag, mapH, mapW);
SetBoom(&pMap, mapH, mapW, boomCnt);
SwapBoom(&pMap, mapH, mapW);
system("cls");
PrintMap(&pMap, mapH, mapW);
int getBoom=0, trueBoom=0;
while (true) {
if (getBoom==boomCnt && trueBoom==0) { /* 勝利 */ break; }
int x, y, flag;
scanf("%d%d%d", &x, &y, &flag); // flag: 0=挖雷, 1=標記
int ret = BeginGame(&pMap, &pFlag, x, y, mapH, mapW, flag);
if (ret == -3) { /* 踩雷失敗 */ break; }
}
FreeMap(&pMap, mapH);
FreeMap(&pFlag, mapH);
ReturnWindows();
return 0;
}
渲染與互動細節
Color(n):SetConsoleTextAttribute 設定前景色
PrintMap:依 CellValue 輸出 Unicode 方塊字符(■、★、☆、①~⑧)
- 標記切換:循環
HIDDEN_MINE → FLAG_TRUE → COVERED → HIDDEN_MINE
- 勝利條件:所有地雷被正確標記 (
getBoom==boomCnt && trueBoom==0)
編譯需求
- Windows 平台 (需
windows.h, conio.h)
- 支援 Unicode 輸出的終端機 (Windows Terminal / 新版 CMD)
- C++11 或以上 (建議)