黑马程序员——C基础之迷宫游戏

来源:互联网 发布:csol星陨巨锤连击编程 编辑:程序博客网 时间:2024/05/20 22:30

------- iOS培训、android培训、java培训、期待与您交流! ----------

#include <stdio.h>


#define row 6

#define col 6

/**

 *  打印地图

 *

 *  @param map 地图的数组

 */

void printMap(char map[row][col]){

    for (int i = 0; i <row; i++) {

        for (int j = 0; j <col; j++) {

            printf("%c",map[i][j]);

        }

        printf("\n");

    }

}

/**

 *  移动小人

 *

 *  @param map  地图的数组

 *  @param oldX 小人原来位置x坐标

 *  @param oldY 小人原来位置y坐标

 *  @param newX 小人将要移动到位置x坐标

 *  @param newY 小人将要移动到位置y坐标

 */

void personMove(char map[row][col],int oldX,int oldY,int newX,int newY){

    char temp;

    temp = map[oldX][oldY];

    map[oldX][oldY] = map[newX][newY];

    map[newX][newY] = temp;

}

int main(int argc,constchar * argv[]) {

    

    char map[row][col]={

        {'#','#','#','#','#','#'},

        {'#','0','#','#',' ',' '},

        {'#',' ','#','#',' ','#'},

        {'#',' ',' ','#',' ','#'},

        {'#','#',' ',' ',' ','#'},

        {'#','#','#','#','#','#'},

    };

    char direction;

    int currentX = 1;

    int currentY = 1;

    char street = ' ';

    printMap(map);

    printf("请控制小人移动: w. s. a. d. q.退出\n");

    //char ch;//吸收字符\n

    while (1) {

        scanf("%c",&direction);

        getchar();//吸收多余 \n

        switch (direction) {

            case 'w':

            case 'W':

                if (map[currentX-1][currentY] == street) {

                    personMove(map,currentX,currentY,currentX-1,currentY);

                    currentX--;

                }

                break;

            case 's':

            case 'S':

                if (map[currentX+1][currentY] == street) {

                    personMove(map,currentX,currentY,currentX+1,currentY);

                    currentX++;

                }

                break;

            case 'a':

            case 'A':

                if (map[currentX][currentY-1] == street) {

                    personMove(map,currentX,currentY,currentX,currentY-1);

                    currentY--;

                }

                break;

            case 'd':

            case 'D':

                if (map[currentX][currentY+1] == street) {

                    personMove(map,currentX,currentY,currentX,currentY+1);

                    currentY++;

                }

                break;

            case 'q':

            case 'Q':

                return 0;

                break;

                

            default:

                break;

        }

        printMap(map);

        if (currentY == col - 1) {

            printf("哇哦,你出来了!\n");

            break;

        }

    }

    

    return 0;

}


0 0