获取方向键的功能:使用getch.h头文件的getch函数
1、在windows中把getch.h头文件放入共享文件夹
2、终端进入共享文件夹 cd /media/sf_Share/
3、复制头文件到C标准库中 sudo cp getch.h /usr/include/
4、加读权限 sudo chmod +r /usr/include/getch.h
走迷宫思路框架:
1、定义二维字符数组作为迷宫
‘#’ 墙壁 ’ ’ 路 ‘@’ 老鼠
2、定义变量记录老鼠的位置
3、获取游戏开始的时间 time(NULL)
4、进入死循环
1、清理屏幕 使用system函数调用系统命令
2、显示迷宫(遍历二维数组)
3、检查是否到达出口
如果是:
获取游戏结束时间
结束程序
4、获取方向键并处理
判断键值:183上 184下 185右 186左
如果前面是路:
1、把新位置赋值为老鼠 @
2、把旧位置赋值为空格
3、更新老鼠的坐标为新的位置的坐标
如果前面是墙,则不需要考虑,因为程序不会给出任何反应,对应碰到墙也无法继续向前
#include <stdio.h>
#include <stdlib.h> //system("clear")
#include <getch.h> //getch()
#include <time.h> //time_t start = time(NULL)
int main(int argc,const char* argv[])
{
// 定义迷宫的二维数组
char maze[10][10] = {
{'#',' ','#','#','#','#','#','#','#','#'},
{'#',' ','#','#','#','#','#','#','#','#'},
{'#','@','#','#','#','#','#','#','#','#'},
{'#',' ','#','#',' ',' ',' ','#','#','#'},
{'#',' ','#','#',' ','#',' ','#','#','#'},
{'#',' ','#','#',' ','#',' ','#','#','#'},
{'#',' ','#','#',' ','#',' ',' ',' ','#'},
{'#',' ',' ',' ',' ','#','#','#',' ',' '},
{'#','#','#','#','#','#','#','#','#','#'},
{'#','#','#','#','#','#','#','#','#','#'}
};
// 定义变量记录老鼠位置
int mouse_x = 2,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");
}
// 判断到达出口 7 9
if(7 == mouse_x && 9 == mouse_y)
{
printf("恭喜你到达出口,总共用时%lu秒\n",time(NULL)-start_time);
return 0;
}
// 获取方向按键并处理
switch(getch())
{
case 183:
if(0 != mouse_x && ' ' == maze[mouse_x-1][mouse_y])
{
maze[mouse_x-1][mouse_y] = '@';
maze[mouse_x--][mouse_y] = ' '; //可直接对mouse_x进行--操作
}
break;
case 184:
if(9 != mouse_x && ' ' == maze[mouse_x+1][mouse_y])
{
maze[mouse_x+1][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+1] = '@';
maze[mouse_x][mouse_y++] = ' ';
}
break;
case 186:
if(0 != mouse_y && ' ' == maze[mouse_x][mouse_y-1])
{
maze[mouse_x][mouse_y-1] = '@';
maze[mouse_x][mouse_y--] = ' ';
}
break;
}
}
}
项目总结
我自己的代码采用if语句给getch赋值的形式,运行之后巨卡无比,赋值运算对于C语言的运行来说耗时太久,尤其对于getch这种函数,以后这种项目应一律使用switch case形式
183 上 184 下 185 右 186左 uint8_t == unsigned char
time(NULL)指的是从1970年1月1日到现在的秒数总和