- //
- // main.c
- // MazeRunning
- //
- // Created by amos on 9/25/15.
- // Copyright (c) 2015 augmentum. All rights reserved.
- //
- #define Row 10
- #define Col 10
- #include <stdio.h>
- //定义变量记录当前位置
- int currentX = 0, currentY = 0, steps = 0;
- int nextX = 0, nextY = 0;
- //打印迷宫
- void showMaze(char maze[10][10]){
- for (int i = 0; i < Row; i++) {
- for (int j = 0; j < Col; j++) {
- printf("%c", maze[i][j]);
- }
- printf("\n");
- }
- }
- //判断是否可走
- int isAvaliable(char maze[][10],int x, int y){
- if (x > 10 || x < 0 || y > 10 > y < 0||
- '#' == maze[x][y]) {
- return 0;
- }else{
- return 1;
- }
- }
- //交换小人儿('0')位置和迷宫格(" ")位置
- void swap(char maze[10][10]){
- char temp = maze[currentX][currentY];
- maze[currentX][currentY] = maze[nextX][nextY];
- maze[nextX][nextY] = temp;
- steps++;
- currentX = nextX;
- currentY = nextY;
- showMaze(maze);
- }
- //开始行走
- void startGame(char maze[10][10]){
-
- char direction; //存储用户输入的方向:上W,下S,左A,右D
- char temp; //用来吸收键盘输入的\n
- int dX = 0,dY = 0;//小人儿下一步x轴与y轴变化
-
- while (1) {
- //等待用户输入方向
- printf("\n输入下一步走向(上W,下S,左A,右D):");
- scanf("%c",&direction);
- scanf("%c",&temp);
-
- switch (direction) {
- //向上
- case 'W':
- case 'w':
- dX = -1; dY = 0;
- break;
- //向下
- case 'S':
- case 's':
- dX = 1; dY = 0;
- break;
- //向左
- case 'A':
- case 'a':
- dX = 0; dY = -1;
- break;
- //向右
- case 'D':
- case 'd':
- dX = 0; dY = 1;
- break;
- case 'Q':
- case 'q':
- printf("正在退出游戏.....");
- return;
- default:
- //printf("按键错误.....");
- break;
- }
- nextX = currentX + dX;
- nextY = currentY + dY;
-
- if (isAvaliable(maze, nextX, nextY)) {
- swap(maze);
- //交换后查看当前位置是否已经到达门口
- if(currentY == 9){
- printf("X = %d, Y = %d\n",currentX,currentY);
- printf("Congradulations! You take %d steps in total!", steps);
- return ;
- }
- }
- }
-
- }
- int main(int argc, const char * argv[])
- {
- //初始化迷宫
- char maze[Row][Col] = {
-
- {'0','#','#','#','#','#','#','#','#','#'},
- {' ',' ','#','#','#','#',' ',' ',' ','#'},
- {'#',' ','#','#','#','#',' ','#',' ','#'},
- {'#',' ',' ',' ',' ','#',' ','#',' ','#'},
- {'#',' ',' ','#',' ',' ',' ',' ','#','#'},
- {'#','#',' ','#',' ','#','#',' ',' ','#'},
- {'#','#',' ','#',' ','#','#',' ',' ','#'},
- {'#','#',' ','#',' ','#','#','#',' ','#'},
- {'#','#',' ',' ',' ','#','#','#',' ','M'},
- {'#','#','#','#','#','#','#','#','#','#'}
- };
- //首次显示迷宫供玩儿家看
- showMaze(maze);
- //开始游戏
- startGame(maze);
- return 0;
- }
复制代码
|
|