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