Files
fzu-product/2023旧版内容/3.编程思维体系构建/3.4.6.9.练习:生成代码.md

2.8 KiB
Raw Blame History

9.练习:生成代码

到目前为止,我们的冒险游戏有 10 个对象。每个对象由有 5 个属性组成。一个真正的文本冒险可能有数百个甚至数千个对象,并且每个对象的属性数量也可能增加(请参阅下一章)。在目前的形式下,维护如此庞大的对象和属性列表将很困难。

例如,当我们在添加对象 wallFieldwallCave 时,我们必须在三个不同的位置执行此操作:一次在 object.h 中(作为#define),两次在 object.c 中(数组 objs 中的一个元素,以及一个单独的标签数组)。这显然十分笨拙并且容易出错。

我们将不再手工维护 object. h 和 object. c而是从更适合我们需要的单一源开始生成文件。这个新的源文件可以用你喜欢的任何语言 ( 典型的是某些特定领域的语言 ),只要你有工具把它转换回 C。下面是一个简单的例子考虑下列布局来组织我们的对象

                 /* Raw C code (declarations) */
- ObjectName
      AttributeName AttributeValue
      AttributeName AttributeValue
      ...
- ObjectName
      AttributeName AttributeValue
      AttributeName AttributeValue
      ...
- ...

根据到目前为止收集的对象,我们可以构造以下源文件。文件名并不重要;我只是简单地将其命名为object.txt,以明确它与object.hobject.c相关。

object.txt

#include <stdio.h>
#include "object.h"

typedef struct object {
   const char    *description;
   const char   **tags;
   struct object *location;
   struct object *destination;
} OBJECT;

extern OBJECT objs[];
//对象
- field
     description "an open field"
     tags        "field"

- cave
     description "a little cave"
     tags        "cave"

- silver
     description "a silver coin"
     tags        "silver", "coin", "silver coin"
     location    field

- gold
     description "a gold coin"
     tags        "gold", "coin", "gold coin"
     location    cave

- guard
     description "a burly guard"
     tags        "guard", "burly guard"
     location    field

- player
     description "yourself"
     tags        "yourself"
     location    field

- intoCave
     description "a cave entrance to the east"
     tags        "east", "entrance"
     location    field
     destination cave

- exitCave
     description "an exit to the west"
     tags        "west", "exit"
     location    cave
     destination field

- wallField
     description "dense forest all around"
     tags        "west", "north", "south", "forest"
     location    field

- wallCave
     description "solid rock all around"
     tags        "east", "north", "south", "rock"
     location    cave

::: warning 🤔 思考题:你能否自己用 C 来实现这段伪代码? :::