用C语言写迷宫
思路: 1、定义一个二维数组作为迷宫 0 ‘ ’ 1 ‘#’ 2 ‘@’ 2、定义两个变量来记录老鼠的坐标 3、记录游戏开始时间 4、进入死循环 (1)清理屏幕system(“clear”); (2)显示迷宫(遍历打印二位数组) (3)判断是否到达出口 是:获取游戏结束时间 结束程序 (4)获取方向键并处理 判断前方是否是路 是: 1、旧位置=0; 2、新位置=2; 3、更新老鼠的位置
#include <stdio.h> #include <getch.h> #include <time.h> #include <stdlib.h>
int main(int argc,const char* argv[]) { //定义迷宫 char arr[10][10] = { {1,1,1,1,1,1,1,1,1,1}, {1,0,2,0,1,1,1,1,1,1}, {1,0,1,1,1,1,1,1,1,1}, {1,0,1,1,1,1,1,1,1,1}, {1,0,0,0,1,1,1,0,0,0}, {1,1,1,0,1,1,1,0,1,1}, {1,1,1,0,0,0,0,0,1,1}, {1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1}, };
//定义老鼠坐标
int mouse_x = 1,mouse_y = 2;
//获取开始时间
time_t start_time = time(NULL);
for(;;)
{
//清理屏幕
system("clear");
for(int i=0; i<10; i++)
{
for(int j=0; j<10; j++)
{
switch(arr[i][j])
{
case 0: printf(" ");break;
case 1: printf("# ");break;
case 2: printf("@ ");break;
}
}
printf("\n");
}
//判断是否到达出口
if(4 == mouse_x && 9 == mouse_y)
{
time_t end_time = time(NULL);
printf("成功走出迷宫,耗时%lu\n",end_time-start_time);
return 0;
}
//获取方向键并处理
switch(getch())
{
case 183:
if(0 == arr[mouse_x-1][mouse_y] && 0 != mouse_x)
{
arr[mouse_x][mouse_y] = 0;
arr[--mouse_x][mouse_y] = 2;
} break;
case 184:
if(0 == arr[mouse_x+1][mouse_y] && 9 != mouse_x)
{
arr[mouse_x][mouse_y] = 0;
arr[++mouse_x][mouse_y] = 2;
} break;
case 185:
if(0 == arr[mouse_x][mouse_y+1] && 9 != mouse_y)
{
arr[mouse_x][mouse_y] = 0;
arr[mouse_x][++mouse_y] = 2;
} break;
case 186:
if(0 == arr[mouse_x][mouse_y-1] && 0 != mouse_y)
{
arr[mouse_x][mouse_y] = 0;
arr[mouse_x][--mouse_y] = 2;
} break;
}
}
}
|