首页 > 代码库 > 推箱子

推箱子

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 推箱子
{
class Program
{
static void Main(string[] args)
{
//1、编地图

int[,] map = new int[10, 10]{
{1,1,1,1,1,1,1,1,1,1},
{1,4,0,0,0,1,0,0,0,1},
{1,0,0,0,0,1,0,0,0,1},
{1,0,0,2,0,1,0,0,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,4,0,0,2,0,0,0,0,1},
{1,0,0,0,0,1,0,3,0,1},
{1,0,0,2,0,1,0,0,0,1},
{1,4,0,0,0,1,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};

int x = 7;
int y = 6;

//2、设置地图中的内容
//空地=0, 墙=1,箱子=2,小人=3,目标点=4,完成点=5

while (true)
{
Console.Clear();
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (map[i, j] == 0)
Console.Write(" ");
else if (map[i, j] == 1)
Console.Write("■");
else if (map[i, j] == 2)
Console.Write("□");
else if (map[i, j] == 3)
Console.Write("♀");
else if (map[i, j] == 4)
Console.Write("☆");
else if (map[i, j] == 5)
Console.Write("★");

}
Console.WriteLine();
}

//3、动起来

ConsoleKeyInfo key = Console.ReadKey();

//向上
if (key.Key.ToString() == "UpArrow")
{
if (map[y - 1, x] == 0)//如果下一步是空地
{
int z = map[y, x];
map[y, x] = map[y - 1, x];
map[y - 1, x] = z;
y--;
}
else if (map[y - 1, x] == 2)//小人的下一步是箱子
{
if (map[y - 2, x] != 1 && map[y - 2, x] != 4)
{
//先让箱子和下一步调换
int z = map[y - 2, x];
map[y - 2, x] = map[y - 1, x];
map[y - 1, x] = z;

//让小人和下一步调换
z = map[y, x];
map[y, x] = map[y - 1, x];
map[y - 1, x] = z;
y--;
}

if (map[y - 2, x] == 4)
{
//先让箱子和下一步调换
map[y - 2, x] = 5;

//让小人和下一步调换
map[y - 1, x] = 0;
int z = map[y, x];
map[y, x] = map[y - 1, x];
map[y - 1, x] = z;
y--;
}

}
}

//向下
if (key.Key.ToString() == "DownArrow")
{
if (map[y + 1, x] == 0)//如果下一步是空地
{
int z = map[y, x];
map[y, x] = map[y + 1, x];
map[y + 1, x] = z;
y++;
}
else if (map[y + 1, x] == 2)
{
if (map[y + 2, x] != 1 && map[y + 2, x] != 4)
{
//先让箱子和下一步调换
int z = map[y + 2, x];
map[y + 2, x] = map[y + 1, x];
map[y + 1, x] = z;

//让小人和下一步调换
z = map[y, x];
map[y, x] = map[y + 1, x];
map[y + 1, x] = z;
y++;
}

if (map[y + 2, x] == 4)
{
//先让箱子和下一步调换
map[y + 2, x] = 5;

//让小人和下一步调换
map[y + 1, x] = 0;
int z = map[y, x];
map[y, x] = map[y + 1, x];
map[y + 1, x] = z;
y++;
}

}


}

//向左
if (key.Key.ToString() == "LeftArrow")
{
if (map[y, x - 1] == 0)//如果下一步是空地
{
int z = map[y, x];
map[y, x] = map[y, x - 1];
map[y, x - 1] = z;
x--;
}
else if (map[y, x-1] == 2)
{
if (map[y, x-2] != 1 && map[y, x-2] != 4)
{
//先让箱子和下一步调换
int z = map[y, x-2];
map[y , x-2] = map[y , x-1];
map[y, x-1] = z;

//让小人和下一步调换
z = map[y, x];
map[y, x] = map[y, x-1];
map[y, x-1] = z;
x--;
}

if (map[y, x-2] == 4)
{
//先让箱子和下一步调换
map[y, x-2] = 5;

//让小人和下一步调换
map[y, x-1] = 0;
int z = map[y, x];
map[y, x] = map[y, x-1];
map[y, x-1] = z;
x--;
}

}
}

//向右
if (key.Key.ToString() == "RightArrow")
{
if (map[y, x + 1] == 1)
continue;

int z = map[y, x];
map[y, x] = map[y, x + 1];
map[y, x + 1] = z;
x++;
}


}


}
}
}

推箱子