Rationalize names of structure array sizes.
[open-adventure.git] / newdungeon.py
1 #!/usr/bin/python3
2
3 # This is the new open-adventure dungeon generator. It'll eventually replace the existing dungeon.c It currently outputs a .h and .c pair for C code.
4
5 import yaml
6
7 yaml_name = "adventure.yaml"
8 h_name = "newdb.h"
9 c_name = "newdb.c"
10
11 statedefines = ""
12
13 h_template = """/* Generated from adventure.yaml - do not hand-hack! */
14 #ifndef NEWDB_H
15 #define NEWDB_H
16
17 #include <stdio.h>
18 #include <stdbool.h>
19
20 #define SILENT  -1      /* no sound */
21
22 typedef struct {{
23   const char* inventory;
24   const char** longs;
25   const char** sounds;
26   const char** texts;
27 }} object_description_t;
28
29 typedef struct {{
30   const char* small;
31   const char* big;
32 }} descriptions_t;
33
34 typedef struct {{
35   descriptions_t description;
36   const long sound;
37   const bool loud;
38 }} location_t;
39
40 typedef struct {{
41   const char* query;
42   const char* yes_response;
43 }} obituary_t;
44
45 typedef struct {{
46   const int threshold;
47   const int point_loss;
48   const char* message;
49 }} turn_threshold_t;
50
51 typedef struct {{
52   const int threshold;
53   const char* message;
54 }} class_t;
55
56 typedef struct {{
57   const int number;
58   const int turns;
59   const int penalty;
60   const char* question;
61   const char* hint;
62 }} hint_t;
63
64 extern location_t locations[];
65 extern object_description_t object_descriptions[];
66 extern const char* arbitrary_messages[];
67 extern const class_t classes[];
68 extern turn_threshold_t turn_thresholds[];
69 extern obituary_t obituaries[];
70 extern hint_t hints[];
71 extern long conditions[];
72
73 #define NHINTS          {}
74 #define NCLASSES        {}
75 #define NDEATHS         {}
76 #define NTHRESHOLDS     {}
77
78 enum arbitrary_messages_refs {{
79 {}
80 }};
81
82 enum locations_refs {{
83 {}
84 }};
85
86 enum object_descriptions_refs {{
87 {}
88 }};
89
90 /* State definitions */
91
92 {}
93 #endif /* end NEWDB_H */
94 """
95
96 c_template = """/* Generated from adventure.yaml - do not hand-hack! */
97
98 #include "common.h"
99 #include "{}"
100
101 const char* arbitrary_messages[] = {{
102 {}
103 }};
104
105 const class_t classes[] = {{
106 {}
107 }};
108
109 turn_threshold_t turn_thresholds[] = {{
110 {}
111 }};
112
113 location_t locations[] = {{
114 {}
115 }};
116
117 object_description_t object_descriptions[] = {{
118 {}
119 }};
120
121 obituary_t obituaries[] = {{
122 {}
123 }};
124
125 hint_t hints[] = {{
126 {}
127 }};
128
129 long conditions[] = {{
130 {}
131 }};
132
133 /* end */
134 """
135
136 def make_c_string(string):
137     """Render a Python string into C string literal format."""
138     if string == None:
139         return "NULL"
140     string = string.replace("\n", "\\n")
141     string = string.replace("\t", "\\t")
142     string = string.replace('"', '\\"')
143     string = string.replace("'", "\\'")
144     string = '"' + string + '"'
145     return string
146
147 def get_refs(l):
148     reflist = [x[0] for x in l]
149     ref_str = ""
150     for ref in reflist:
151         ref_str += "    {},\n".format(ref)
152     ref_str = ref_str[:-1] # trim trailing newline
153     return ref_str
154
155 def get_arbitrary_messages(arb):
156     template = """    {},
157 """
158     arb_str = ""
159     for item in arb:
160         arb_str += template.format(make_c_string(item[1]))
161     arb_str = arb_str[:-1] # trim trailing newline
162     return arb_str
163
164 def get_class_messages(cls):
165     template = """    {{
166         .threshold = {},
167         .message = {},
168     }},
169 """
170     cls_str = ""
171     for item in cls:
172         threshold = item["threshold"]
173         message = make_c_string(item["message"])
174         cls_str += template.format(threshold, message)
175     cls_str = cls_str[:-1] # trim trailing newline
176     return cls_str
177
178 def get_turn_thresholds(trn):
179     template = """    {{
180         .threshold = {},
181         .point_loss = {},
182         .message = {},
183     }},
184 """
185     trn_str = ""
186     for item in trn:
187         threshold = item["threshold"]
188         point_loss = item["point_loss"]
189         message = make_c_string(item["message"])
190         trn_str += template.format(threshold, point_loss, message)
191     trn_str = trn_str[:-1] # trim trailing newline
192     return trn_str
193
194 def get_locations(loc):
195     template = """    {{
196         .description = {{
197             .small = {},
198             .big = {},
199         }},
200         .sound = {},
201         .loud = {},
202     }},
203 """
204     loc_str = ""
205     for item in loc:
206         short_d = make_c_string(item[1]["description"]["short"])
207         long_d = make_c_string(item[1]["description"]["long"])
208         sound = item[1].get("sound", "SILENT")
209         loud = "true" if item[1].get("loud") else "false"
210         loc_str += template.format(short_d, long_d, sound, loud)
211     loc_str = loc_str[:-1] # trim trailing newline
212     return loc_str
213
214 def get_object_descriptions(obj):
215     template = """    {{
216         .inventory = {},
217         .longs = (const char* []) {{
218 {}
219         }},
220         .sounds = (const char* []) {{
221 {}
222         }},
223         .texts = (const char* []) {{
224 {}
225         }},
226     }},
227 """
228     obj_str = ""
229     for item in obj:
230         i_msg = make_c_string(item[1]["inventory"])
231         longs_str = ""
232         if item[1]["longs"] == None:
233             longs_str = " " * 12 + "NULL,"
234         else:
235             labels = []
236             for l_msg in item[1]["longs"]:
237                 if not isinstance(l_msg, str):
238                     labels.append(l_msg)
239                     l_msg = l_msg[1]
240                 longs_str += " " * 12 + make_c_string(l_msg) + ",\n"
241             longs_str = longs_str[:-1] # trim trailing newline
242             if labels:
243                 global statedefines
244                 statedefines += "/* States for %s */\n" % item[0]
245                 for (i, (label, message)) in enumerate(labels):
246                     if len(message) >= 45:
247                         message = message[:45] + "..."
248                     statedefines += "#define %s\t%d /* %s */\n" % (label, i, message)
249                 statedefines += "\n"
250         sounds_str = ""
251         if item[1].get("sounds") == None:
252             sounds_str = " " * 12 + "NULL,"
253         else:
254              for l_msg in item[1]["sounds"]:
255                  sounds_str += " " * 12 + make_c_string(l_msg) + ",\n"
256              sounds_str = sounds_str[:-1] # trim trailing newline
257         texts_str = ""
258         if item[1].get("texts") == None:
259             texts_str = " " * 12 + "NULL,"
260         else:
261              for l_msg in item[1]["texts"]:
262                  texts_str += " " * 12 + make_c_string(l_msg) + ",\n"
263              texts_str = texts_str[:-1] # trim trailing newline
264         obj_str += template.format(i_msg, longs_str, sounds_str, texts_str)
265     obj_str = obj_str[:-1] # trim trailing newline
266     return obj_str
267
268 def get_obituaries(obit):
269     template = """    {{
270         .query = {},
271         .yes_response = {},
272     }},
273 """
274     obit_str = ""
275     for o in obit:
276         query = make_c_string(o["query"])
277         yes = make_c_string(o["yes_response"])
278         obit_str += template.format(query, yes)
279     obit_str = obit_str[:-1] # trim trailing newline
280     return obit_str
281
282 def get_hints(hnt, arb):
283     template = """    {{
284         .number = {},
285         .penalty = {},
286         .turns = {},
287         .question = {},
288         .hint = {},
289     }},
290 """
291     hnt_str = ""
292     md = dict(arb)
293     for member in hnt:
294         item = member["hint"]
295         number = item["number"]
296         penalty = item["penalty"]
297         turns = item["turns"]
298         question = make_c_string(md[item["question"]])
299         hint = make_c_string(md[item["hint"]])
300         hnt_str += template.format(number, penalty, turns, question, hint)
301     hnt_str = hnt_str[:-1] # trim trailing newline
302     return hnt_str
303
304 def get_condbits(locations):
305     cnd_str = ""
306     for (name, loc) in locations:
307         conditions = loc["conditions"]
308         hints = loc.get("hints") or []
309         flaglist = []
310         for flag in conditions:
311             if conditions[flag]:
312                 flaglist.append(flag)
313         line = "|".join([("(1<<COND_%s)" % f) for f in flaglist])
314         trail = "|".join([("(1<<COND_H%s)" % f['name']) for f in hints])
315         if trail:
316             line += "|" + trail
317         if line.startswith("|"):
318             line = line[1:]
319         if not line:
320             line = "0"
321         cnd_str += "    " + line + ",\t// " + name + "\n"
322     return cnd_str
323
324 if __name__ == "__main__":
325     with open(yaml_name, "r") as f:
326         db = yaml.load(f)
327
328     c = c_template.format(
329         h_name,
330         get_arbitrary_messages(db["arbitrary_messages"]),
331         get_class_messages(db["classes"]),
332         get_turn_thresholds(db["turn_thresholds"]),
333         get_locations(db["locations"]),
334         get_object_descriptions(db["object_descriptions"]),
335         get_obituaries(db["obituaries"]),
336         get_hints(db["hints"], db["arbitrary_messages"]),
337         get_condbits(db["locations"]),
338     )
339
340     h = h_template.format(
341         len(db["hints"]),
342         len(db["classes"]),
343         len(db["obituaries"]),
344         len(db["turn_thresholds"]),
345         get_refs(db["arbitrary_messages"]),
346         get_refs(db["locations"]),
347         get_refs(db["object_descriptions"]),
348         statedefines,
349     )
350
351     with open(h_name, "w") as hf:
352         hf.write(h)
353
354     with open(c_name, "w") as cf:
355         cf.write(c)
356
357 # end