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