- #include <stdio.h>
- #define ROW 6
- #define COL 12
- int X=1,Y=1,i,j;
- char direction,temp,lu = ' ';
- void printMap(char map[ROW][COL]){
- for(i=0;i<ROW;i++){
- for(j=0;j<COL;j++){
- printf("%c",map[i][j]);
- }
- printf("\n");
- }
- }
- void peopleMove(char map[ROW][COL],int oldX,int oldY,int newX,int newY){
- temp = map[oldX][oldY];
- map[oldX][oldY] = map[newX][newY];
- map[newX][newY] = temp;
- //oldX--;
- }
- int main(){
- char map[ROW][COL]={
- {'#','#','#','#','#','#','#','#','#','#','#','#'},
- {'#','O','#','#',' ',' ',' ','#','#','#','#','#'},
- {'#',' ','#','#',' ','#',' ','#',' ',' ',' ','#'},
- {'#',' ',' ','#',' ','#',' ','#',' ','#',' ','#'},
- {'#','#',' ',' ',' ','#',' ',' ',' ','#',' ',' '},
- {'#','#','#','#','#','#','#','#','#','#','#','#'}
- };
-
-
- printMap(map);
- //printf("请控制线小人方向,w:上;s:下;a:左;d:右,请输入:\n");
- while(1){
- printf("请控制线小人方向,w:上;s:下;a:左;d:右,请输入:\n");
- scanf("%c",&direction);
- getchar();//至关重要,必须加,用于抵消输入时的换行按钮
- switch(direction){
- case 'w':
- case 'W':
- if(map[X-1][Y] == lu){
- peopleMove(map,X,Y,X-1,Y);
- X--;
- }
- break;
- case 's':
- case 'S':
- if(map[X+1][Y] == lu){
- peopleMove(map,X,Y,X+1,Y);
- X++;
- }
- break;
- case 'a':
- case 'A':
- if(map[X][Y-1] == lu){
- peopleMove(map,X,Y,X,Y-1);
- Y--;
- }
- break;
- case 'd':
- case 'D':
- if(map[X][Y+1] == lu){
- peopleMove(map,X,Y,X,Y+1);
- Y++;
- }
- break;
- case 'q':
- case 'Q':
- return 0;
- break;
- default :
- printf("请重新输入\n");
- break;
- }
- printMap(map);
- if(Y == COL-1){
- printf("恭喜你,走出来了!\n");
- return 0;
- }
-
- }
- return 0;
- }
复制代码 练习老师所讲代码,应用与实现
|
|