1 #include <stdio.h> 2 //宏定義 maze[ROWS][COLS];行和列; 3 #define ROWS 7 4 #define COLS 6 5 //繪制迷宮(全局變量) 6 char maze[ROWS][COLS]= { 7 {'#','#','#','#','#','#'}, 8 {'#','0','#',' ',' ',' '}, 9 {'#',' ','#',' ','#','#'}, 10 {'#',' ','#',' ',' ','#'}, 11 {'#',' ',' ','#',' ','#'}, 12 {'#','#',' ',' ',' ','#'}, 13 {'#','#','#','#','#','#'} 14 }; 15 //設置X,Y坐標(全局變量); 16 int currentX=1,currentY=1; 17 //移動後的XY坐標(全局變量); 18 int nextX,nextY; 19 //看下一步是否能走 int[x][y]==' ' ; 20 char street = ' '; 21 22 //初始化函數 23 void printMaze(); 24 void moveToNextPosition(); 25 void calculateNextPosition(char direction); 26 27 28 29 int main(int argc, const char * argv[]) { 30 nextX = currentX; 31 nextY = currentY; 32 //屏幕打印出迷宮; 33 printMaze(); 34 char direction; 35 while (1) { 36 printf("請移動人物,用鍵盤W/S/A/D(上下左右)操作\n"); 37 scanf("%c",&direction); 38 calculateNextPosition(direction); 39 moveToNextPosition(); 40 printMaze(); 41 if (currentX==ROWS-1||currentY==COLS-1){ 42 printf("通關了,呵呵!"); 43 break; 44 } 45 } 46 return 0; 47 } 48 49 50 //打印地圖 51 void printMaze(){ 52 for(int i = 0;i<ROWS;i++){ 53 for (int j = 0;j<COLS;j++) { 54 printf("%c",maze[i][j]); 55 } 56 printf("\n"); 57 } 58 } 59 //移動人物 60 void moveToNextPosition(){ 61 if (maze[nextX][nextY]==street) { 62 char temp = maze[currentX][currentY]; 63 maze[currentX][currentY] = maze[nextX][nextY]; 64 maze[nextX][nextY] = temp; 65 currentX = nextX; 66 currentY = nextY; 67 68 }else{ 69 nextX = currentX; 70 nextY = currentY; 71 } 72 } 73 //計算下一個位置 74 void calculateNextPosition(char direction){ 75 switch (direction) { 76 case 'w':{ 77 nextX = currentX - 1; 78 break; 79 } 80 case 's':{ 81 nextX = currentX + 1; 82 break; 83 } 84 case 'a':{ 85 nextY = currentY - 1; 86 break; 87 } 88 case 'd':{ 89 nextY = currentY + 1; 90 break; 91 } 92 default: 93 break; 94 } 95 }