扫雷
#include <bits/stdc++.h>
#include<time.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
using namespace std;
int chang=10,kuan=10; //长和宽
int a[100][100],ans,zds,sls,jsls,dijic;
int flag[100][100],zj=0;
bool blei[100][100];
int qx[10]= {1,-1,0,0,1,1,-1,-1};
int qy[10]= {0,0,1,-1,1,-1,1,-1};
int x,y;
void zd() {
for(int i=1; i<=zds; i++) {
int nx=rand()%chang+1;
int ny=rand()%kuan+1;
if(a[nx][ny]==99) {
i--;
} else {
a[nx][ny]=99;
}
}
}
void sz() {
for(int i=1; i<=chang; i++) {
for(int j=1; j<=kuan; j++) {
if(a[i][j]!=99) {
if(a[i-1][j]==99) {
a[i][j]++;
}
if(a[i][j-1]==99) {
a[i][j]++;
}
if(a[i+1][j]==99) {
a[i][j]++;
}
if(a[i][j+1]==99) {
a[i][j]++;
}
if(a[i-1][j-1]==99) {
a[i][j]++;
}
if(a[i-1][j+1]==99) {
a[i][j]++;
}
if(a[i+1][j-1]==99) {
a[i][j]++;
}
if(a[i+1][j+1]==99) {
a[i][j]++;
}
}
}
}
}
void dfs(int xx,int yy) {
flag[xx][yy]=1;
ans++;
if(a[xx][yy]!=0) {
return;
} else {
for(int i=0; i<=7; i++) {
int nx=xx+qx[i],ny=yy+qy[i];
if(a[nx][ny]!=99&&nx<=chang&&nx>=1&&ny<=kuan&&ny>=1&&flag[nx][ny]!=true) {
dfs(nx,ny);
}
}
}
}
int main() {
cout<<"长和宽:";
cin>>chang>>kuan;
system("cls");
cout<<"雷数:";
cin>>zds;
sls=zds;
jsls=zds;
system("cls");
srand((unsigned int)(time(NULL)));
zd();
sz();
x=5,y=5;//初始光标位置
while((ans<(chang*kuan)-zds&&sls>0)||jsls<0) {
for(int i=0; i<=chang; i++) {
for(int j=0; j<=kuan; j++) {
if(i==0&&j==0) {
cout<<" ";
} else if(j==0) {
if(i>=10) {
cout<<i<<' ';
} else {
cout<<i<<" ";
}
} else if(i==0) {
if(j>=10) {
cout<<j;
} else {
cout<<j<<" ";
}
} else if(i==x&&j==y) {
cout<<'+'<<' ';
} else if(blei[i][j]==true) {
cout<<'P'<<' ';
} else if(flag[i][j]==1) {
cout<<a[i][j]<<' ';
} else {
cout<<"- ";
}
}
cout<<endl;
}
cout<<"还剩"<<jsls<<"颗雷"<<endl;
cout<<"按'e'键标记"<<endl;
cout<<"按' '键掀开"<<endl;
char xy=_getch();
if(xy==' ') {
if(dijic==0) {
dijic=1;
while(a[x][y]!=0) {
memset(a,0,sizeof(a));
zd();
sz();
}
}
}
if(xy==' ') {
if(blei[x][y]==false) {
if(a[x][y]!=99) {
if(flag[x][y]==0) {
// if(dijic==0) {
// dijic=1;
// while(a[x][y]!='0') {
// zd();
// sz();
// }
// }
dfs(x,y);
}
} else {
zj=1;
break;
}
}
} else if(xy=='e') {
if(flag[x][y]==0) {
if(blei[x][y]==true) {
if(a[x][y]==99) {
sls++;
jsls++;
} else {
jsls++;
}
blei[x][y]=false;
} else if(a[x][y]==99) {
sls--;
jsls--;
blei[x][y]=true;
} else {
jsls--;
blei[x][y]=true;
}
}
} else {
if(xy=='w') {
if(x-1>=1&&x-1<=chang&&y>=1&&y<=kuan) {
x--;
}
}
if(xy=='s') {
if(x+1>=1&&x+1<=chang&&y>=1&&y<=kuan) {
x++;
}
}
if(xy=='a') {
if(x>=1&&x<=chang&&y-1>=1&&y-1<=kuan) {
y--;
}
}
if(xy=='d') {
if(x>=1&&x<=chang&&y+1>=1&&y+1<=kuan) {
y++;
}
}
}
system("cls");
}
system("cls");
for(int i=0; i<=chang; i++) {
for(int j=0; j<=kuan; j++) {
if(i==0&&j==0) {
cout<<" ";
} else if(i==0) {
cout<<j<<' ';
} else if(j==0) {
if(i>=10) {
cout<<i<<' ';
} else {
cout<<i<<" ";
}
} else if(a[i][j]==99) {
cout<<"* ";
} else {
cout<<a[i][j]<<' ';
}
}
cout<<endl;
}
if(zj==1) {
cout<<"你输了";
} else {
cout<<"你赢了";
}
return 0;
}