C语言(简单游戏)-走出迷宫

 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 }

 

转载于:https://www.cnblogs.com/glchan/p/4814992.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值