如何生成显示文本游戏房屋布局的地图并从控制台打印出来?

问题描述 投票:0回答:0

我想设计一个基于文本的游戏,其中有一个房子作为 Swift 的布局(在 Visual Studio Code 上的 Linux VM 中编码)。 为了实现房屋布局,我有不同的“房间”对象,每个主要方向(北、东、南、西)都有出口。在指定哪个房间有哪个出口时,我还用字典结构给它分配了出口通向的房间。

enum Direction:String {
    /// 4 main cardinal points
    case North, East, South, West
}

/// A rudimentary implementation of a room (location) within the game map, based on a name and exits to other rooms. The exits are labeled with a `Direction`.
class Room {
    
    /// The name of the room (does not need to be an identifier)
    var name:String
    
    /// The exit map (initially empty)
    var exits = [Direction:Room]()
    
    /// Initializer
    init(name:String) {
        self.name = name
    }

    /**
     This function allows to retrieve a neighboring room based on its exit direction from inside the current room.
     
     - Parameters:
        - direction: A `Direction`
     - Returns: The room through the exit in the next direction (if any)
     */
    func nextRoom(direction:Direction) -> Room? {
        return exits[direction]
    }
    
}

/// Extension for the `CustomStringConvertible` protocol.
extension Room:CustomStringConvertible {

    /// The description includes the name of the room as well as all possible exit directions
    var description: String {
        return "You are in \(self.name)\n\nExits:\n\(self.exits.keys.map { "- \($0.rawValue)" }.joined(separator: "\n"))"
    }
    
}

我目前设计的房间布局如下所示:

Diagram of the house's room layout

我已经编写了每个房间的文本表示。 从长远来看,计划是添加不同的房屋以引入更多级别,所以如果可能的话我不想对地图进行硬编码。

我现在试图解决很长一段时间的问题是打印出房间的正确定位。 我想我可以通过编写一个算法来解决这个问题,该算法逐个解析房间并将它们相应地放置在二维数组中。

有没有人有任何可以帮助我以某种方式推进我的代码的解决方案提示?

非常感谢对我的问题给出的任何反馈。

  • 我试着水平分割房间,从最左边的房间开始逐个解析第一排房间,然后推进到最右边的房间。然后我会为每个房间分配一个 x 和 y 坐标,然后继续到下一个房间。一旦我到达最右边的房间,我就会继续到下面一排最左边的房间并重复这个过程。我会对每一行都这样做,但我注意到打印出那个版本的地图会将房间定位在错误的位置(例如厨房将与浴室对齐,等等)
  • 我还尝试用我放在房子外边缘的“空房间”来扩展房子的布局,我认为这样一来,解析时的定位就会与以前不同。它不是。

我无法测试更多,因为我对如何解决这个问题没有更多的想法,而且搜索网络也没有太大帮助,因为大多数结果都链接到 XCode 和其他基于文本的游戏的示例代码都集成了硬编码地图。

arrays swift console-application ascii-art text-based
© www.soinside.com 2019 - 2024. All rights reserved.