Improve INSTALL.adoc's directions and asciidoc-ness.
[open-adventure.git] / make_dungeon.py
1 #!/usr/bin/env python
2
3 # This is the open-adventure dungeon generator. It consumes a YAML description of
4 # the dungeon and outputs a dungeon.h and dungeon.c pair of C code files.
5 #
6 # The nontrivial part of this is the compilation of the YAML for
7 # movement rules to the travel array that's actually used by
8 # playermove().
9 #
10 # Copyright (c) 2017 by Eric S. Raymond
11 # SPDX-License-Identifier: BSD-2-clause
12
13 import sys, yaml
14
15 YAML_NAME = "adventure.yaml"
16 H_NAME = "dungeon.h"
17 C_NAME = "dungeon.c"
18 H_TEMPLATE_PATH = "templates/dungeon.h.tpl"
19 C_TEMPLATE_PATH = "templates/dungeon.c.tpl"
20
21 DONOTEDIT_COMMENT = "/* Generated from adventure.yaml - do not hand-hack! */\n\n"
22
23 statedefines = ""
24
25 def make_c_string(string):
26     """Render a Python string into C string literal format."""
27     if string == None:
28         return "NULL"
29     string = string.replace("\n", "\\n")
30     string = string.replace("\t", "\\t")
31     string = string.replace('"', '\\"')
32     string = string.replace("'", "\\'")
33     string = '"' + string + '"'
34     return string
35
36 def get_refs(l):
37     reflist = [x[0] for x in l]
38     ref_str = ""
39     for ref in reflist:
40         ref_str += "    {},\n".format(ref)
41     ref_str = ref_str[:-1] # trim trailing newline
42     return ref_str
43
44 def get_string_group(strings):
45     template = """{{
46             .strs = {},
47             .n = {},
48         }}"""
49     if strings == []:
50         strs = "NULL"
51     else:
52         strs = "(const char* []) {" + ", ".join([make_c_string(s) for s in strings]) + "}"
53     n = len(strings)
54     sg_str = template.format(strs, n)
55     return sg_str
56
57 def get_arbitrary_messages(arb):
58     template = """    {},
59 """
60     arb_str = ""
61     for item in arb:
62         arb_str += template.format(make_c_string(item[1]))
63     arb_str = arb_str[:-1] # trim trailing newline
64     return arb_str
65
66 def get_class_messages(cls):
67     template = """    {{
68         .threshold = {},
69         .message = {},
70     }},
71 """
72     cls_str = ""
73     for item in cls:
74         threshold = item["threshold"]
75         message = make_c_string(item["message"])
76         cls_str += template.format(threshold, message)
77     cls_str = cls_str[:-1] # trim trailing newline
78     return cls_str
79
80 def get_turn_thresholds(trn):
81     template = """    {{
82         .threshold = {},
83         .point_loss = {},
84         .message = {},
85     }},
86 """
87     trn_str = ""
88     for item in trn:
89         threshold = item["threshold"]
90         point_loss = item["point_loss"]
91         message = make_c_string(item["message"])
92         trn_str += template.format(threshold, point_loss, message)
93     trn_str = trn_str[:-1] # trim trailing newline
94     return trn_str
95
96 def get_locations(loc):
97     template = """    {{ // {}: {}
98         .description = {{
99             .small = {},
100             .big = {},
101         }},
102         .sound = {},
103         .loud = {},
104     }},
105 """
106     loc_str = ""
107     for (i, item) in enumerate(loc):
108         short_d = make_c_string(item[1]["description"]["short"])
109         long_d = make_c_string(item[1]["description"]["long"])
110         sound = item[1].get("sound", "SILENT")
111         loud = "true" if item[1].get("loud") else "false"
112         loc_str += template.format(i, item[0], short_d, long_d, sound, loud)
113     loc_str = loc_str[:-1] # trim trailing newline
114     return loc_str
115
116 def get_objects(obj):
117     template = """    {{ // {}: {}
118         .words = {},
119         .inventory = {},
120         .plac = {},
121         .fixd = {},
122         .is_treasure = {},
123         .descriptions = (const char* []) {{
124 {}
125         }},
126         .sounds = (const char* []) {{
127 {}
128         }},
129         .texts = (const char* []) {{
130 {}
131         }},
132         .changes = (const char* []) {{
133 {}
134         }},
135     }},
136 """
137     obj_str = ""
138     for (i, item) in enumerate(obj):
139         attr = item[1]
140         try:
141             words_str = get_string_group(attr["words"])
142         except KeyError:
143             words_str = get_string_group([])
144         i_msg = make_c_string(attr["inventory"])
145         descriptions_str = ""
146         if attr["descriptions"] == None:
147             descriptions_str = " " * 12 + "NULL,"
148         else:
149             labels = []
150             for l_msg in attr["descriptions"]:
151                 descriptions_str += " " * 12 + make_c_string(l_msg) + ",\n"
152             for label in attr.get("states", []):
153                 labels.append(label)
154             descriptions_str = descriptions_str[:-1] # trim trailing newline
155             if labels:
156                 global statedefines
157                 statedefines += "/* States for %s */\n" % item[0]
158                 for (n, label) in enumerate(labels):
159                     statedefines += "#define %s\t%d\n" % (label, n)
160                 statedefines += "\n"
161         sounds_str = ""
162         if attr.get("sounds") == None:
163             sounds_str = " " * 12 + "NULL,"
164         else:
165              for l_msg in attr["sounds"]:
166                  sounds_str += " " * 12 + make_c_string(l_msg) + ",\n"
167              sounds_str = sounds_str[:-1] # trim trailing newline
168         texts_str = ""
169         if attr.get("texts") == None:
170             texts_str = " " * 12 + "NULL,"
171         else:
172              for l_msg in attr["texts"]:
173                  texts_str += " " * 12 + make_c_string(l_msg) + ",\n"
174              texts_str = texts_str[:-1] # trim trailing newline
175         changes_str = ""
176         if attr.get("changes") == None:
177             changes_str = " " * 12 + "NULL,"
178         else:
179              for l_msg in attr["changes"]:
180                  changes_str += " " * 12 + make_c_string(l_msg) + ",\n"
181              changes_str = changes_str[:-1] # trim trailing newline
182         locs = attr.get("locations", ["LOC_NOWHERE", "LOC_NOWHERE"])
183         immovable = attr.get("immovable", False)
184         try:
185             if type(locs) == str:
186                 locs = [locs, -1 if immovable else 0]
187         except IndexError:
188             sys.stderr.write("dungeon: unknown object location in %s\n" % locs)
189             sys.exit(1)
190         treasure = "true" if attr.get("treasure") else "false"
191         obj_str += template.format(i, item[0], words_str, i_msg, locs[0], locs[1], treasure, descriptions_str, sounds_str, texts_str, changes_str)
192     obj_str = obj_str[:-1] # trim trailing newline
193     return obj_str
194
195 def get_obituaries(obit):
196     template = """    {{
197         .query = {},
198         .yes_response = {},
199     }},
200 """
201     obit_str = ""
202     for o in obit:
203         query = make_c_string(o["query"])
204         yes = make_c_string(o["yes_response"])
205         obit_str += template.format(query, yes)
206     obit_str = obit_str[:-1] # trim trailing newline
207     return obit_str
208
209 def get_hints(hnt):
210     template = """    {{
211         .number = {},
212         .penalty = {},
213         .turns = {},
214         .question = {},
215         .hint = {},
216     }},
217 """
218     hnt_str = ""
219     for member in hnt:
220         item = member["hint"]
221         number = item["number"]
222         penalty = item["penalty"]
223         turns = item["turns"]
224         question = make_c_string(item["question"])
225         hint = make_c_string(item["hint"])
226         hnt_str += template.format(number, penalty, turns, question, hint)
227     hnt_str = hnt_str[:-1] # trim trailing newline
228     return hnt_str
229
230 def get_condbits(locations):
231     cnd_str = ""
232     for (name, loc) in locations:
233         conditions = loc["conditions"]
234         hints = loc.get("hints") or []
235         flaglist = []
236         for flag in conditions:
237             if conditions[flag]:
238                 flaglist.append(flag)
239         line = "|".join([("(1<<COND_%s)" % f) for f in flaglist])
240         trail = "|".join([("(1<<COND_H%s)" % f['name']) for f in hints])
241         if trail:
242             line += "|" + trail
243         if line.startswith("|"):
244             line = line[1:]
245         if not line:
246             line = "0"
247         cnd_str += "    " + line + ",\t// " + name + "\n"
248     return cnd_str
249
250 def get_motions(motions):
251     template = """    {{
252         .words = {},
253     }},
254 """
255     mot_str = ""
256     for motion in motions:
257         contents = motion[1]
258         if contents["words"] == None:
259             words_str = get_string_group([])
260         else:
261             words_str = get_string_group(contents["words"])
262         mot_str += template.format(words_str)
263         global ignore
264         if contents.get("oldstyle", True) == False:
265             for word in contents["words"]:
266                 if len(word) == 1:
267                     ignore += word.upper()
268     return mot_str
269
270 def get_actions(actions):
271     template = """    {{
272         .words = {},
273         .message = {},
274         .noaction = {},
275     }},
276 """
277     act_str = ""
278     for action in actions:
279         contents = action[1]
280
281         if contents["words"] == None:
282             words_str = get_string_group([])
283         else:
284             words_str = get_string_group(contents["words"])
285
286         if contents["message"] == None:
287             message = "NULL"
288         else:
289             message = make_c_string(contents["message"])
290
291         if contents.get("noaction") == None:
292             noaction = "false"
293         else:
294             noaction = "true"
295
296         act_str += template.format(words_str, message, noaction)
297         global ignore
298         if contents.get("oldstyle", True) == False:
299             for word in contents["words"]:
300                 if len(word) == 1:
301                     ignore += word.upper()
302     act_str = act_str[:-1] # trim trailing newline
303     return act_str
304
305 def bigdump(arr):
306     out = ""
307     for (i, entry) in enumerate(arr):
308         if i % 10 == 0:
309             if out and out[-1] == ' ':
310                 out = out[:-1]
311             out += "\n    "
312         out += str(arr[i]).lower() + ", "
313     out = out[:-2] + "\n"
314     return out
315
316 def buildtravel(locs, objs):
317     assert len(locs) <= 300
318     assert len(objs) <= 100
319     # THIS CODE IS WAAAY MORE COMPLEX THAN IT NEEDS TO BE.  It's the
320     # result of a massive refactoring exercise that concentrated all
321     # the old nastiness in one spot. It hasn't been finally simplified
322     # because there's no need to do it until one of the assertions
323     # fails. Hint: if you try cleaning this up, the acceptance test is
324     # simple - the output dungeon.c must not change.
325     #
326     # This function first compiles the YAML to a form identical to the
327     # data in section 3 of the old adventure.text file, then a second
328     # stage unpacks that data into the travel array.  Here are the
329     # rules of that intermediate form:
330     #
331     # Each row of data contains a location number (X), a second
332     # location number (Y), and a list of motion numbers (see section 4).
333     # each motion represents a verb which will go to Y if currently at X.
334     # Y, in turn, is interpreted as follows.  Let M=Y/1000, N=Y mod 1000.
335     #           If N<=300       it is the location to go to.
336     #           If 300<N<=500   N-300 is used in a computed goto to
337     #                                   a section of special code.
338     #           If N>500        message N-500 from section 6 is printed,
339     #                                   and he stays wherever he is.
340     # Meanwhile, M specifies the conditions on the motion.
341     #           If M=0          it's unconditional.
342     #           If 0<M<100      it is done with M% probability.
343     #           If M=100        unconditional, but forbidden to dwarves.
344     #           If 100<M<=200   he must be carrying object M-100.
345     #           If 200<M<=300   must be carrying or in same room as M-200.
346     #           If 300<M<=400   game.prop(M % 100) must *not* be 0.
347     #           If 400<M<=500   game.prop(M % 100) must *not* be 1.
348     #           If 500<M<=600   game.prop(M % 100) must *not* be 2, etc.
349     # If the condition (if any) is not met, then the next *different*
350     # "destination" value is used (unless it fails to meet *its* conditions,
351     # in which case the next is found, etc.).  Typically, the next dest will
352     # be for one of the same verbs, so that its only use is as the alternate
353     # destination for those verbs.  For instance:
354     #           15      110022  29      31      34      35      23      43
355     #           15      14      29
356     # This says that, from loc 15, any of the verbs 29, 31, etc., will take
357     # him to 22 if he's carrying object 10, and otherwise will go to 14.
358     #           11      303008  49
359     #           11      9       50
360     # This says that, from 11, 49 takes him to 8 unless game.prop[3]=0, in which
361     # case he goes to 9.  Verb 50 takes him to 9 regardless of game.prop[3].
362     ltravel = []
363     verbmap = {}
364     for i, motion in enumerate(db["motions"]):
365         try:
366             for word in motion[1]["words"]:
367                 verbmap[word.upper()] = i
368         except TypeError:
369             pass
370     def dencode(action, name):
371         "Decode a destination number"
372         if action[0] == "goto":
373             try:
374                 return locnames.index(action[1])
375             except ValueError:
376                 sys.stderr.write("dungeon: unknown location %s in goto clause of %s\n" % (action[1], name))
377         elif action[0] == "special":
378             return 300 + action[1]
379         elif action[0] == "speak":
380             try:
381                 return 500 + msgnames.index(action[1])
382             except ValueError:
383                 sys.stderr.write("dungeon: unknown location %s in carry clause of %s\n" % (cond[1], name))
384         else:
385             print(cond)
386             raise ValueError
387     def cencode(cond, name):
388         if cond is None:
389             return 0
390         elif cond == ["nodwarves"]:
391             return 100
392         elif cond[0] == "pct":
393             return cond[1]
394         elif cond[0] == "carry":
395             try:
396                 return 100 + objnames.index(cond[1])
397             except ValueError:
398                 sys.stderr.write("dungeon: unknown object name %s in carry clause of %s\n" % (cond[1], name))
399                 sys.exit(1)
400         elif cond[0] == "with":
401             try:
402                 return 200 + objnames.index(cond[1])
403             except IndexError:
404                 sys.stderr.write("dungeon: unknown object name %s in with clause of \n" % (cond[1], name))
405                 sys.exit(1)
406         elif cond[0] == "not":
407             try:
408                 obj = objnames.index(cond[1])
409                 if type(cond[2]) == int:
410                     state = cond[2]
411                 elif cond[2] in objs[obj][1].get("states", []):
412                     state = objs[obj][1].get("states").index(cond[2])
413                 else:
414                     for (i, stateclause) in enumerate(objs[obj][1]["descriptions"]):
415                         if type(stateclause) == list:
416                             if stateclause[0] == cond[2]:
417                                 state = i
418                                 break
419                     else:
420                         sys.stderr.write("dungeon: unmatched state symbol %s in not clause of %s\n" % (cond[2], name))
421                         sys.exit(0);
422                 return 300 + obj + 100 * state
423             except ValueError:
424                 sys.stderr.write("dungeon: unknown object name %s in not clause of %s\n" % (cond[1], name))
425                 sys.exit(1)
426         else:
427             print(cond)
428             raise ValueError
429
430     for (i, (name, loc)) in enumerate(locs):
431         if "travel" in loc:
432             for rule in loc["travel"]:
433                 tt = [i]
434                 dest = dencode(rule["action"], name) + 1000 * cencode(rule.get("cond"), name)
435                 tt.append(dest)
436                 tt += [motionnames[verbmap[e]].upper() for e in rule["verbs"]]
437                 if not rule["verbs"]:
438                     tt.append(1)        # Magic dummy entry for null rules
439                 ltravel.append(tuple(tt))
440
441     # At this point the ltravel data is in the Section 3
442     # representation from the FORTRAN version.  Next we perform the
443     # same mapping into what used to be the runtime format.
444
445     travel = [[0, "LOC_NOWHERE", 0, 0, 0, 0, 0, 0, "false", "false"]]
446     tkey = [0]
447     oldloc = 0
448     while ltravel:
449         rule = list(ltravel.pop(0))
450         loc = rule.pop(0)
451         newloc = rule.pop(0)
452         if loc != oldloc:
453             tkey.append(len(travel))
454             oldloc = loc 
455         elif travel:
456             travel[-1][-1] = "false" if travel[-1][-1] == "true" else "true" 
457         while rule:
458             cond = newloc // 1000
459             nodwarves = (cond == 100)
460             if cond == 0:
461                 condtype = "cond_goto"
462                 condarg1 = condarg2 = 0
463             elif cond < 100:
464                 condtype = "cond_pct"
465                 condarg1 = cond
466                 condarg2 = 0
467             elif cond == 100:
468                 condtype = "cond_goto"
469                 condarg1 = 100
470                 condarg2 = 0
471             elif cond <= 200:
472                 condtype = "cond_carry"
473                 condarg1 = objnames[cond - 100]
474                 condarg2 = 0
475             elif cond <= 300:
476                 condtype = "cond_with"
477                 condarg1 = objnames[cond - 200]
478                 condarg2 = 0
479             else:
480                 condtype = "cond_not"
481                 condarg1 = cond % 100
482                 condarg2 = (cond - 300) // 100.
483             dest = newloc % 1000
484             if dest <= 300:
485                 desttype = "dest_goto";
486                 destval = locnames[dest]
487             elif dest > 500:
488                 desttype = "dest_speak";
489                 destval = msgnames[dest - 500]
490             else:
491                 desttype = "dest_special";
492                 destval = locnames[dest - 300]
493             travel.append([len(tkey)-1,
494                            locnames[len(tkey)-1],
495                            rule.pop(0),
496                            condtype,
497                            condarg1,
498                            condarg2,
499                            desttype,
500                            destval,
501                            "true" if nodwarves else "false",
502                            "false"])
503         travel[-1][-1] = "true"
504     return (travel, tkey)
505
506 def get_travel(travel):
507     template = """    {{ // from {}: {}
508         .motion = {},
509         .condtype = {},
510         .condarg1 = {},
511         .condarg2 = {},
512         .desttype = {},
513         .destval = {},
514         .nodwarves = {},
515         .stop = {},
516     }},
517 """
518     out = ""
519     for entry in travel:
520         out += template.format(*entry)
521     out = out[:-1] # trim trailing newline
522     return out
523
524 if __name__ == "__main__":
525     with open(YAML_NAME, "r") as f:
526         db = yaml.load(f)
527
528     locnames = [x[0] for x in db["locations"]]
529     msgnames = [el[0] for el in db["arbitrary_messages"]]
530     objnames = [el[0] for el in db["objects"]]
531     motionnames = [el[0] for el in db["motions"]]
532
533     (travel, tkey) = buildtravel(db["locations"],
534                                  db["objects"])
535     ignore = ""
536     try:
537         with open(H_TEMPLATE_PATH, "r") as htf:
538             # read in dungeon.h template
539             h_template = DONOTEDIT_COMMENT + htf.read()
540         with open(C_TEMPLATE_PATH, "r") as ctf:
541             # read in dungeon.c template
542             c_template = DONOTEDIT_COMMENT + ctf.read()
543     except IOError as e:
544         print('ERROR: reading template failed ({})'.format(e.strerror))
545         exit(-1)
546
547     c = c_template.format(
548         h_file             = H_NAME,
549         arbitrary_messages = get_arbitrary_messages(db["arbitrary_messages"]),
550         classes            = get_class_messages(db["classes"]),
551         turn_thresholds    = get_turn_thresholds(db["turn_thresholds"]),
552         locations          = get_locations(db["locations"]),
553         objects            = get_objects(db["objects"]),
554         obituaries         = get_obituaries(db["obituaries"]),
555         hints              = get_hints(db["hints"]),
556         conditions         = get_condbits(db["locations"]),
557         motions            = get_motions(db["motions"]),
558         actions            = get_actions(db["actions"]),
559         tkeys              = bigdump(tkey),
560         travel             = get_travel(travel), 
561         ignore             = ignore
562     )
563
564     # 0-origin index of birds's last song.  Bird should
565     # die after player hears this.
566     deathbird = len(dict(db["objects"])["BIRD"]["sounds"]) - 1
567
568     h = h_template.format(
569         num_locations      = len(db["locations"])-1,
570         num_objects        = len(db["objects"])-1,
571         num_hints          = len(db["hints"]),
572         num_classes        = len(db["classes"])-1,
573         num_deaths         = len(db["obituaries"]),
574         num_thresholds     = len(db["turn_thresholds"]),
575         num_motions        = len(db["motions"]),
576         num_actions        = len(db["actions"]),
577         num_travel         = len(travel),
578         num_keys           = len(tkey),
579         bird_endstate      = deathbird,
580         arbitrary_messages = get_refs(db["arbitrary_messages"]),
581         locations          = get_refs(db["locations"]),
582         objects            = get_refs(db["objects"]),
583         motions            = get_refs(db["motions"]),
584         actions            = get_refs(db["actions"]),
585         state_definitions  = statedefines
586     )
587
588     with open(H_NAME, "w") as hf:
589         hf.write(h)
590
591     with open(C_NAME, "w") as cf:
592         cf.write(c)
593
594 # end