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