c 走迷宮
阿新 • • 發佈:2020-07-13
走迷宮
1、定義二位字元陣列作為迷宮
2、定義變記錄老鼠的位置
3、獲取遊戲開始時間
4、進入迴圈
1、清理螢幕,使用system呼叫系統命令
2、顯示迷宮(遍歷二位字元陣列)
3、檢查是否到達出口
獲取遊戲結束時間,計算走出迷宮用了多少秒
4、獲取方向鍵並處理
判斷接下來要走的位置是否是路
1、把走過的位置賦值為空格
2、把新位置賦值為人
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <getch.h> int main() { char arr[10][10]={ //自己設定迷宮路徑,' '表示路徑,'1'表示牆,'s'表示人 's',' ','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', '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', '1','1','1','1','1','1','1','1',' ','1', '1','1','1','1','1','1','1','1',' ',' '}; int lsx,lsy; time_t start_time=time(NULL); while(10!=lsy) { system("clear"); for(int i=0;i<10;i++) { for(intj=0;j<10;j++) { printf("%c",arr[i][j]); if(arr[i][j]=='s') { lsx=i; lsy=j; } } printf("\n"); } if(9==lsx && 9==lsy) { printf("恭喜你走出迷宮,共用時%u秒!\n",time(NULL)-start_time); return 0; } switch(getch()) { case 185: if(9!=lsy && arr[lsx][lsy+1]==' ') { arr[lsx][lsy+1]='s'; arr[lsx][lsy]=' '; ++lsy; } break; case 186: if(0!=lsy && arr[lsx][lsy-1]==' ') { arr[lsx][lsy-1]='s'; arr[lsx][lsy]=' '; --lsy; } break; case 184: if(9!=lsx && arr[lsx+1][lsy]==' ') { arr[lsx+1][lsy]='s'; arr[lsx][lsy]=' '; ++lsx; } break; case 183: if(0!=lsx && arr[lsx-1][lsy]==' ') { arr[lsx-1][lsy]='s'; arr[lsx][lsy]=' '; --lsx; } break; } } }
#ifndef GETCH_H #define GETCH_H #include <stdio.h> #include <termios.h> #include <unistd.h> // 修改終端的控制方式,1取消回顯、確認 2獲取資料 3還原 static int getch(void) { // 記錄終端的配置資訊 struct termios old; // 獲取終端的配置資訊 tcgetattr(STDIN_FILENO,&old); // 設定新的終端配置 struct termios _new = old; // 取消確認、回顯 _new.c_lflag &= ~(ICANON|ECHO); // 設定終端配置資訊 tcsetattr(STDIN_FILENO,TCSANOW,&_new); // 在新模式下獲取資料 unsigned int key_val = 0; do{ key_val = key_val+getchar(); }while(stdin->_IO_read_end - stdin->_IO_read_ptr); // 還原配置資訊 tcsetattr(STDIN_FILENO,TCSANOW,&old); return key_val; } #endif//GETCH_H