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