自己编写的扫雷程序....
程序代码:
#include<iostream> #include<ctime> using namespace std; #define ROW 9 // 行数 #define COL 9 // 列数 #define BOMBNUMS 10 // 雷数 char arrInfo[ROW][COL];//定义一个全局二维数组; void ClearZero(int iRow, int iCol);//将0转换为空格的函数 void cBuLei();//布雷 int main() { int iRow , iCol; cout << "请输入横坐标:" << endl; cin >> iRow; cout << "请输入纵坐标:" << endl; cin >> iCol; cBuLei(); ClearZero(iRow, iCol); for(int a = 0; a < ROW; ++a) { for(int b = 0; b < COL; ++b) { cout << " " << arrInfo [a][b]; } cout << endl; } return 0; } void cBuLei() { memset(arrInfo, '0' , ROW * COL * sizeof(char) ); int iNum = 0; // 已经布下的雷 unsigned iBombNO = 0; srand( time(0) ); int iTmpRow, iTmpCol; //行、列位置 while ( iNum < BOMBNUMS ) { iBombNO = rand() % (ROW * COL); iTmpRow = iBombNO / COL; iTmpCol = iBombNO % COL; if (arrInfo[iTmpRow][iTmpCol] == '*' ) //如果找到的位置有炸弹,重新找位置 { continue; } arrInfo[iTmpRow][iTmpCol] = '*'; // 设置为雷 ++iNum; //已经布下的雷数加1 } for(int j = 0; j < ROW; ++j) { for ( int k = 0; k < COL; ++k) { if (arrInfo [j][k] != '*') { //开始计算雷周围的数字 int iTmp = 0; if ((j-1 >= 0) && (k-1 >= 0)) { if (arrInfo[j-1][k-1] == '*') iTmp += 1; } if (j-1 >= 0) { if (arrInfo[j-1][k] == '*') iTmp += 1; } if ((j-1 >= 0) && (k+1 < COL)) { if (arrInfo[j-1][k+1] == '*') iTmp += 1; } if (k-1 >= 0) { if (arrInfo[j][k-1] == '*') iTmp += 1; } if (k+1 < COL) { if (arrInfo[j][k+1] == '*') iTmp += 1; } if ((j+1 < ROW) && (k-1 >= 0)) { if (arrInfo[j+1][k-1] == '*') iTmp += 1; } if (j+1 < ROW) { if (arrInfo[j+1][k] == '*') iTmp += 1; } if ((j+1 < ROW) && (k+1 < COL)) { if (arrInfo[j+1][k+1] == '*') iTmp += 1; } //结束计算 arrInfo [j][k] = char(iTmp + 48);//将计算出来的数字赋给坐标 } } } } void ClearZero(int iRow, int iCol) { if (arrInfo[iRow][iCol] == '0') { arrInfo[iRow][iCol] = ' '; if ((iRow-1 >= 0) && (iCol-1 >= 0) && (arrInfo[iRow-1][iCol-1] == '0')) { ClearZero(iRow-1, iCol-1); } if ((iRow-1 >= 0) && (arrInfo[iRow-1][iCol] == '0')) { ClearZero(iRow-1, iCol); } if ((iRow-1 >= 0) && (iCol+1 < COL) && (arrInfo[iRow-1][iCol+1] == '0')) { ClearZero(iRow-1, iCol+1); } if ((iCol-1 >= 0) && (arrInfo[iRow][iCol-1] == '0')) { ClearZero(iRow, iCol-1); } if ((iCol+1 < COL) && (arrInfo[iRow][iCol+1] == '0')) { ClearZero(iRow, iCol+1); } if ((iRow+1 < ROW) && (iCol-1 >= 0) && (arrInfo[iRow+1][iCol-1] == '0')) { ClearZero(iRow+1, iCol-1); } if ((iRow+1 < ROW) && (arrInfo[iRow+1][iCol] == '0')) { ClearZero(iRow+1, iCol); } if ((iRow+1 < ROW) && (iCol+1 < COL) && (arrInfo[iRow+1][iCol+1] == '0')) { ClearZero(iRow+1, iCol+1); } } }