#define Row 10
#define Col 24
#include <stdio.h>
/**
* 交换小人和路
*
* @param a 地图数组
* @param oldX 小人移动前的旧的X坐标
* @param oldY 小人移动前的旧的Y坐标
* @param newX 小人移动后的新的X坐标
* @param newY 小人移动后的新的Y坐标
*/
void changePerson(char a[Row][Col],int oldX,int oldY,int newX,int newY){
char stemp;
stemp = a[oldX][oldY];
a[oldX][oldY]=a[newX][newY];
a[newX][newY]=stemp;
}
/**
* 打印地图
*
* @param a 地图数组
*/
void printMap(char a[Row][Col]){
for (int i=0; i<Row; i++) {
for (int j=0; j<Col; j++) {
printf("%c",a[i][j]);
}
printf("\n");
}
}
int main(int argc, const char * argv[]) {
// 定义地图,小人的坐标,接收用户输入的方向
char direction;
int peopleX=1,peopleY=1,oldX,oldY;
char Map[Row][Col]={
{'#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#'},
{'#','0','#','#',' ',' ',' ',' ','#','#',' ',' ',' ',' ','#','#',' ',' ',' ',' ','#','#',' ',' '},
{'#',' ','#','#',' ','#','#',' ',' ','#',' ','#','#',' ','#','#',' ','#','#',' ',' ','#',' ','#'},
{'#',' ','#','#',' ',' ',' ','#',' ','#',' ','#','#',' ','#','#',' ',' ',' ','#',' ','#',' ','#'},
{'#',' ',' ','#','#','#',' ','#',' ','#',' ','#','#',' ',' ','#','#','#',' ','#',' ','#',' ','#'},
{'#','#',' ','#',' ',' ',' ','#',' ','#',' ','#','#','#',' ','#',' ',' ',' ','#',' ','#',' ','#'},
{'#','#',' ','#',' ','#','#','#',' ','#',' ','#','#','#',' ','#',' ','#','#','#',' ','#',' ','#'},
{'#','#',' ',' ',' ','#','#','#',' ',' ',' ','#','#','#',' ',' ',' ','#','#','#',' ',' ',' ','#'},
{'#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#'},
{'#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#'}
};
//打印地图
printMap(Map);
//提示用户开始玩游戏
//循环判断小人移动
printf("游戏开始!\n请控制小人移动: w.上 s.下 a.左 d.右 q.退出\n");
while (1) {
//自动走出迷宫
if(Map[peopleX-1][peopleY]==' '&& peopleX-1!=oldX && peopleY!=oldY){
direction='w';
}
if(Map[peopleX+1][peopleY]==' '&& peopleX+1!=oldX && peopleY!=oldY){
direction='s';
}
if(Map[peopleX][peopleY-1]==' '&& peopleX!=oldX && peopleY-1!=oldY){
direction='a';
}
if(Map[peopleX][peopleY+1]==' '&& peopleX!=oldX && peopleY+1!=oldY){
direction='d';
}
//手动接收用户输入的信息
// scanf("%c",&direction);
// getchar(); //吸收多余的 \n
oldX=peopleX;
oldY=peopleY;
//判断小人移动的方向
switch (direction) {
case 'w':
case 'W':
if (Map[peopleX-1][peopleY]==' ') {
changePerson(Map, peopleX, peopleY, peopleX-1, peopleY);//交换小人和路
peopleX--;//小人坐标更新
}
break;
case 's':
case 'S':
if (Map[peopleX+1][peopleY]==' ') {
changePerson(Map, peopleX, peopleY, peopleX+1, peopleY);
peopleX++;
}
break;
case 'a':
case 'A':
if (Map[peopleX][peopleY-1]==' ') {
changePerson(Map, peopleX, peopleY, peopleX, peopleY-1);
peopleY--;
}
break;
case 'd':
case 'D':
if (Map[peopleX][peopleY+1]==' ') {
changePerson(Map, peopleX, peopleY, peopleX, peopleY+1);
peopleY++;
}
break;
case 'q':
case 'Q':
return 0;
break;
default:
break;
}
//重绘地图
printMap(Map);
//判断小人是否走出迷宫
if(peopleY==Col-1){
printf("哇哦!太棒了!你走出迷宫了!\n");
break;
}
for (int i=0; i<100000000; i++);
}
return 0;
}
|
|