本人用二维数组设计一个迷宫的小游戏 望各位大牛 前来优化 使用函数进行封装 而且现在为何地图总打印出两遍
#include <stdio.h>
int main(int argc, const char * argv[]) { //定义一个地图 char ch[5][5]= { {'*','*','*','*','*'}, {'*','o','*',' ',' '}, {'*',' ','*',' ','*'}, {'*',' ',' ',' ','*'}, {'*','*','*','*','*'} }; for (int i=0; i<5; i++) { for (int j=0; j<5; j++) { printf("%c",ch[j]); } printf("\n"); } int x=1; int y=1; char street= ' '; printf("请通过w,s,a,d来控制小人\n"); char direction; while (1) { scanf("%c",&direction); // char z; // scanf("\n",&z); char temp; switch (direction) { case 's': if (ch[x+1][y]==street) { temp=ch[x][y]; ch[x][y]=ch[x+1][y]; ch[x+1][y]=temp; x=x+1; } break; case 'w': if (ch[x-1][y]==street) { temp=ch[x][y]; ch[x][y]=ch[x-1][y]; ch[x-1][y]=temp; x=x-1; } break; case 'a': if (ch[x][y-1]==street) { temp=ch[x][y]; ch[x][y]=ch[x][y-1]; ch[x][y-1]=temp; y=y-1; } break; case 'd': if (ch[x][y+1]==street) { temp=ch[x][y]; ch[x][y]=ch[x][y+1]; ch[x][y+1]=temp; y=y+1; } break; default: break; } for (int i=0; i<5; i++) { for (int j=0; j<5; j++) { printf("%c",ch[j]); } printf("\n"); } if (y==4) { printf("恭喜\n"); break; } } return 0; }
|