c#编写一关推箱子游戏
时间: 2023-12-30 07:04:06 浏览: 42
以下是使用C#编写的一个关卡的推箱子游戏的示例:
```csharp
using System;
class Program
{
static void Main()
{
// 定义地图
char[,] map = new char[,]
{
{ '#', '#', '#', '#', '#', '#', '#', '#', '#', '#' },
{ '#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#' },
{ '#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#' },
{ '#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#' },
{ '#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#' },
{ '#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#' },
{ '#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#' },
{ '#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#' },
{ '#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#' },
{ '#', '#', '#', '#', '#', '#', '#', '#', '#', '#' }
};
// 定义人物和箱子的初始位置
int playerX = 1;
int playerY = 1;
int boxX = 3;
int boxY = 3;
// 游戏循环
while (true)
{
// 清空屏幕
Console.Clear();
// 绘制地图
for (int y = 0; y < map.GetLength(0); y++)
{
for (int x = 0; x < map.GetLength(1); x++)
{
if (x == playerX && y == playerY)
{
Console.Write('P'); // 绘制人物
}
else if (x == boxX && y == boxY)
{
Console.Write('B'); // 绘制箱子
}
else
{
Console.Write(map[y, x]); // 绘制地图
}
}
Console.WriteLine();
}
// 判断是否胜利
if (boxX == 7 && boxY == 7)
{
Console.WriteLine("恭喜你通关了!");
break;
}
// 获取玩家输入
ConsoleKeyInfo keyInfo = Console.ReadKey();
// 根据玩家输入移动人物和箱子
switch (keyInfo.Key)
{
case ConsoleKey.UpArrow:
if (map[playerY - 1, playerX] != '#')
{
playerY--;
if (playerX == boxX && playerY == boxY - 1 && map[boxY - 1, boxX] != '#')
{
boxY--;
}
}
break;
case ConsoleKey.DownArrow:
if (map[playerY + 1, playerX] != '#')
{
playerY++;
if (playerX == boxX && playerY == boxY + 1 && map[boxY + 1, boxX] != '#')
{
boxY++;
}
}
break;
case ConsoleKey.LeftArrow:
if (map[playerY, playerX - 1] != '#')
{
playerX--;
if (playerX == boxX - 1 && playerY == boxY && map[boxY, boxX - 1] != '#')
{
boxX--;
}
}
break;
case ConsoleKey.RightArrow:
if (map[playerY, playerX + 1] != '#')
{
playerX++;
if (playerX == boxX + 1 && playerY == boxY && map[boxY, boxX + 1] != '#')
{
boxX++;
}
}
break;
}
}
}
}
```