#include <stdio.h> #include <stdlib.h> #include <getch.h>
int main() { //定义一个8*8的二位数组作为地图 //0对应" “代表路,1对应”#“代表墙,2对应”@“代表人,3对应O代表目标点,4对应B代表箱子 int box[8][8]={ {0,0,1,1,1,1,0,0}, {0,0,1,3,3,1,0,0}, {0,1,1,0,3,1,1,0}, {0,1,0,0,4,3,1,0}, {1,1,0,4,0,0,1,1}, {1,0,0,1,4,4,0,1}, {1,0,0,2,0,0,0,1}, {1,1,1,1,1,1,1,1} }; int x = 6,y = 3,temp = 0; //打印地图 for(;; ) { system(“clear”); for(int i=0;i<8;i++) { for(int j=0;j<8;j++) { switch(box[i][j]) { case 0: printf(” “); break; case 1: printf(”# “); break; case 2: printf(”@ "); break; case 3: printf("O "); break; case 4: printf(“B “); break; } } printf(”\n”); } //判断游戏是否结束 if(box[1][3]==4&&box[1][4]==4&&box[2][4]==4&&box[3][5]==4) { printf(“游戏结束,一共走了%d步”,temp); return 0; } //获取按键 switch(getch()) { case 183: if(box[x-1][y] == 0) { box[x-1][y] = 2; box[x][y] = 0; x–; temp++; } else if (box[x-1][y] == 4&&box[x-2][y]!=1&&box[x-2][y]!=4) {
box[x-1][y]=2;
box[x][y] = 0;
box[x-2][y] = 4;
x--;
temp++;
}
else if (box[x-1][y] == 3)
{
box[x-1][y] = 2;
box[x][y] = 0;
x--;
temp++;
}
break;
case 184:
if(box[x+1][y] == 0)
{
box[x+1][y] = 2;
box[x][y] = 0;
x++;
temp++;
}
else if (box[x+1][y] == 4 && box[x+2][y]!=1 && box[x+2][y] !=4)
{
box[x+1][y]=2;
box[x][y] = 0;
box[x+2][y] = 4;
x++;
temp++;
}
else if (box[x+1][y] == 3)
{
box[x+1][y] = 2;
box[x][y] = 0;
x++;
temp++;
}
break;
case 185:
if(box[x][y+1] == 0)
{
box[x][y+1] = 2;
box[x][y] = 0;
y++;
temp++;
}
else if (box[x][y+1] == 4&&box[x][y+2]!=1&&box[x][y+2]!=4)
{
box[x][y+1]=2;
box[x][y] = 0;
box[x][y+2] = 4;
y++;
temp++;
}
else if (box[x][y+1] == 3)
{
box[x][y+1] = 2;
box[x][y] = 0;
y++;
temp++;
}
break;
case 186:
if(box[x][y-1] == 0)
{
box[x][y-1] = 2;
box[x][y] = 0;
y--;
temp++;
}
else if (box[x][y-1] == 4&&box[x][y-2]!=1&&box[x][y-2]!=4)
{
box[x][y-1]=2;
box[x][y] = 0;
box[x][y-2] = 4;
y--;
temp++;
}
else if (box[x][y-1] == 3)
{
box[x][y-1] = 2;
box[x][y] = 0;
y--;
temp++;
}
break;
}
if(box[2][4] == 0)
box[2][4] = 3;
if(box[1][3] == 0)
box[1][3] = 3;
if(box[1][4] == 0)
box[1][4] = 3;
if(box[3][5] == 0)
box[3][5] = 3;
}
}
|