走迷宫: 1、定义一个二维数组作为迷宫 2、定义老鼠的坐标 3、获取游戏开始时的时间time(NULL) 4、进入循环 1、system 清理屏幕 2、显示迷宫(遍历二维数组) 3、检查是否走出迷宫 获取游戏结束时的时间:计算出共花费多少时间 time(NULL) 是:结束程序 4、获取方向键并处理 判断接下来要走的位置是否有路 1、把新位置赋值为老鼠’@’ 2、把旧位置赋值为路 ’ ’ 3、把记录老鼠的坐标更新
代码:
#include<stdio.h> #include<getch.h> #include<stdlib.h> #include<time.h> int main(int argc,const char* argv[]) { time_t start_time = time(NULL); char map[10][10] = { {'#','#','#','#','#','#','#','#','#','#'}, {'#',' ','@','#',' ',' ',' ',' ','#','#'}, {'#',' ','#','#',' ','#','#',' ',' ','#'}, {'#',' ','#','#',' ','#','#','#','#','#'}, {'#',' ','#',' ',' ',' ','#',' ',' ',' '}, {'#',' ','#',' ','#',' ','#',' ','#','#'}, {'#',' ','#',' ','#',' ',' ',' ',' ','#'}, {'#',' ','#',' ','#','#',' ','#',' ','#'}, {'#',' ',' ',' ','#','#',' ','#',' ','#'}, {'#','#','#','#','#','#','#','#','#','#'}, }; //定义角色的坐标 char mouse_x = 1,mouse_y = 2; for(;;) { system("clear"); for(int i=0;i<10;i++) { for(int j=0;j<10;j++) { printf("%c",map[i][j]); } printf("\n"); } if(4 == mouse_x && 9 == mouse_y) { time_t end_time = time(NULL); printf("win game!\n你一共用时%d秒!\n",end_time-start_time); break; } //通过方向键移动角色一次 switch(getch()) { case 183: //向上移动 if(' ' == map[mouse_x-1][mouse_y]) { map[mouse_x-1][mouse_y] = '0'; map[mouse_x][mouse_y] = ' '; mouse_x--; } break; case 184: if(' ' == map[mouse_x+1][mouse_y]) { map[mouse_x+1][mouse_y] = '0'; map[mouse_x][mouse_y] = ' '; mouse_x++; } break; case 185: if(' ' == map[mouse_x][mouse_y+1]) { map[mouse_x][mouse_y+1] = '0'; map[mouse_x][mouse_y] = ' '; mouse_y++; } break; case 186: if(' ' == map[mouse_x][mouse_y-1]) { map[mouse_x][mouse_y-1] = '0'; map[mouse_x][mouse_y] = ' '; mouse_y--; } break; } } return 0; }