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