3399cafa1a01205208e945ae8fe68c19e76878cf
[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 #define NVOCAB          {}
116
117 enum arbitrary_messages_refs {{
118 {}
119 }};
120
121 enum locations_refs {{
122 {}
123 }};
124
125 enum object_descriptions_refs {{
126 {}
127 }};
128
129 /* State definitions */
130
131 {}
132 #endif /* end NEWDB_H */
133 """
134
135 c_template = """/* Generated from adventure.yaml - do not hand-hack! */
136
137 #include "common.h"
138 #include "{}"
139
140 const char* arbitrary_messages[] = {{
141 {}
142 }};
143
144 const class_t classes[] = {{
145 {}
146 }};
147
148 const turn_threshold_t turn_thresholds[] = {{
149 {}
150 }};
151
152 const location_t locations[] = {{
153 {}
154 }};
155
156 const object_description_t object_descriptions[] = {{
157 {}
158 }};
159
160 const obituary_t obituaries[] = {{
161 {}
162 }};
163
164 const hint_t hints[] = {{
165 {}
166 }};
167
168 long conditions[] = {{
169 {}
170 }};
171
172 const vocabulary_t vocabulary[] = {{
173 {}
174 }};
175
176 const long actspk[] = {{
177     NO_MESSAGE,
178 {}
179 }};
180
181 /* end */
182 """
183
184 def make_c_string(string):
185     """Render a Python string into C string literal format."""
186     if string == None:
187         return "NULL"
188     string = string.replace("\n", "\\n")
189     string = string.replace("\t", "\\t")
190     string = string.replace('"', '\\"')
191     string = string.replace("'", "\\'")
192     string = '"' + string + '"'
193     return string
194
195 def get_refs(l):
196     reflist = [x[0] for x in l]
197     ref_str = ""
198     for ref in reflist:
199         ref_str += "    {},\n".format(ref)
200     ref_str = ref_str[:-1] # trim trailing newline
201     return ref_str
202
203 def get_arbitrary_messages(arb):
204     template = """    {},
205 """
206     arb_str = ""
207     for item in arb:
208         arb_str += template.format(make_c_string(item[1]))
209     arb_str = arb_str[:-1] # trim trailing newline
210     return arb_str
211
212 def get_class_messages(cls):
213     template = """    {{
214         .threshold = {},
215         .message = {},
216     }},
217 """
218     cls_str = ""
219     for item in cls:
220         threshold = item["threshold"]
221         message = make_c_string(item["message"])
222         cls_str += template.format(threshold, message)
223     cls_str = cls_str[:-1] # trim trailing newline
224     return cls_str
225
226 def get_turn_thresholds(trn):
227     template = """    {{
228         .threshold = {},
229         .point_loss = {},
230         .message = {},
231     }},
232 """
233     trn_str = ""
234     for item in trn:
235         threshold = item["threshold"]
236         point_loss = item["point_loss"]
237         message = make_c_string(item["message"])
238         trn_str += template.format(threshold, point_loss, message)
239     trn_str = trn_str[:-1] # trim trailing newline
240     return trn_str
241
242 def get_locations(loc):
243     template = """    {{ // {}
244         .description = {{
245             .small = {},
246             .big = {},
247         }},
248         .sound = {},
249         .loud = {},
250     }},
251 """
252     loc_str = ""
253     for (i, item) in enumerate(loc):
254         short_d = make_c_string(item[1]["description"]["short"])
255         long_d = make_c_string(item[1]["description"]["long"])
256         sound = item[1].get("sound", "SILENT")
257         loud = "true" if item[1].get("loud") else "false"
258         loc_str += template.format(i, short_d, long_d, sound, loud)
259     loc_str = loc_str[:-1] # trim trailing newline
260     return loc_str
261
262 def get_object_descriptions(obj):
263     template = """    {{ // {}
264         .inventory = {},
265         .plac = {},
266         .fixd = {},
267         .is_treasure = {},
268         .longs = (const char* []) {{
269 {}
270         }},
271         .sounds = (const char* []) {{
272 {}
273         }},
274         .texts = (const char* []) {{
275 {}
276         }},
277     }},
278 """
279     obj_str = ""
280     for (i, item) in enumerate(obj):
281         attr = item[1]
282         i_msg = make_c_string(attr["inventory"])
283         longs_str = ""
284         if attr["longs"] == None:
285             longs_str = " " * 12 + "NULL,"
286         else:
287             labels = []
288             for l_msg in attr["longs"]:
289                 if not isinstance(l_msg, str):
290                     labels.append(l_msg)
291                     l_msg = l_msg[1]
292                 longs_str += " " * 12 + make_c_string(l_msg) + ",\n"
293             longs_str = longs_str[:-1] # trim trailing newline
294             if labels:
295                 global statedefines
296                 statedefines += "/* States for %s */\n" % item[0]
297                 for (i, (label, message)) in enumerate(labels):
298                     if len(message) >= 45:
299                         message = message[:45] + "..."
300                     statedefines += "#define %s\t%d /* %s */\n" % (label, i, message)
301                 statedefines += "\n"
302         sounds_str = ""
303         if attr.get("sounds") == None:
304             sounds_str = " " * 12 + "NULL,"
305         else:
306              for l_msg in attr["sounds"]:
307                  sounds_str += " " * 12 + make_c_string(l_msg) + ",\n"
308              sounds_str = sounds_str[:-1] # trim trailing newline
309         texts_str = ""
310         if attr.get("texts") == None:
311             texts_str = " " * 12 + "NULL,"
312         else:
313              for l_msg in attr["texts"]:
314                  texts_str += " " * 12 + make_c_string(l_msg) + ",\n"
315              texts_str = texts_str[:-1] # trim trailing newline
316         locs = attr.get("locations", ["LOC_NOWHERE", "LOC_NOWHERE"])
317         immovable = attr.get("immovable", False)
318         try:
319             if type(locs) == str:
320                 locs = [locnames.index(locs), -1 if immovable else 0]
321             else:
322                 locs = [locnames.index(x) for x in locs]
323         except IndexError:
324             sys.stderr.write("dungeon: unknown object location in %s\n" % locs)
325             sys.exit(1)
326         treasure = "true" if attr.get("treasure") else "false"
327         obj_str += template.format(i, i_msg, locs[0], locs[1], treasure, longs_str, sounds_str, texts_str)
328     obj_str = obj_str[:-1] # trim trailing newline
329     return obj_str
330
331 def get_obituaries(obit):
332     template = """    {{
333         .query = {},
334         .yes_response = {},
335     }},
336 """
337     obit_str = ""
338     for o in obit:
339         query = make_c_string(o["query"])
340         yes = make_c_string(o["yes_response"])
341         obit_str += template.format(query, yes)
342     obit_str = obit_str[:-1] # trim trailing newline
343     return obit_str
344
345 def get_hints(hnt, arb):
346     template = """    {{
347         .number = {},
348         .penalty = {},
349         .turns = {},
350         .question = {},
351         .hint = {},
352     }},
353 """
354     hnt_str = ""
355     md = dict(arb)
356     for member in hnt:
357         item = member["hint"]
358         number = item["number"]
359         penalty = item["penalty"]
360         turns = item["turns"]
361         question = make_c_string(item["question"])
362         hint = make_c_string(item["hint"])
363         hnt_str += template.format(number, penalty, turns, question, hint)
364     hnt_str = hnt_str[:-1] # trim trailing newline
365     return hnt_str
366
367 def get_condbits(locations):
368     cnd_str = ""
369     for (name, loc) in locations:
370         conditions = loc["conditions"]
371         hints = loc.get("hints") or []
372         flaglist = []
373         for flag in conditions:
374             if conditions[flag]:
375                 flaglist.append(flag)
376         line = "|".join([("(1<<COND_%s)" % f) for f in flaglist])
377         trail = "|".join([("(1<<COND_H%s)" % f['name']) for f in hints])
378         if trail:
379             line += "|" + trail
380         if line.startswith("|"):
381             line = line[1:]
382         if not line:
383             line = "0"
384         cnd_str += "    " + line + ",\t// " + name + "\n"
385     return cnd_str
386
387 def recompose(type_word, value):
388     "Compose the internal code for a vocabulary word from its YAML entry"
389     parts = ("motion", "action", "object", "special")
390     try:
391         return value + 1000 * parts.index(type_word)
392     except KeyError:
393         sys.stderr.write("dungeon: %s is not a known word\n" % word)
394         sys.exit(1)
395     except IndexError:
396         sys.stderr.write("%s is not a known word classifier" % attrs["type"])
397         sys.exit(1)
398
399 def get_vocabulary(vocabulary):
400     template = """    {{
401         .word = {},
402         .type = {},
403         .value = {},
404     }},
405 """
406     voc_str = ""
407     for vocab in vocabulary:
408         word = make_c_string(vocab["word"])
409         type_code = recompose(vocab["type"], vocab["value"])
410         value = vocab["value"]
411         voc_str += template.format(word, type_code, value)
412     voc_str = voc_str[:-1] # trim trailing newline
413     return voc_str
414
415 def get_actspk(actspk):
416     res = ""
417     for (i, word) in actspk.items():
418         res += "    %s,\n" % word
419     return res
420
421 if __name__ == "__main__":
422     with open(yaml_name, "r") as f:
423         db = yaml.load(f)
424
425     locnames = [x[0] for x in db["locations"]]
426
427     c = c_template.format(
428         h_name,
429         get_arbitrary_messages(db["arbitrary_messages"]),
430         get_class_messages(db["classes"]),
431         get_turn_thresholds(db["turn_thresholds"]),
432         get_locations(db["locations"]),
433         get_object_descriptions(db["object_descriptions"]),
434         get_obituaries(db["obituaries"]),
435         get_hints(db["hints"], db["arbitrary_messages"]),
436         get_condbits(db["locations"]),
437         get_vocabulary(db["vocabulary"]),
438         get_actspk(db["actspk"]),
439     )
440
441     h = h_template.format(
442         len(db["locations"])-1,
443         len(db["object_descriptions"])-1,
444         len(db["hints"]),
445         len(db["classes"]),
446         len(db["obituaries"]),
447         len(db["turn_thresholds"]),
448         len(db["actspk"]),
449         len(db["vocabulary"]),
450         get_refs(db["arbitrary_messages"]),
451         get_refs(db["locations"]),
452         get_refs(db["object_descriptions"]),
453         statedefines,
454     )
455
456     with open(h_name, "w") as hf:
457         hf.write(h)
458
459     with open(c_name, "w") as cf:
460         cf.write(c)
461
462 # end