写小游戏求助
  • 板块灌水区
  • 楼主Aaron530
  • 当前回复3
  • 已保存回复3
  • 发布时间2022/10/14 20:20
  • 上次更新2023/10/27 07:33:04
查看原帖
写小游戏求助
677489
Aaron530楼主2022/10/14 20:20

有人知道为什么会无限生成地图吗

#include <bits/stdc++.h>
#include <windows.h>
using namespace std;
int n;//地图大小
bool map1[105][105]={false};//地图
char endline='\n';//换行
char space=' ';//空格

//bfs
bool book[105][105]={1};//标记
int tx,ty;//搜索坐标
int sx,sy,ex,ey;//起点、终点坐标
int head,tail;//队首,队尾
int d[4][2]={{0,1},{1,0},{-1,0},{0,-1}};//方向数组
struct node
{
	int x,y;
}q[10005];//队列
bool bfs()
{
	head=1,tail=1;
	int flag=1;
	q[tail].x=sx;
	q[tail].y=sy;
	tail++;
	book[sx][sy]=1;
	while(head<tail)
	{
		node h=q[head];
		for(int i=0;i<4;i++)
		{
			tx=h.x+d[i][0];
			ty=h.y+d[i][1];
			if(tx<2 || tx>=n || ty<2 || ty>=n)
				continue;
			if(map1[tx][ty]==0 || book[tx][ty]==1)
				continue;
			q[tail].x=tx;
			q[tail].y=ty;
			tail++;
			book[tx][ty]=1;
			if(tx==ex && ty==ey)
			{
				flag=0;
				return true;
			}
		}
		head++;
	}
	if(flag==1)
		return false;
}

void SetColorAndBackground(int Forgc, int Backc)//字符颜色 
{
	WORD wColor = ((Backc & 0x0f) << 4) + (Forgc & 0x0f);
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), wColor);
}
void clean(int x)//等待+清屏
{
	Sleep(x);//等待x毫秒
	system("cls");//清屏
}
void randmap()//随机地图
{
	srand(time(NULL));
	for(int i=2;i<n;i++)
		for(int j=2;j<n;j++)
		{
			bool num=rand()%2;//TRUE为路,FALSE为墙
			map1[i][j]=num;
		}
}
void print()//打印地图
{
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++)
		{
			if(map1[i][j]==true)//路
			{
				SetColorAndBackground(0,0);
				printf("█");
			}
			else//墙
			{
				SetColorAndBackground(4,0);
				printf("█");
			}
			putchar(space);
		}
		putchar(endline);
	}
}
int main()
{
	cout<<"请输入地图大小";
	clean(500);
	cin>>n;
	int tf=1;//是否修改
	while(tf)
	{
		cout<<"当前地图大小为:"<<n<<"*"<<n;
		cout<<endl<<"是否修改?";
		cout<<endl<<"修改输入1,不修改输入0";
		clean(2000);
		cin>>tf;
		if(tf==1)
			cin>>n;
	}
	while(sx==ex && sy==ey)//随机起、终点
	{
		sx=rand()%n;
		sy=rand()%n;
		ex=rand()%n;
		sy=rand()%n;
	}
	if(sx==0)
		sx=1;
	if(sy==0)
		sy=1;
	if(ex==0)
		ex=1;
	if(ey==0)
		ey=1;
	cout<<"地图生成中,请稍等...";
	while(1)
	{
		for(int i=2;i<n;i++)
			for(int j=2;j<n;j++)
				book[i][j]=0;
		map1[sx][sy]=1;
		map1[ex][ey]=1;
		randmap();
//		print();
//		cout<<sx<<" "<<sy;
//		cout<<ex<<" "<<ey;
//		clean(15000);
		
		if(bfs())
			break;
	}
	print();
	cout<<endl;
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++)
		{
			cout<<map1[i][j]<<" ";
		}
		putchar(endline);
	}
	return 0;
}
2022/10/14 20:20
加载中...