C语言推箱子
#include <stdio.h>
#include <windows.h>
#include <conio.h>
//地图规格
#define Width 8
#define Height 8
//地图元素
#define Blank 0
#define Wall 1
#define Target 2 //目标位置
#define Box 3
#define RightBox 4 //已经放对位置的箱子
//人的初始位置
#define StartX 6
#define StartY 5
int map [Height][Width]={
{1 , 1 , 1 , 1 , 1 , 1 , 1 , 1},
{1 , 0 , 0 , 0 , 1 , 0 , 0 , 1},
{1 , 0 , 1 , 0 , 1 , 3 , 2 , 1},
{1 , 0 , 0 , 0 , 0 , 3 , 2 , 1},
{1 , 0 , 1 , 0 , 1 , 3 , 2 , 1},
{1 , 0 , 0 , 0 , 1 , 0 , 0 , 1},
{1 , 1 , 1 , 1 , 1 , 0 , 0 , 1},
{0 , 0 , 0 , 0 , 1 , 1 , 1 , 1}};
int boxmap [Height][Width];
//存储箱子位置的地图
int x , y;
//存储人的位置
//将map的箱子保存在boxmap的相应位置
void InitMap()
{
int i , j;
x = StartX;
y = StartY;
for(i = 0; i < Height; i++)
for(j = 0; j < Width; j++)
boxmap [i][j] = Blank;
for(i = 0; i < Height; i++)
for(j = 0; j < Width; j++)
{
if(map [i][j] == Box)
{
boxmap [i][j] = Box;
map [i][j] = Blank;
}
if(map [i][j] == RightBox)
{
boxmap [i][j] = Box;
map [i][j] = Target;
}
}
}
void DrawMap()
{
int i , j;
for(i = 0; i < Height; i++)
{
for(j = 0; j < Width; j++)
{
if(i == x && j == y)
printf("m");
else
{
if(boxmap [i][j] == Box)
{
if(map [i][j] == Target)
printf("@");
else
printf("O");
}
else
{
switch(map[i][j])
{
case Blank:
printf(" ");
break;
case Wall:
printf("#");
break;
case Target:
printf("*");
break;
}
}
}
}
putchar('\n');
}
}
void Move(int xMove , int yMove)
{ //人的前面是个箱子
if(boxmap [x + xMove][y + yMove] == Box)
{ //如果箱子前面不是箱子并且也不是墙,那么就移动箱子和人
if(boxmap [x + 2 * xMove][y + 2 * yMove] != Box && map [x + 2 * xMove][y + 2 * yMove] != Wall)
{
boxmap [x + xMove][y + yMove] = Blank;
boxmap [x + 2 * xMove][y + 2 * yMove] = Box;
x += xMove;
y += yMove;
}
}
else
{ //如果人前面不是墙或箱子就移动
if(map [x + xMove][y + yMove] != Wall)
{
x += xMove;
y += yMove;
}
}
}
int judge()
{
int win = 1;
int i , j;
for(i = 0; i < Height; i++)
for(j = 0; j < Width; j++)
if(boxmap [i][j] == Box && map [i][j] != Target)
win = 0;
return win;
}
void gotoxy(int x , int y)
{
COORD point = { x, y };
HANDLE HOutput = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(HOutput, point);
}
int main()
{
char input;
InitMap();
while(!judge())
{
gotoxy(0,0);
DrawMap();
input = getch();
switch(input)
{
case 'w':
Move(-1 , 0);
break;
case 's':
Move(1 , 0);
break;
case 'a':
Move(0 , -1);
break;
case 'd':
Move(0 , 1);
break;
}
}
printf("\n-------You won--------\n");
}
来源:CSDN
作者:勇不言败_1234
链接:https://blog.csdn.net/YBYB_1234/article/details/104343281