
以下是一个简单的用C#编写推箱子游戏的示例结构:
一、创建游戏地图类

- 首先定义地图类的基本结构
- 我们可以使用二维数组来表示游戏地图。例如,定义一个
Map类。
- 我们可以使用二维数组来表示游戏地图。例如,定义一个
classMap { privateint[,] mapArray; privateint width; privateint height; publicMap(int width, int height) { this.width = width; this.height = height; mapArray = newint[width, height]; } publicintGetWidth() { return width; } publicintGetHeight() { return height; } publicintGetCellValue(int x, int y) { return mapArray[x, y]; } publicvoidSetCellValue(int x, int y, intvalue) { mapArray[x, y] = value; } }
二、创建角色类(玩家)
- 定义玩家类
Player- 包含玩家的位置信息等。
classPlayer { privateint x; privateint y; publicPlayer(int startX, int startY) { x = startX; y = startY; } publicintGetX() { return x; } publicintGetY() { return y; } publicvoidMove(int dx, int dy, Map map) { int newX = x + dx; int newY = y + dy; if (newX >= 0 && newX < map.GetWidth() && newY >= 0 && newY < map.GetHeight()) { if (map.GetCellValue(newX, newY) == 0) {x = newX;y = newY; } elseif (map.GetCellValue(newX, newY) == 2) {int boxX = newX + dx;int boxY = newY + dy;if (boxX >= 0 && boxX < map.GetWidth() && boxY >= 0 && boxY < map.GetHeight()){ if (map.GetCellValue(boxX, boxY) == 0) { map.SetCellValue(boxX, boxY, 2); map.SetCellValue(newX, newY, 0); x = newX; y = newY; }} } } } }
三、游戏主逻辑类
- 创建
Game类来控制游戏流程
classGame { private Map map; private Player player; publicGame() { map = new Map(8, 8); // 初始化地图,例如设置墙壁(1)、箱子(2)、目标点(3)等 map.SetCellValue(1, 1, 1); map.SetCellValue(2, 2, 2); map.SetCellValue(3, 3, 3); player = new Player(0, 0); } publicvoidRun() { while (true) { // 绘制地图 DrawMap(); ConsoleKeyInfo keyInfo = Console.ReadKey(); int dx = 0; int dy = 0; switch (keyInfo.Key) {case ConsoleKey.UpArrow: dy = -1; break;case ConsoleKey.DownArrow: dy = 1; break;case ConsoleKey.LeftArrow: dx = -1; break;case ConsoleKey.RightArrow: dx = 1; break;case ConsoleKey.Escape: return; } player.Move(dx, dy, map); } } privatevoidDrawMap() { for (int i = 0; i < map.GetHeight(); i++) { for (int j = 0; j < map.GetWidth(); j++) {if (map.GetCellValue(j, i) == 1){ Console.Write("#");}elseif (map.GetCellValue(j, i) == 2){ Console.Write("O");}elseif (map.GetCellValue(j, i) == 3){ Console.Write(".");}elseif (j == player.GetX() && i == player.GetY()){ Console.Write("@");}else{ Console.Write(" ");} } Console.WriteLine(); } } }
四、启动游戏
- 在
Main方法中启动游戏
classProgram { staticvoidMain() { Game game = new Game(); game.Run(); } }
这个示例只是一个简单的推箱子游戏的基础框架,还可以进一步完善,比如增加关卡、更好的界面显示、错误处理等功能。
