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