0是人,X是箱子把箱子推到最下面就成功。
#include<stdio.h>
#define ROWS 10
#define COLS 8
int x = 3;
int y = 2;
char dir = '0';
//创建一个地图
char map[ROWS][COLS] = {
{'#', '#', '#', '#', '#', '#', '#', '#'},
{'#', ' ', ' ', '#', '#', '#', '#', '#'},
{'#', ' ', 'X', '#', '#', ' ', ' ', '#'},
{'#', ' ', '0', ' ', ' ', ' ', ' ', '#'},
{'#', '#', '#', '#', '#', ' ', ' ', '#'},
{'#', '#', '#', '#', '#', '#', ' ', '#'},
{'#', ' ', ' ', '#', '#', '#', ' ', ' '},
{'#', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
{'#', ' ', '#', '#', '#', '#', '#', '#'},
{'#', ' ', '#', '#', '#', '#', '#', '#'}
};
void mademap()//打印地图
{
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 8; j++)
{
printf("%c", map[i][j]);
}
printf("\n");
}
}
void goleft()
{
if (map[x][y - 1] == ' ')//如果向左一个位置是空格则可以走
{
map[x][y] = ' ';//当前位置换成空格
y = y - 1;
map[x][y] = '0';//左边一个位置换成0
system("cls");
}
else if (map[x][y - 1] == 'X')//如果向左一个是箱子
{
if (map[x][y - 2] == ' ')
{
map[x][y - 2] = 'X';
map[x][y] = ' ';//当前位置换成空格
y = y - 1;
map[x][y] = '0';//左边一个位置换成0
system("cls");
}
else
{
system("cls");
}
}
else
{
system("cls");
}
}
void goright()
{
if (map[x][y + 1] == ' ')//如果向右一个位置是空格则可以走
{
map[x][y] = ' ';//当前位置换成空格
y = y + 1;
map[x][y] = '0';//右边一个位置换成0
system("cls");
}
else if (map[x][y + 1] == 'X')//如果向右一个是箱子
{
if (map[x][y + 2] == ' ')
{
map[x][y + 2] = 'X';
map[x][y] = ' ';//当前位置换成空格
y = y + 1;
map[x][y] = '0';//右边一个位置换成0
system("cls");
}
else
{
system("cls");
}
}
else
{
system("cls");
}
}
void goup()
{
if (map[x - 1][y] == ' ')//如果向上一个位置是空格则可以走
{
map[x][y] = ' ';//当前位置换成空格
x = x - 1;
map[x][y] = '0';//上边一个位置换成0
system("cls");
}
else if (map[x - 1][y] == 'X')//如果向上一个是箱子
{
if (map[x - 2][y] == ' ')
{
map[x - 2][y] = 'X';
map[x][y] = ' ';//当前位置换成空格
x = x - 1;
map[x][y] = '0';//上边一个位置换成0
system("cls");
}
else
{
system("cls");
}
}
else
{
system("cls");
}
}
void godown()
{
if (map[x + 1][y] == ' ')//如果向下一个位置是空格则可以走
{
map[x][y] = ' ';//当前位置换成空格
x = x + 1;
map[x][y] = '0';//下边一个位置换成0
system("cls");
}
else if (map[x + 1][y] == 'X')//如果向下一个是箱子
{
if (map[x + 2][y] == ' ')
{
map[x + 2][y] = 'X';
map[x][y] = ' ';//当前位置换成空格
x = x + 1;
map[x][y] = '0';//下边一个位置换成0
system("cls");
}
else
{
system("cls");
}
}
else
{
system("cls");
}
}
void enterDirection()
{
printf("请输入0的前进方向:w=上,s=下,a=左,d=右\n");
rewind(stdin);
scanf_s("%c", &dir);
}
int main(int argc, const char* argv[])
{
while (map[1][7] != '0')//循环
{
//地图
mademap();
//输入指令
enterDirection();
//判断条件
if (dir == 'A' || dir == 'a')
{
goleft();
}
else if (dir == 'S' || dir == 's')
{
godown();
}
else if (dir == 'D' || dir == 'd')
{
goright();
}
else if (dir == 'W' || dir == 'w')
{
goup();
}
else
{
printf("亲?请看清楚规则!");
}
if (map[9][1] == 'X')
{
system("cls");
printf("成功了。");
break;
}
}
}
难度简单把之前那个走迷宫改一下就好了 😄