1.首先 Console.ReadKey(); 给他个停住属性
2.画地图:string[,] map = new string[10, 10] {
{" "," ","■","■","■","■","■","■","■","■"},
{" "," ","■"," "," "," "," ","☆"," ","■"},
{"■","■","■"," "," "," "," "," "," ","■"},
{"■"," "," "," "," "," "," "," "," ","■"},
{"■"," "," "," "," "," "," "," "," ","■"},
{"■"," "," ","□"," "," "," "," "," ","■"},
{"■"," "," "," "," "," ","■","■","■","■"},
{"■"," "," "," "," "," ","■"," "," "," "},
{"■","♀"," "," "," "," ","■"," "," "," "},
{"■","■","■","■","■","■","■"," "," "," "},
};
可以自定义地图
3. int x = 1;
int y = 8;
int end1x = 7;
int end1y = 1; 小人的初始位置
4. while (true) 打印地图
{
Console.Clear(); 清空掉所有已经打印的内容
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
Console.Write(map[i, j]);
}
Console.WriteLine();
}
5.分析情况 if (map[end1y, end1x] == "★")
{
Console.WriteLine("恭喜过关");
break;
}
ConsoleKeyInfo key = Console.ReadKey();
向上
if (key.Key.ToString() == "UpArrow")
{
小人当前的位置与要去的下一步位置内容互换
if (map[y - 1, x] == "■" 如果小人的下一步是墙,什么都不干
{
}
else 小人的下一步不是墙
{
if (map[y - 1, x] == "□" && map[y - 2, x] != "■")
{
if (map[y - 2, x] == "☆")
{
箱子的下一步是目标点,让箱子填满目标点
map[y - 2, x] = "★";
map[y - 1, x] = " ";
string temp = map[y, x];
map[y, x] = map[y - 1, x];
map[y - 1, x] = temp;
y--; 真正改变小人的位置
}
else if (map[y - 2, x] == " ")
{
推着箱子走,箱子的下一步是空地才可以走
先让箱子和箱子的下一步互换
string temp = map[y - 1, x];
map[y - 1, x] = map[y - 2, x];
map[y - 2, x] = temp;
temp = map[y, x];
map[y, x] = map[y - 1, x];
map[y - 1, x] = temp;
y--; 真正改变小人的位置
}
}
else if (map[y - 1, x] == " ")
{
正常行走
string temp = map[y, x];
map[y, x] = map[y - 1, x];
map[y - 1, x] = temp;
y--; 真正改变小人的位置
}
}
}
向下
else if (key.Key.ToString() == "DownArrow")
{
string temp = map[y, x];
map[y, x] = map[y + 1, x];
map[y + 1, x] = temp;
y++; 真正改变小人的位置
}
向左
else if (key.Key.ToString() == "LeftArrow")
{
string temp = map[y, x];
map[y, x] = map[y, x - 1];
map[y, x - 1] = temp;
x--; 真正改变小人的位置
}
向右
else if (key.Key.ToString() == "RightArrow")
{
小人当前的位置与要去的下一步位置内容互换
if (map[y, x + 1] == "■") 如果小人的下一步是墙,什么都不干
{
}
else //小人的下一步不是墙
{
if (map[y, x + 1] == "□" && map[y, x + 2] != "■")
{
先让箱子和箱子的下一步互换
string temp = map[y, x + 1];
map[y, x + 1] = map[y, x + 2];
map[y, x + 2] = temp;
temp = map[y, x];
map[y, x] = map[y, x + 1];
map[y, x + 1] = temp;
x++; 真正改变小人的位置
}
else if (map[y, x + 1] == " ")
{
正常行走
string temp = map[y, x];
map[y, x] = map[y, x + 1];
map[y, x + 1] = temp;
x++; 真正改变小人的位置
}
}
}
}
效果图: