c language review: walking the maze

Briefly review the small task of walking the maze in the c language (really simple, it has not been modified by 100 million points): for example, make the map bigger, hide the treasure chest, if you go the wrong way, laugh at you, you If it is cleared, it will be necessary. . .

#include<stdio.h>
#define ROWS 6
#define COLS 8
int x = 1;
int y = 1;
char dir = '0';
//创建一个地图
char  map[ROWS][COLS] =
      {
		{'#', '#', '#', '#', '#', '#', '#', '#'},
		{'#', '0', '#', '#', ' ', ' ', ' ', ' '},
		{'#', ' ', ' ', '#', ' ', '#', '#', '#'},
		{'#', '#', ' ', '#', ' ', '#', ' ', '#'},
		{'#', '#', ' ', ' ', ' ', ' ', ' ', '#'},
		{'#', '#', '#', '#', '#', '#', '#', '#'}
	};
void mademap()//打印地图
{
	for (int i = 0;i < 6;i++)
	{
		for (int j = 0;j < 8;j++)
		{
			printf("%c", map[i][j]);
		}
		printf("\n");
	}
}
void goleft()
{
	if (map[x][y -1] == ' ')//如果向左一个位置是空格则可以走
	{
		map[x][y] = ' ';//当前位置换成空格
		y = y - 1;
		map[x][y] = '0';//左边一个位置换成0
		system("cls");
	}
	else
	{
		system("cls");
		printf("此路不通,请重新开始。\n");
		map[x][y] = ' ';
		map[1][1] = '0';
		x = 1;
		y = 1;
	}
}
void goright()
{
	if (map[x][y + 1] == ' ')//如果向右一个位置是空格则可以走
	{
		map[x][y] = ' ';//当前位置换成空格
     	y = y + 1;
		map[x][y] = '0';//右边一个位置换成0
		system("cls");
	}
	else
	{
		system("cls");
		printf("此路不通,请重新开始。\n");
		map[x][y] = ' ';
		map[1][1] = '0';
		x = 1;
		y = 1;
	}
}
void goup()
{
	if (map[x - 1][y] == ' ')//如果向上一个位置是空格则可以走
	{
		map[x][y] = ' ';//当前位置换成空格
		x = x - 1;
		map[x][y] = '0';//上边一个位置换成0
		system("cls");
	}
	else
	{
		system("cls");
		printf("此路不通,请重新开始。\n");
		map[x][y] = ' ';
		map[1][1] = '0';
		x = 1;
		y = 1;
	}
}
void godown()
{
	if (map[x+1][y] == ' ')//如果向下一个位置是空格则可以走
	{
		map[x][y] = ' ';//当前位置换成空格
		x = x + 1;
		map[x][y] = '0';//下边一个位置换成0
		system("cls");
	}
	else
	{
		system("cls");
		printf("此路不通,请重新开始。\n");
		map[x][y] = ' ';
		map[1][1] = '0';
		x = 1;
		y = 1;
	}
}
void enterDirection()
{
	printf("请输入小人的前进方向:w=上,s=下,a=左,d=右\n");
	rewind(stdin);
	scanf_s("%c", &dir);
}
int main(int argc,const char * argv[]) 
{
	while (map[1][7] != '0')//循环
	{
		//地图
		mademap();
		//输入指令
		enterDirection();
		//判断条件
		if (dir == 'A' || dir == 'a')
		{
			goleft();
		}
		else if (dir == 'S' || dir == 's')
		{
			godown();
		}
		else if (dir == 'D' || dir == 'd')
		{
			goright();
		}
		else if (dir == 'W' || dir == 'w')
		{
			goup();
		}
	}
}

I use Visual Studio 2019 to run the program, and the computer is window10, so scanf_s will report a warning but it will not affect it.

Guess you like

Origin blog.csdn.net/innumai/article/details/113107379