简单扩散

 

简单扩散简单扩散

让我们直接来看看代码 

#include <iostream>
#include <conio.h>

void main()
{
	const int w = 10;
	const int h = 10;
	int map[w*h] = 
	{
		0,0,0,0,1,0,0,0,0,0,
		0,0,1,1,1,1,0,0,0,0,
		0,1,0,0,0,0,1,0,0,0,
		0,1,0,0,0,0,0,1,0,0,
		0,1,0,0,0,0,0,0,1,0,
		0,1,0,0,0,0,0,0,1,0,
		0,1,0,1,1,1,0,0,1,0,
		0,1,0,1,0,1,0,1,1,0,
		0,1,1,1,0,1,1,1,0,0,
		0,0,0,0,0,0,0,0,0,0
	};
	//翻开与否的数组
	bool show[w*h] = {};

	//光标
	int px = 0; 
	int py = 0;

	while (1)
	{
		system("cls");
		for (int i = 0;i < w*h; ++i)
		{
			if (i == px + py * w)
				std::cout<<"光";
			else if (show[i])
			{
				if (map[i] == 1)
					std::cout<<"①";
				else if (map[i] == 0)
					std::cout<<"  ";
			}
			else
			{
				std::cout<<"■";
			}
			if (i % w== w-1)
				std::cout<<std::endl;
		}

		int a = _getch();
		if (a == 'w')
		{
			if (py > 0) py -- ;
		}
		else if (a == 's')
		{
			if (py < h-1) py ++;
		}
		else if (a == 'a')
		{
			if (px > 0) px --;
		}
		else if (a == 'd')
		{
			if (px < w - 1) px ++;
		}
		else if (a == ' ')
		{
			//如果没有翻开
			if (!show[px+py*w])
			{
				if (map[px+py*w] == 1)
					show[px+py*w] = true;
				else
				{
					int A[w*h];					
					int len = 0;
					A[len++] = px+py*w;//把点击的位置装入A中
					for (int i = 0;i < len; ++i)
					{
						if (map[A[i]] == 0)
						{
							int xx[] = {0,0,-1,1};
							int yy[] = {-1,1,0,0};
							//循环四个方向
							for (int k = 0; k < 4; ++k)
							{
								int x = A[i] % w + xx[k];
								int y = A[i] / w + yy[k];
								//如果没有出界
								if (x >= 0 && x < w && y >= 0 && y < h)
								{
									//如果是黄色直接翻开
									if (map[x+y*w] == 1)
										show[x+y*w] = true;
									else
									{
										//判断x+y*w在不在A表中,不在才装入A表
										bool zai = false;
										for (int i = 0; i < len; ++i)
										{	if (A[i] == x+y*w)
											{
												zai=true;
												break;
											}
										}
										if (!zai)
											A[len++] = x+y*w;
									}
								}
							}
							
						}
					}
					//在A表中的所有下标都要翻开
					for (int i = 0;i < len; ++i)
					{
						show[A[i]] = true;
					}

				}
			}
		}
	}


}