c++实现扫雷(坐标)

时间:2021-02-14 18:08:41

昨天在观察贪食蛇的代码时,看到了有如何实现扫雷的c++代码,觉得挺有趣,今天便又试了一下

#include <ctime>
#include <cstdlib>
#include <iostream>
using namespace std;
int map[][]; // 为避免边界的特殊处理,故将二维数组四周边界扩展1
int derection[] = { , , - }; //方向数组
int calculate ( int x, int y )
{
int counter = ;
for ( int i = ; i < ; i++ )
for ( int j = ; j < ; j++ )
if ( map[ x+derection[i]][ y+derection[j] ] == )
counter++; // 统计以(x,y)为中心的四周的雷数目
return counter;
}
void game ( int x, int y )
{
if ( calculate ( x, y ) == )
{
map[x][y] = ;
for ( int i = ; i < ; i++ )
{ // 模拟游戏过程,若点到一个空白,则系统自动向外扩展
for ( int j = ; j < ; j++ )
if ( x+derection[i] <= && y+derection[j] <= && x+derection[i] >= && y+derection[j] >=
&& !( derection[i] == && derection[j] == ) && map[x+derection[i]][y+derection[j]] == - )
game( x+derection[i], y+derection[j] ); // 条件比较多,一是不可以让两个方向坐标同时为0,否则 } //二是递归不能出界.三是要保证不返回调用。
}
else
map[x][y] = calculate(x,y);
}
void print ()
{
for ( int i = ; i < ; i++ )
{
for ( int j = ; j < ; j++ )
{
if ( map[i][j] == - || map[i][j] == )
cout << "#";
else
cout << map[i][j];
}
cout << endl;
}
}
bool check ()
{
int counter = ;
for ( int i = ; i < ; i++ )
for ( int j = ; j < ; j++ )
if ( map[i][j] != - )
counter++;
if ( counter == )
return true;
else
return false;
} int main ()
{ int i, j, x, y;
char ch;
srand ( time ( ) ); do
{
memset ( map, -, sizeof(map) ); // 将map全部初始化为-1,以后用-1表示未涉及的区域 for ( i = ; i < ; )
{
x = rand()% + ;
y = rand()% + ;
if ( map[x][y] != )
{
map[x][y] = ;
i++;
}
} for ( i = ; i < ; i++ )
{
for ( j = ; j < ; j++ )
cout << "#";
cout << "\n";
}
cout << "\n"; cout << "Please enter a coordinate: ";
while ( cin >> x >> y )
{
if ( map[x][y] == )
{
cout << "GAME OVER" << endl; //点中雷之后游戏结束,并且输出雷的位置
for ( i = ; i < ; i++ )
{
for ( j = ; j < ; j++ )
{
if ( map[i][j] == )
cout << "@";
else
cout << "#";
}
cout << endl;
}
break;
} game(x,y);
print(); if ( check () )
{
cout << "YOU WIN" << endl;
break;
}
cout << "\n\n";
} cout << "Do you want to play again, if true enter Y, or enter N" << endl;
cin >> ch;
cout << "\n\n";
} while ( ch == 'Y' ); return ;
}

程序截图:

c++实现扫雷(坐标)

c++实现扫雷(坐标)

界面有点简陋,并是通过坐标来排雷的,而且到现在还没搞懂他这个程序到底该怎样输入坐标,不过还是感谢作者吧