跳到正文

个人记录

[说过不鸽!]经典扫雷小游戏

_Sushi约 6 分钟
原文
文章信息与版本

文章信息

发布
2022年7月10日
收录
2025年12月12日
更新
2026年11月15日
篇幅
约 6 分钟

版本

  1. v2当前
  2. v1
C++
#include<bits/stdc++.h>
#include<conio.h>
#include<windows.h>
using namespace std;
const int n=15,m=15;
int a[n+2][m+2];
int f[n+1][m+1];
int flag;
int x=1,y=1,u,v;
char c;
void gotoxy(int x, int y)
{
    COORD coord;
	HANDLE hscr;
	coord.X=x;
	coord.Y=y;
	hscr=GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleCursorPosition(hscr, coord);
}
void empty(int x,int y)
{
	f[x][y]=1;
	if(!f[x-1][y]&&a[x-1][y]==0&&x-1>=1) empty(x-1,y);
	else if(a[x-1][y]!=-1&&x-1>=1) f[x-1][y]=1;
	if(!f[x+1][y]&&a[x+1][y]==0&&x+1<=n) empty(x+1,y);
	else if(f[x+1][y]!=-1&&x+1<=n) f[x+1][y]=1;
	if(!f[x][y-1]&&a[x][y-1]==0&&y-1>=1) empty(x,y-1);
	else if(f[x][y-1]!=-1&&y-1>=1) f[x][y-1]=1;
	if(!f[x][y+1]&&a[x][y+1]==0&&y+1<=m) empty(x,y+1);
	else if(f[x][y+1]!=-1&&y+1<=m) f[x][y+1]=1;
}
void Init()
{
	srand((unsigned)time(NULL));
	for(int i=1;i<=n;i++)
	    for(int j=1;j<=m;j++)if(rand()%10==0) a[i][j]=-1;
	for(int i=1;i<=n;i++)
	    for(int j=1;j<=m;j++)
	        if(a[i][j]==0) a[i][j]=(a[i-1][j]==-1)+(a[i][j-1]==-1)+(a[i+1][j]==-1)+(a[i][j+1]==-1)+(a[i-1][j-1]==-1)+(a[i+1][j+1]==-1)+(a[i-1][j+1]==-1)+(a[i+1][j-1]==-1);
}
void draw()
{
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			gotoxy(j*2-2,i-1);
			if(x==i&&y==j) cout<<"你";
	        else if(f[i][j]==1)
	                if(a[i][j]!=0) cout<<a[i][j]<<" ";
	        	    else cout<<"  ";
	        	else if(f[i][j]==2)
	        	    cout<<"# ";
	            else cout<<"■";
		}
	    cout<<endl;
	}
}
void play()
{
	u=x,v=y;
	c='x';
	c=getch();
	if(c=='w') u--;
	if(c=='s') u++;
	if(c=='a') v--;
	if(c=='d') v++;
	if(u<1||u>n||v<1||v>m) return;
	x=u,y=v;
	if(c==' ')
	    if(a[x][y]==-1) {flag=1;return;}
	    else if(a[x][y]==0) empty(x,y);
	    else f[x][y]=1;
	if(c=='f')
		f[x][y]=2-f[x][y];
	flag=2;
	for(int i=1;i<=n&&flag==2;i++)
		for(int j=1;j<=m&&flag==2;j++)
		    if(a[i][j]!=-1&&!f[i][j])
		        flag=0;
	draw();
	return;
}
int main()
{
	CONSOLE_CURSOR_INFO cursor_info={1,0};
    SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cursor_info);
    system("mode con cols=31 lines=16");
	ST:
	flag=0;
	memset(a,0,sizeof(a));
	memset(f,0,sizeof(f));
	x=y=1;
	cout<<"上移:w"<<endl;
	cout<<"下移:s"<<endl;
	cout<<"左移:a"<<endl;
	cout<<"右移:d"<<endl;
	cout<<"插旗:f"<<endl;
	cout<<"扫雷:空格"<<endl;
	cout<<"按任意键开始"<<endl;
	getch();
	system("cls");
	Init();
	draw();
	while(!flag) play();
	if(flag==1)
	{
		system("cls");
		for(int i=1;i<=n;i++)
	    {
		    for(int j=1;j<=m;j++)
	            if(a[i][j]==-1) cout<<"雷";
	            else if(f[i][j])
	        	        if(a[i][j]!=0) cout<<a[i][j]<<" ";
	        	        else cout<<"  ";
	                else cout<<"■";
	        cout<<endl;
	    }
		MessageBox(NULL,"GAMEOVER","",MB_OK);
	}
	if(flag==2)
	{
		system("cls");
		MessageBox(NULL,"YOU WIN!","",MB_OK);
	}
	system("cls");
	goto ST;
	return 0;
}
原文