我想设计一个基于文本的游戏,其中有一个房子作为 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"))"
}
}
我目前设计的房间布局如下所示:
我已经编写了每个房间的文本表示。 从长远来看,计划是添加不同的房屋以引入更多级别,所以如果可能的话我不想对地图进行硬编码。
我现在试图解决很长一段时间的问题是打印出房间的正确定位。 我想我可以通过编写一个算法来解决这个问题,该算法逐个解析房间并将它们相应地放置在二维数组中。
有没有人有任何可以帮助我以某种方式推进我的代码的解决方案提示?
非常感谢对我的问题给出的任何反馈。
我无法测试更多,因为我对如何解决这个问题没有更多的想法,而且搜索网络也没有太大帮助,因为大多数结果都链接到 XCode 和其他基于文本的游戏的示例代码都集成了硬编码地图。