走迷宫:
1、定义二维字符数组作为迷宫
2、定义变量记录老鼠的位置
3、获取游戏开始时间
3、进入循环
1、清理屏幕,使用system调用系统命令。
2、显示迷宫(遍历二维字符数组)
3、检查是否到达出口
获取游戏结束时间,计算出走出迷宫用了多少秒。
4、获取方向键并处理
判断接下来要走的位置是否是路,
1、把旧位置赋值为空格
2、把新位置赋值为老鼠
3、把记录老鼠位置的变量改变。
#include
#include
#include
#include
int main()
{
char maze[10][10] = {
{'#','#','#','#','#','#','#','#','#','#'},
{'#','@','#',' ',' ',' ',' ',' ',' ',' '},
{'#',' ','#',' ','#',' ','#',' ','#','#'},
{'#',' ','#',' ','#','#','#',' ','#','#'},
{'#',' ','#',' ',' ',' ','#',' ',' ','#'},
{'#',' ','#',' ','#',' ','#','#','#','#'},
{'#',' ','#',' ','#',' ','#',' ','#','#'},
{'#',' ','#',' ','#',' ','#',' ','#','#'},
{'#',' ',' ',' ','#',' ',' ',' ','#','#'},
{'#','#','#','#','#','#','#','#','#','#'},
};
int mouse_x = 1 , mouse_y = 1;
time_t start_time = time(NULL);
for(;;)
{
system("clear");
for(int i=0; i<10; i++)
{
for(int j=0; j<10; j++)
{
printf("%c ",maze[i][j]);
}
printf("\n");
}
if(1 == mouse_x && 9 == mouse_y)
{
printf("恭喜你走出迷宫,共用时%u秒!\n",time(NULL) - start_time);
return 0;
}
switch(getch())
{
case 183:
if(0 != mouse_x && ' '==maze[mouse_x-1][mouse_y])
{
maze[mouse_x][mouse_y] = ' ';
maze[--mouse_x][mouse_y] = '@';
}
break;
case 184:
if(9 != mouse_x && ' '==maze[mouse_x+1][mouse_y])
{
maze[mouse_x][mouse_y] = ' ';
maze[++mouse_x][mouse_y] = '@';
}
break;
case 185:
if(9 != mouse_y && ' '==maze[mouse_x][mouse_y+1])
{
maze[mouse_x][mouse_y] = ' ';
maze[mouse_x][++mouse_y] = '@';
}
break;
case 186:
if(0 != mouse_y && ' '==maze[mouse_x][mouse_y-1])
{
maze[mouse_x][mouse_y] = ' ';
maze[mouse_x][--mouse_y] = '@';
}
break;
}
}
}
运行结果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200713165921678.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NjEyNDk4NQ==,size_16,color_FFFFFF,t_70)