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