扫雷
C++#include<bits/stdc++.h>
using namespace std;
char board[32][32];
bool shown[32][32] = {},spreaded[32][32] = {};
int n;
int is_mine(int x,int y)
{
if(x < 0 || y < 0 || x >= n || y >= n)
{
return 0;
}
return board[x][y] == '*';
}
int around(int x,int y)
{
return is_mine(x - 1,y) + is_mine(x + 1,y) + is_mine(x - 1,y - 1) + is_mine(x + 1,y - 1) + is_mine(x - 1,y + 1) + is_mine(x + 1,y + 1) + is_mine(x,y - 1) + is_mine(x,y + 1);
}
void spread(int x,int y)
{
if(!(x < 0 || y < 0 || x >= n || y >= n || spreaded[x][y] == 1 || board[x][y] == '*'))
{
shown[x][y] = 1;
spreaded[x][y] = 1;
if(board[x][y] == '0')
{
spread(x - 1,y);
spread(x + 1,y);
spread(x,y - 1);
spread(x,y + 1);
}
}
}
int main()
{
srand(time(0));
cout << "欢迎游玩扫雷1.0!\n请选择难度,简单难度输入1,中等难度输入2,困难难度输入3:";
cin >> n;
while(n < 1 || n > 3)
{
cout << "输入不合法,请重新输入:";
cin >> n;
}
n = 5 * pow(2,n - 1);
cout << "创建游戏中……\n";
int mine_cnt = (rand() % n / 2) + n,x,y;
for(int i = 0;i < mine_cnt;i++)
{
x = rand() % n;
y = rand() % n;
while(board[x][y] == '*')
{
x = rand() % n;
y = rand() % n;
}
board[x][y] = '*';
}
for(int i = 0;i < n;i++)
{
for(int j = 0;j < n;j++)
{
if(board[i][j] != '*')
{
board[i][j] = char(around(i,j) + '0');
}
}
}
cout << "创建完毕!\n";
for(int i = 0;i < n;i++)
{
for(int j = 0;j < n;j++)
{
cout << "?";
}
cout << "\n";
}
cout << "===游戏开始===\n";
int find_cnt = 0,type;
while(1)
{
if(find_cnt == mine_cnt)
{
cout << "你赢了!\n你找到了" << find_cnt << "/" << mine_cnt << "个雷\n完整棋盘:\n";
for(int i = 0;i < n;i++)
{
for(int j = 0;j < n;j++)
{
cout << board[i][j];
}
cout << "\n";
}
break;
}
cout << "普通操作请输入1,标记雷请输入2:";
cin >> type;
while(type < 1 || type > 2)
{
cout << "输入不合法,请重新输入:";
cin >> type;
}
cout << "请输入x,y坐标:";
cin >> x >> y;
swap(x,y);
x--;
y--;
while(x < 0 || y < 0 || x >= n || y >= n || shown[x][y])
{
cout << "输入不合法(可能是坐标不合法或此点以被展示),请重新输入:";
cin >> x >> y;
swap(x,y);
x--;
y--;
}
for(int i = 0;i < 64;i++)
{
cout << "\n";
}
if(type == 1 && board[x][y] == '*' || type == 2 && board[x][y] != '*')
{
cout << "你输了!\n你找到了" << find_cnt << "/" << mine_cnt << "个雷\n完整棋盘:\n";
for(int i = 0;i < n;i++)
{
for(int j = 0;j < n;j++)
{
cout << board[i][j];
}
cout << "\n";
}
break;
}
if(type == 2)
{
cout << "标记成功!\n";
shown[x][y] = 1;
}
else
{
cout << "此格不是雷!\n";
spread(x,y);
find_cnt++;
}
cout << "目前棋盘:\n";
for(int i = 0;i < n;i++)
{
for(int j = 0;j < n;j++)
{
if(shown[i][j])
{
cout << board[i][j];
}
else
{
cout << "?";
}
}
cout << "\n";
}
}
return 0;
}