#include <stdio.h>
#define ROW 10
#define COL 11
void myPrintMap(char arr[ROW][COL]);
void perMove(char arr[ROW][COL],int oldX, int oldY, int newX, int newY);
int main(int argc, const char * argv[]) {
//定义变量 字符串 所以是10行11列
char boxMap[ROW][COL] ={
"##########",
"#O #### #",
"# X#### #",
"# #",
"###### #",
"# #### #",
"# #",
"# ######",
"# ",
"##########"};
char direction; //方向变量
int perX = 1; //当前x
int perY = 1; //当前y
int perNewX; //下一步x
int perNewY; //下一步y
int boxX = 2;
int boxY = 2;
int boxNewX;
int boxNewY;
char street = ' '; //路
char box = 'X'; //箱子
int flag = 1;
//打印地图
myPrintMap(boxMap);
//提示用户规则
printf("请输入方向:W.上 S.下 A.左 D.右 Q.退出\n");
//循环控制程序
while(flag){
//接收输入方向
scanf("%c", &direction);
getchar();
//防穿墙
perNewX = perX;
perNewY = perY;
//判断输入的方向
switch(direction){
case 'W':
case 'w':
perNewX--;
break;
case 'S':
case 's':
perNewX++;
break;
case 'A':
case 'a':
perNewY--;
break;
case 'D':
case 'd':
perNewY++;
break;
case 'Q':
case 'q':
printf("程序已退出!!!!");
return 0;
}
//根据方向移动小人
//判断移动是否是路
if (boxMap[perNewX][perNewY] == street) {
perMove(boxMap, perX, perY, perNewX, perNewY);
perX = perNewX;
perY = perNewY;
//判断是否是箱子
}else if(boxMap[perNewX][perNewY] == box){
//判断箱子前面是否是路
boxNewX = boxX + (boxX - perX);
boxNewY = boxY + (boxY - perY);
if(boxMap[boxNewX][boxNewY] == street){
//移动小人与箱子
perMove(boxMap, boxX, boxY, boxNewX, boxNewY);
perMove(boxMap, perX, perY, boxX, boxY);
perX = perNewX;
perY = perNewY;
boxX = boxNewX;
boxY = boxNewY;
}
}
//重绘地图
myPrintMap(boxMap);
//判断箱子是否到达指定位置
if(boxY == 9){
printf("恭喜你!!!");
return 0;
}
}
return 0;
}
/**
* 打印地图
*
* @param arr 地图数组
*/
void myPrintMap(char arr[ROW][COL]){
for(int i = 0; i < ROW; i++){
printf("%s\n", arr[i]);
}
}
/**
* 交换位置
*
* @param arr 地图
* @param oldX 当前x
* @param oldY 当前y
* @param newX 路x
* @param newY 路y
*/
void perMove(char arr[ROW][COL], int oldX,int oldY, int newX,int newY){
char temp;
temp = arr[oldX][oldY];
arr[oldX][oldY] = arr[newX][newY];
arr[newX][newY] = temp;
} |