2

我正在尝试制作一个简单的幼稚文字冒险游戏(基于此页面为基础)来学习 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"]
}

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

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

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

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

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

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

任何人都可以提供一些建议吗?

4

1 回答 1

5

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

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

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

room此外,为and创建一个抽象数据类型也是一个好主意items,这将保证它们实际上存在于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
...
于 2015-12-18T19:37:32.143 回答