【问题标题】:OCaml: design datatypes for a text adventure gameOCaml:为文本冒险游戏设计数据类型
【发布时间】:2016-03-25 13:37:36
【问题描述】:

我正在尝试制作一个简单的幼稚文字冒险游戏(base one this page)来学习 OCaml。

这款游戏是关于制作游戏引擎的,所以所有关于房间、物品等的信息都存储在一个 json 文件中。

示例 json 文件如下所示:

{
  "rooms":
  [
    {
      "id": "room1",
      "description": "This is Room 1.  There is an exit to the north.\nYou should drop the white hat here.",
      "items": ["black hat"],
      "points": 10,
      "exits": [
        {
          "direction": "north",
          "room": "room2"
        }
      ],
      "treasure": ["white hat"]
    },
    {
      "id": "room2",
      "description": "This is Room 2.  There is an exit to the south.\nYou should drop the black hat here.",
      "items": [],
      "points": 10,
      "exits": [
        {
          "direction": "south",
          "room": "room1"
        }
      ],
      "treasure": ["black hat"]
    }
  ],
  "start_room": "room1",
  "items":
  [
    {
      "id": "black hat",
      "description": "A black fedora",
      "points": 100
    },
    {
      "id": "white hat",
      "description": "A white panama",
      "points": 100
    }
  ],
  "start_items": ["white hat"]
}

我几乎完成了游戏,但在项目描述页面上,它说有两个目标是

  • 设计用户定义的数据类型,尤其是记录和变体。
  • 编写在列表和树上使用模式匹配和高阶函数的代码。

但是,我制作的唯一用户定义数据类型是用于捕获游戏当前状态的记录类型,我没有使用树和变体:

type state = {
  current_inventory : string list ;
  current_room      : string ;
  current_score     : int ;
  current_turn      : int ;
}

然后只需解析用户输入并使用模式匹配来处理不同的情况。

我一直在试图弄清楚我应该如何在我的游戏中使用 variant(或多态变体)tree

谁能给点建议?

【问题讨论】:

    标签: data-structures ocaml game-engine adventure


    【解决方案1】:

    json 本质上是一棵树。当然,您可以在没有内存表示的情况下解析 json,并在您通过 json 数据下降时执行副作用计算,以使用您已读取的数据填充哈希表。这是一个有效的选项,但看起来就像课程作者期望的那样,您首先读取整个 json 并将其在内存中表示为树,然后在树上执行查找。

    关于变体,你应该用变体类型表示以下数据:

    1. 移动方向:type dir = N | NE | E ...
    2. 动词type verb = Go | Take of item | Drop of item

    另外,为roomitems 创建一个抽象数据类型是个好主意,这将保证它们确实存在于json 数据库中。您正在使用string 来代表他们。但是这种类型包括所有值,包括那些不代表有效标识符的值,以及那些不在游戏描述文件中出现的值。库存物品也值得拥有自己的类型。

    一般在类型系统丰富的语言中,你应该尽量用类型系统来表达。

    为了不那么理论,如果我是你,那么我的游戏中将有以下类型(作为第一个近似值):

    type game
    type room
    type item
    type verb 
    type dir
    type treasure
    type state
    
    (** a static representation of a game (using a tree inside) *)
    module Game : sig 
      type t = game
      val from_json : string -> t option
      val start : t -> room
      val room_exits : t -> room -> (dir * room) list
    end
    
    module Room : sig
      type t = room
      val description : t -> string
      val items : t -> item list
      val points : t -> int
      val treasure : t -> treasure list
    end
    ...
    

    【讨论】:

    • 感谢您的建议,很有帮助
    猜你喜欢
    • 2011-03-17
    • 2016-08-25
    • 2013-07-08
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 2021-06-23
    相关资源
    最近更新 更多