Take FORTRANish upper-case function names to C-style lowercase...
[open-adventure.git] / newdungeon.py
1 #!/usr/bin/python3
2
3 # This is the new open-adventure dungeon generator. It'll eventually
4 # replace the existing dungeon.c It currently outputs a .h and .c pair
5 # for C code.
6
7 import yaml
8
9 yaml_name = "adventure.yaml"
10 h_name = "newdb.h"
11 c_name = "newdb.c"
12
13 statedefines = ""
14
15 h_template = """/* Generated from adventure.yaml - do not hand-hack! */
16 #ifndef NEWDB_H
17 #define NEWDB_H
18
19 #include <stdio.h>
20 #include <stdbool.h>
21
22 #define SILENT  -1      /* no sound */
23
24 /* Symbols for cond bits */
25 #define COND_LIT        0       /* Light */
26 #define COND_OILY       1       /* If bit 2 is on: on for oil, off for water */
27 #define COND_FLUID      2       /* Liquid asset, see bit 1 */
28 #define COND_NOARRR     3       /* Pirate doesn't go here unless following */
29 #define COND_NOBACK     4       /* Cannot use "back" to move away */
30 #define COND_ABOVE      5
31 #define COND_DEEP       6       /* Deep - e.g where dwarves are active */
32 #define COND_FOREST     7       /* In the forest */
33 #define COND_FORCED     8       /* Only one way in or out of here */
34 /* Bits past 10 indicate areas of interest to "hint" routines */
35 #define COND_HBASE      10      /* Base for location hint bits */
36 #define COND_HCAVE      11      /* Trying to get into cave */
37 #define COND_HBIRD      12      /* Trying to catch bird */
38 #define COND_HSNAKE     13      /* Trying to deal with snake */
39 #define COND_HMAZE      14      /* Lost in maze */
40 #define COND_HDARK      15      /* Pondering dark room */
41 #define COND_HWITT      16      /* At Witt's End */
42 #define COND_HCLIFF     17      /* Cliff with urn */
43 #define COND_HWOODS     18      /* Lost in forest */
44 #define COND_HOGRE      19      /* Trying to deal with ogre */
45 #define COND_HJADE      20      /* Found all treasures except jade */
46
47 typedef struct {{
48   const char* inventory;
49   int plac, fixd;
50   bool is_treasure;
51   const char** longs;
52   const char** sounds;
53   const char** texts;
54 }} object_description_t;
55
56 typedef struct {{
57   const char* small;
58   const char* big;
59 }} descriptions_t;
60
61 typedef struct {{
62   descriptions_t description;
63   const long sound;
64   const bool loud;
65 }} location_t;
66
67 typedef struct {{
68   const char* query;
69   const char* yes_response;
70 }} obituary_t;
71
72 typedef struct {{
73   const int threshold;
74   const int point_loss;
75   const char* message;
76 }} turn_threshold_t;
77
78 typedef struct {{
79   const int threshold;
80   const char* message;
81 }} class_t;
82
83 typedef struct {{
84   const int number;
85   const int turns;
86   const int penalty;
87   const char* question;
88   const char* hint;
89 }} hint_t;
90
91 typedef struct {{
92   const char* word;
93   const int type;
94   const int value;
95 }} vocabulary_t;
96
97 extern const location_t locations[];
98 extern const object_description_t object_descriptions[];
99 extern const char* arbitrary_messages[];
100 extern const class_t classes[];
101 extern const turn_threshold_t turn_thresholds[];
102 extern const obituary_t obituaries[];
103 extern const hint_t hints[];
104 extern long conditions[];
105 extern const vocabulary_t vocabulary[];
106 extern const long actspk[];
107
108 #define NLOCATIONS      {}
109 #define NOBJECTS        {}
110 #define NHINTS          {}
111 #define NCLASSES        {}
112 #define NDEATHS         {}
113 #define NTHRESHOLDS     {}
114 #define NVERBS          {}
115
116 enum arbitrary_messages_refs {{
117 {}
118 }};
119
120 enum locations_refs {{
121 {}
122 }};
123
124 enum object_descriptions_refs {{
125 {}
126 }};
127
128 /* State definitions */
129
130 {}
131 #endif /* end NEWDB_H */
132 """
133
134 c_template = """/* Generated from adventure.yaml - do not hand-hack! */
135
136 #include "common.h"
137 #include "{}"
138
139 const char* arbitrary_messages[] = {{
140 {}
141 }};
142
143 const class_t classes[] = {{
144 {}
145 }};
146
147 const turn_threshold_t turn_thresholds[] = {{
148 {}
149 }};
150
151 const location_t locations[] = {{
152 {}
153 }};
154
155 const object_description_t object_descriptions[] = {{
156 {}
157 }};
158
159 const obituary_t obituaries[] = {{
160 {}
161 }};
162
163 const hint_t hints[] = {{
164 {}
165 }};
166
167 long conditions[] = {{
168 {}
169 }};
170
171 const vocabulary_t vocabulary[] = {{
172 {}
173 }};
174
175 const long actspk[] = {{
176     NO_MESSAGE,
177 {}
178 }};
179
180 /* end */
181 """
182
183 def make_c_string(string):
184     """Render a Python string into C string literal format."""
185     if string == None:
186         return "NULL"
187     string = string.replace("\n", "\\n")
188     string = string.replace("\t", "\\t")
189     string = string.replace('"', '\\"')
190     string = string.replace("'", "\\'")
191     string = '"' + string + '"'
192     return string
193
194 def get_refs(l):
195     reflist = [x[0] for x in l]
196     ref_str = ""
197     for ref in reflist:
198         ref_str += "    {},\n".format(ref)
199     ref_str = ref_str[:-1] # trim trailing newline
200     return ref_str
201
202 def get_arbitrary_messages(arb):
203     template = """    {},
204 """
205     arb_str = ""
206     for item in arb:
207         arb_str += template.format(make_c_string(item[1]))
208     arb_str = arb_str[:-1] # trim trailing newline
209     return arb_str
210
211 def get_class_messages(cls):
212     template = """    {{
213         .threshold = {},
214         .message = {},
215     }},
216 """
217     cls_str = ""
218     for item in cls:
219         threshold = item["threshold"]
220         message = make_c_string(item["message"])
221         cls_str += template.format(threshold, message)
222     cls_str = cls_str[:-1] # trim trailing newline
223     return cls_str
224
225 def get_turn_thresholds(trn):
226     template = """    {{
227         .threshold = {},
228         .point_loss = {},
229         .message = {},
230     }},
231 """
232     trn_str = ""
233     for item in trn:
234         threshold = item["threshold"]
235         point_loss = item["point_loss"]
236         message = make_c_string(item["message"])
237         trn_str += template.format(threshold, point_loss, message)
238     trn_str = trn_str[:-1] # trim trailing newline
239     return trn_str
240
241 def get_locations(loc):
242     template = """    {{ // {}
243         .description = {{
244             .small = {},
245             .big = {},
246         }},
247         .sound = {},
248         .loud = {},
249     }},
250 """
251     loc_str = ""
252     for (i, item) in enumerate(loc):
253         short_d = make_c_string(item[1]["description"]["short"])
254         long_d = make_c_string(item[1]["description"]["long"])
255         sound = item[1].get("sound", "SILENT")
256         loud = "true" if item[1].get("loud") else "false"
257         loc_str += template.format(i, short_d, long_d, sound, loud)
258     loc_str = loc_str[:-1] # trim trailing newline
259     return loc_str
260
261 def get_object_descriptions(obj):
262     template = """    {{ // {}
263         .inventory = {},
264         .plac = {},
265         .fixd = {},
266         .is_treasure = {},
267         .longs = (const char* []) {{
268 {}
269         }},
270         .sounds = (const char* []) {{
271 {}
272         }},
273         .texts = (const char* []) {{
274 {}
275         }},
276     }},
277 """
278     obj_str = ""
279     for (i, item) in enumerate(obj):
280         attr = item[1]
281         i_msg = make_c_string(attr["inventory"])
282         longs_str = ""
283         if attr["longs"] == None:
284             longs_str = " " * 12 + "NULL,"
285         else:
286             labels = []
287             for l_msg in attr["longs"]:
288                 if not isinstance(l_msg, str):
289                     labels.append(l_msg)
290                     l_msg = l_msg[1]
291                 longs_str += " " * 12 + make_c_string(l_msg) + ",\n"
292             longs_str = longs_str[:-1] # trim trailing newline
293             if labels:
294                 global statedefines
295                 statedefines += "/* States for %s */\n" % item[0]
296                 for (i, (label, message)) in enumerate(labels):
297                     if len(message) >= 45:
298                         message = message[:45] + "..."
299                     statedefines += "#define %s\t%d /* %s */\n" % (label, i, message)
300                 statedefines += "\n"
301         sounds_str = ""
302         if attr.get("sounds") == None:
303             sounds_str = " " * 12 + "NULL,"
304         else:
305              for l_msg in attr["sounds"]:
306                  sounds_str += " " * 12 + make_c_string(l_msg) + ",\n"
307              sounds_str = sounds_str[:-1] # trim trailing newline
308         texts_str = ""
309         if attr.get("texts") == None:
310             texts_str = " " * 12 + "NULL,"
311         else:
312              for l_msg in attr["texts"]:
313                  texts_str += " " * 12 + make_c_string(l_msg) + ",\n"
314              texts_str = texts_str[:-1] # trim trailing newline
315         locs = attr.get("locations", ["LOC_NOWHERE", "LOC_NOWHERE"])
316         immovable = attr.get("immovable", False)
317         try:
318             if type(locs) == str:
319                 locs = [locnames.index(locs), -1 if immovable else 0]
320             else:
321                 locs = [locnames.index(x) for x in locs]
322         except IndexError:
323             sys.stderr.write("dungeon: unknown object location in %s\n" % locs)
324             sys.exit(1)
325         treasure = "true" if attr.get("treasure") else "false"
326         obj_str += template.format(i, i_msg, locs[0], locs[1], treasure, longs_str, sounds_str, texts_str)
327     obj_str = obj_str[:-1] # trim trailing newline
328     return obj_str
329
330 def get_obituaries(obit):
331     template = """    {{
332         .query = {},
333         .yes_response = {},
334     }},
335 """
336     obit_str = ""
337     for o in obit:
338         query = make_c_string(o["query"])
339         yes = make_c_string(o["yes_response"])
340         obit_str += template.format(query, yes)
341     obit_str = obit_str[:-1] # trim trailing newline
342     return obit_str
343
344 def get_hints(hnt, arb):
345     template = """    {{
346         .number = {},
347         .penalty = {},
348         .turns = {},
349         .question = {},
350         .hint = {},
351     }},
352 """
353     hnt_str = ""
354     md = dict(arb)
355     for member in hnt:
356         item = member["hint"]
357         number = item["number"]
358         penalty = item["penalty"]
359         turns = item["turns"]
360         question = make_c_string(item["question"])
361         hint = make_c_string(item["hint"])
362         hnt_str += template.format(number, penalty, turns, question, hint)
363     hnt_str = hnt_str[:-1] # trim trailing newline
364     return hnt_str
365
366 def get_condbits(locations):
367     cnd_str = ""
368     for (name, loc) in locations:
369         conditions = loc["conditions"]
370         hints = loc.get("hints") or []
371         flaglist = []
372         for flag in conditions:
373             if conditions[flag]:
374                 flaglist.append(flag)
375         line = "|".join([("(1<<COND_%s)" % f) for f in flaglist])
376         trail = "|".join([("(1<<COND_H%s)" % f['name']) for f in hints])
377         if trail:
378             line += "|" + trail
379         if line.startswith("|"):
380             line = line[1:]
381         if not line:
382             line = "0"
383         cnd_str += "    " + line + ",\t// " + name + "\n"
384     return cnd_str
385
386 def recompose(type_word, value):
387     "Compose the internal code for a vocabulary word from its YAML entry"
388     parts = ("motion", "action", "object", "special")
389     try:
390         return value + 1000 * parts.index(type_word)
391     except KeyError:
392         sys.stderr.write("dungeon: %s is not a known word\n" % word)
393         sys.exit(1)
394     except IndexError:
395         sys.stderr.write("%s is not a known word classifier" % attrs["type"])
396         sys.exit(1)
397
398 def get_vocabulary(vocabulary):
399     template = """    {{
400         .word = {},
401         .type = {},
402         .value = {},
403     }},
404 """
405     voc_str = ""
406     for vocab in vocabulary:
407         word = make_c_string(vocab["word"])
408         type_code = recompose(vocab["type"], vocab["value"])
409         value = vocab["value"]
410         voc_str += template.format(word, type_code, value)
411     voc_str = voc_str[:-1] # trim trailing newline
412     return voc_str
413
414 def get_actspk(actspk):
415     res = ""
416     for (i, word) in actspk.items():
417         res += "    %s,\n" % word
418     return res
419
420 if __name__ == "__main__":
421     with open(yaml_name, "r") as f:
422         db = yaml.load(f)
423
424     locnames = [x[0] for x in db["locations"]]
425
426     c = c_template.format(
427         h_name,
428         get_arbitrary_messages(db["arbitrary_messages"]),
429         get_class_messages(db["classes"]),
430         get_turn_thresholds(db["turn_thresholds"]),
431         get_locations(db["locations"]),
432         get_object_descriptions(db["object_descriptions"]),
433         get_obituaries(db["obituaries"]),
434         get_hints(db["hints"], db["arbitrary_messages"]),
435         get_condbits(db["locations"]),
436         get_vocabulary(db["vocabulary"]),
437         get_actspk(db["actspk"]),
438     )
439
440     h = h_template.format(
441         len(db["locations"])-1,
442         len(db["object_descriptions"])-1,
443         len(db["hints"]),
444         len(db["classes"]),
445         len(db["obituaries"]),
446         len(db["turn_thresholds"]),
447         len(db["actspk"]),
448         get_refs(db["arbitrary_messages"]),
449         get_refs(db["locations"]),
450         get_refs(db["object_descriptions"]),
451         statedefines,
452     )
453
454     with open(h_name, "w") as hf:
455         hf.write(h)
456
457     with open(c_name, "w") as cf:
458         cf.write(c)
459
460 # end