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.
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
10 # Copyright (c) 2017 by Eric S. Raymond
11 # SPDX-License-Identifier: BSD-2-clause
15 YAML_NAME = "adventure.yaml"
18 H_TEMPLATE_PATH = "templates/dungeon.h.tpl"
19 C_TEMPLATE_PATH = "templates/dungeon.c.tpl"
21 DONOTEDIT_COMMENT = "/* Generated from adventure.yaml - do not hand-hack! */\n\n"
25 def make_c_string(string):
26 """Render a Python string into C string literal format."""
29 string = string.replace("\n", "\\n")
30 string = string.replace("\t", "\\t")
31 string = string.replace('"', '\\"')
32 string = string.replace("'", "\\'")
33 string = '"' + string + '"'
37 reflist = [x[0] for x in l]
40 ref_str += " {},\n".format(ref)
41 ref_str = ref_str[:-1] # trim trailing newline
44 def get_string_group(strings):
52 strs = "(const char* []) {" + ", ".join([make_c_string(s) for s in strings]) + "}"
54 sg_str = template.format(strs, n)
57 def get_arbitrary_messages(arb):
62 arb_str += template.format(make_c_string(item[1]))
63 arb_str = arb_str[:-1] # trim trailing newline
66 def get_class_messages(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
80 def get_turn_thresholds(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
96 def get_locations(loc):
97 template = """ {{ // {}: {}
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
116 def get_objects(obj):
117 template = """ {{ // {}: {}
123 .descriptions = (const char* []) {{
126 .sounds = (const char* []) {{
129 .texts = (const char* []) {{
132 .changes = (const char* []) {{
138 for (i, item) in enumerate(obj):
141 words_str = get_string_group(attr["words"])
143 words_str = get_string_group([])
144 i_msg = make_c_string(attr["inventory"])
145 descriptions_str = ""
146 if attr["descriptions"] == None:
147 descriptions_str = " " * 12 + "NULL,"
150 for l_msg in attr["descriptions"]:
151 descriptions_str += " " * 12 + make_c_string(l_msg) + ",\n"
152 for label in attr.get("states", []):
154 descriptions_str = descriptions_str[:-1] # trim trailing newline
157 statedefines += "/* States for %s */\n" % item[0]
158 for (n, label) in enumerate(labels):
159 statedefines += "#define %s\t%d\n" % (label, n)
162 if attr.get("sounds") == None:
163 sounds_str = " " * 12 + "NULL,"
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
169 if attr.get("texts") == None:
170 texts_str = " " * 12 + "NULL,"
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
176 if attr.get("changes") == None:
177 changes_str = " " * 12 + "NULL,"
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)
185 if type(locs) == str:
186 locs = [locs, -1 if immovable else 0]
188 sys.stderr.write("dungeon: unknown object location in %s\n" % locs)
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
195 def get_obituaries(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
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
230 def get_condbits(locations):
232 for (name, loc) in locations:
233 conditions = loc["conditions"]
234 hints = loc.get("hints") or []
236 for flag in conditions:
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])
243 if line.startswith("|"):
247 cnd_str += " " + line + ",\t// " + name + "\n"
250 def get_motions(motions):
256 for motion in motions:
258 if contents["words"] == None:
259 words_str = get_string_group([])
261 words_str = get_string_group(contents["words"])
262 mot_str += template.format(words_str)
264 if contents.get("oldstyle", True) == False:
265 for word in contents["words"]:
267 ignore += word.upper()
270 def get_actions(actions):
278 for action in actions:
281 if contents["words"] == None:
282 words_str = get_string_group([])
284 words_str = get_string_group(contents["words"])
286 if contents["message"] == None:
289 message = make_c_string(contents["message"])
291 if contents.get("noaction") == None:
296 act_str += template.format(words_str, message, noaction)
298 if contents.get("oldstyle", True) == False:
299 for word in contents["words"]:
301 ignore += word.upper()
302 act_str = act_str[:-1] # trim trailing newline
307 for (i, entry) in enumerate(arr):
309 if out and out[-1] == ' ':
312 out += str(arr[i]).lower() + ", "
313 out = out[:-2] + "\n"
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.
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:
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
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.
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].
364 for i, motion in enumerate(db["motions"]):
366 for word in motion[1]["words"]:
367 verbmap[word.upper()] = i
370 def dencode(action, name):
371 "Decode a destination number"
372 if action[0] == "goto":
374 return locnames.index(action[1])
376 sys.stderr.write("dungeon: unknown location %s in goto clause of %s\n" % (action[1], name))
377 elif action[0] == "special":
378 return 300 + action[1]
379 elif action[0] == "speak":
381 return 500 + msgnames.index(action[1])
383 sys.stderr.write("dungeon: unknown location %s in carry clause of %s\n" % (cond[1], name))
387 def cencode(cond, name):
390 elif cond == ["nodwarves"]:
392 elif cond[0] == "pct":
394 elif cond[0] == "carry":
396 return 100 + objnames.index(cond[1])
398 sys.stderr.write("dungeon: unknown object name %s in carry clause of %s\n" % (cond[1], name))
400 elif cond[0] == "with":
402 return 200 + objnames.index(cond[1])
404 sys.stderr.write("dungeon: unknown object name %s in with clause of \n" % (cond[1], name))
406 elif cond[0] == "not":
408 obj = objnames.index(cond[1])
409 if type(cond[2]) == int:
411 elif cond[2] in objs[obj][1].get("states", []):
412 state = objs[obj][1].get("states").index(cond[2])
414 for (i, stateclause) in enumerate(objs[obj][1]["descriptions"]):
415 if type(stateclause) == list:
416 if stateclause[0] == cond[2]:
420 sys.stderr.write("dungeon: unmatched state symbol %s in not clause of %s\n" % (cond[2], name))
422 return 300 + obj + 100 * state
424 sys.stderr.write("dungeon: unknown object name %s in not clause of %s\n" % (cond[1], name))
430 for (i, (name, loc)) in enumerate(locs):
432 for rule in loc["travel"]:
434 dest = dencode(rule["action"], name) + 1000 * cencode(rule.get("cond"), name)
436 tt += [motionnames[verbmap[e]].upper() for e in rule["verbs"]]
437 if not rule["verbs"]:
438 tt.append(1) # Magic dummy entry for null rules
439 ltravel.append(tuple(tt))
441 # At this point the ltravel data is in the Section 3
442 # representation from the FORTRAN version. Next we perform the
443 # same mapping into wgat used to be the runtime format.
445 travel = [[0, "LOC_NOWHERE", 0, 0, 0, 0, 0, 0, "false", "false"]]
449 rule = list(ltravel.pop(0))
453 tkey.append(len(travel))
456 travel[-1][-1] = "false" if travel[-1][-1] == "true" else "true"
458 cond = newloc // 1000
459 nodwarves = (cond == 100)
461 condtype = "cond_goto"
462 condarg1 = condarg2 = 0
464 condtype = "cond_pct"
468 condtype = "cond_goto"
472 condtype = "cond_carry"
473 condarg1 = objnames[cond - 100]
476 condtype = "cond_with"
477 condarg1 = objnames[cond - 200]
480 condtype = "cond_not"
481 condarg1 = cond % 100
482 condarg2 = (cond - 300) // 100.
485 desttype = "dest_goto";
486 destval = locnames[dest]
488 desttype = "dest_speak";
489 destval = msgnames[dest - 500]
491 desttype = "dest_special";
492 destval = locnames[dest - 300]
493 travel.append([len(tkey)-1,
494 locnames[len(tkey)-1],
501 "true" if nodwarves else "false",
503 travel[-1][-1] = "true"
504 return (travel, tkey)
506 def get_travel(travel):
507 template = """ {{ // from {}: {}
520 out += template.format(*entry)
521 out = out[:-1] # trim trailing newline
524 if __name__ == "__main__":
525 with open(YAML_NAME, "r") as f:
528 locnames = [x[0] for x in db["locations"]]
529 msgnames = [el[0] for el in db["arbitrary_messages"]]
530 objnames = [el[0] for el in db["objects"]]
531 motionnames = [el[0] for el in db["motions"]]
533 (travel, tkey) = buildtravel(db["locations"],
537 with open(H_TEMPLATE_PATH, "r") as htf:
538 # read in dungeon.h template
539 h_template = DONOTEDIT_COMMENT + htf.read()
540 with open(C_TEMPLATE_PATH, "r") as ctf:
541 # read in dungeon.c template
542 c_template = DONOTEDIT_COMMENT + ctf.read()
544 print('ERROR: reading template failed ({})'.format(e.strerror))
547 c = c_template.format(
549 arbitrary_messages = get_arbitrary_messages(db["arbitrary_messages"]),
550 classes = get_class_messages(db["classes"]),
551 turn_thresholds = get_turn_thresholds(db["turn_thresholds"]),
552 locations = get_locations(db["locations"]),
553 objects = get_objects(db["objects"]),
554 obituaries = get_obituaries(db["obituaries"]),
555 hints = get_hints(db["hints"]),
556 conditions = get_condbits(db["locations"]),
557 motions = get_motions(db["motions"]),
558 actions = get_actions(db["actions"]),
559 tkeys = bigdump(tkey),
560 travel = get_travel(travel),
564 # 0-origin index of birds's last song. Bird should
565 # die after player hears this.
566 deathbird = len(dict(db["objects"])["BIRD"]["sounds"]) - 1
568 h = h_template.format(
569 num_locations = len(db["locations"])-1,
570 num_objects = len(db["objects"])-1,
571 num_hints = len(db["hints"]),
572 num_classes = len(db["classes"])-1,
573 num_deaths = len(db["obituaries"]),
574 num_thresholds = len(db["turn_thresholds"]),
575 num_motions = len(db["motions"]),
576 num_actions = len(db["actions"]),
577 num_travel = len(travel),
578 num_keys = len(tkey),
579 bird_endstate = deathbird,
580 arbitrary_messages = get_refs(db["arbitrary_messages"]),
581 locations = get_refs(db["locations"]),
582 objects = get_refs(db["objects"]),
583 motions = get_refs(db["motions"]),
584 actions = get_refs(db["actions"]),
585 state_definitions = statedefines
588 with open(H_NAME, "w") as hf:
591 with open(C_NAME, "w") as cf: