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1,0,1,0,1,0,0,0,1},
{1,0,1,1,1,1,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,1,0,1,0,1,0,1},
{1,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,1,0,1},
{1,1,1,0,1,0,1,1,1,0,1,0,1,1,1,0,1,0,1,0,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1},
{1,0,0,0,1,0,1,0,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1},
{1,0,1,1,1,0,1,0,1,0,1,0,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,0,1,0,1,1,1,1,1,0,1},
{1,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,1},
{1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,1,1,1,1,1,0,1,0,1,0,1},
{1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,0,0,1},
{1,0,1,1,1,0,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,0,1,0,1,1,1,0,1,0,1,0,1,0,1,1,1,1,1},
{1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,3},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
};//对数组初始化 全局变量 1 代表墙壁 2 代表人 3代表出口 0 空地
void output(void);//输出地图
int main(void)
{
char ch;
int x = 1, y = 0,i=1;
for (x = 0; x < 23; ++x)//找出人的位置
{
for (y = 0; y < 39; ++y)
{
if (plat2[x][y] == 2)
break;//break 只能结束相近的for语句 所以要在下面也要加上 if 语句
}
if (plat2[x][y] == 2)
break;
}
output();
while ( i)
{
ch = getch();
switch (ch)
{
case 's'://向下移动
case 'S':
if (plat2[x + 1][y] != 1)
{
plat2[x + 1][y] = 2;
plat2[x][y] = 0;
++x;
output();
}
break;
case 'a':
case 'A'://向左移动
if (plat2[x][y-1] != 1&&y-1!=-1)
{
plat2[x ][y-1] = 2;
plat2[x][y] = 0;
--y;
output();
}
break;
case 'd':
case 'D'://向右移动
if (plat2[x][y +1] != 1 && y + 1 != 39)
{
if (plat2[x][y+1] == 3)//判断是否到达出口
{
printf("你赢了");
i = 0;
}
else
{
plat2[x][y + 1] = 2;
plat2[x][y] = 0;
++y;
output();
}
}
break;
case 'w':
case 'W'://向下移动
if (plat2[x-1][y] != 1 && x - 1 != -1)
{
plat2[x - 1][y] = 2;
plat2[x][y] = 0;
--x;
output();
}
break;
default:
break;
}
}
system("pause");
return 0;
}
void output(void)
{
system("cls");
int x, y;
printf("\n\n");
for (x = 0; x < 23; ++x)
{
for (y = 0; y<39; ++y)
{
switch (plat2[x][y])
{
case 0:
printf(" ");
break;
case 1:
printf("※");
break;
case 2:
printf("♀");
break;
case 3:
printf("出");
break;
}
}
putchar('\n');
}
return;
}