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
12 yaml_name = "adventure.yaml"
18 h_template = """/* Generated from adventure.yaml - do not hand-hack! */
25 #define SILENT -1 /* no sound */
27 /* Symbols for cond bits */
28 #define COND_LIT 0 /* Light */
29 #define COND_OILY 1 /* If bit 2 is on: on for oil, off for water */
30 #define COND_FLUID 2 /* Liquid asset, see bit 1 */
31 #define COND_NOARRR 3 /* Pirate doesn't go here unless following */
32 #define COND_NOBACK 4 /* Cannot use "back" to move away */
34 #define COND_DEEP 6 /* Deep - e.g where dwarves are active */
35 #define COND_FOREST 7 /* In the forest */
36 #define COND_FORCED 8 /* Only one way in or out of here */
37 /* Bits past 10 indicate areas of interest to "hint" routines */
38 #define COND_HBASE 10 /* Base for location hint bits */
39 #define COND_HCAVE 11 /* Trying to get into cave */
40 #define COND_HBIRD 12 /* Trying to catch bird */
41 #define COND_HSNAKE 13 /* Trying to deal with snake */
42 #define COND_HMAZE 14 /* Lost in maze */
43 #define COND_HDARK 15 /* Pondering dark room */
44 #define COND_HWITT 16 /* At Witt's End */
45 #define COND_HCLIFF 17 /* Cliff with urn */
46 #define COND_HWOODS 18 /* Lost in forest */
47 #define COND_HOGRE 19 /* Trying to deal with ogre */
48 #define COND_HJADE 20 /* Found all treasures except jade */
56 const string_group_t words;
57 const char* inventory;
60 const char** descriptions;
72 descriptions_t description;
79 const char* yes_response;
102 const string_group_t words;
106 const string_group_t words;
111 const string_group_t words;
115 enum condtype_t {{cond_goto, cond_pct, cond_carry, cond_with, cond_not}};
116 enum desttype_t {{dest_goto, dest_special, dest_speak}};
123 const enum desttype_t desttype;
125 const bool nodwarves;
129 /* Abstract out the encoding of words in the travel array. Gives us
130 * some hope of getting to a less cryptic representation than we
131 * inherited from FORTRAN, someday. To understand these, read the
132 * encoding description for travel.
134 #define T_TERMINATE(entry) ((entry).motion == 1)
136 extern const location_t locations[];
137 extern const object_t objects[];
138 extern const char* arbitrary_messages[];
139 extern const class_t classes[];
140 extern const turn_threshold_t turn_thresholds[];
141 extern const obituary_t obituaries[];
142 extern const hint_t hints[];
143 extern long conditions[];
144 extern const motion_t motions[];
145 extern const action_t actions[];
146 extern const special_t specials[];
147 extern const travelop_t travel[];
148 extern const long tkey[];
149 extern const char *ignore;
151 #define NLOCATIONS {}
156 #define NTHRESHOLDS {}
163 #define BIRD_ENDSTATE {}
165 enum arbitrary_messages_refs {{
169 enum locations_refs {{
189 /* State definitions */
192 #endif /* end DUNGEON_H */
195 c_template = """/* Generated from adventure.yaml - do not hand-hack! */
199 const char* arbitrary_messages[] = {{
203 const class_t classes[] = {{
207 const turn_threshold_t turn_thresholds[] = {{
211 const location_t locations[] = {{
215 const object_t objects[] = {{
219 const obituary_t obituaries[] = {{
223 const hint_t hints[] = {{
227 long conditions[] = {{
231 const motion_t motions[] = {{
235 const action_t actions[] = {{
239 const special_t specials[] = {{
243 const long tkey[] = {{{}}};
245 const travelop_t travel[] = {{
249 const char *ignore = \"{}\";
254 def make_c_string(string):
255 """Render a Python string into C string literal format."""
258 string = string.replace("\n", "\\n")
259 string = string.replace("\t", "\\t")
260 string = string.replace('"', '\\"')
261 string = string.replace("'", "\\'")
262 string = '"' + string + '"'
266 reflist = [x[0] for x in l]
269 ref_str += " {},\n".format(ref)
270 ref_str = ref_str[:-1] # trim trailing newline
273 def get_string_group(strings):
281 strs = "(const char* []) {" + ", ".join([make_c_string(s) for s in strings]) + "}"
283 sg_str = template.format(strs, n)
286 def get_arbitrary_messages(arb):
291 arb_str += template.format(make_c_string(item[1]))
292 arb_str = arb_str[:-1] # trim trailing newline
295 def get_class_messages(cls):
303 threshold = item["threshold"]
304 message = make_c_string(item["message"])
305 cls_str += template.format(threshold, message)
306 cls_str = cls_str[:-1] # trim trailing newline
309 def get_turn_thresholds(trn):
318 threshold = item["threshold"]
319 point_loss = item["point_loss"]
320 message = make_c_string(item["message"])
321 trn_str += template.format(threshold, point_loss, message)
322 trn_str = trn_str[:-1] # trim trailing newline
325 def get_locations(loc):
326 template = """ {{ // {}: {}
336 for (i, item) in enumerate(loc):
337 short_d = make_c_string(item[1]["description"]["short"])
338 long_d = make_c_string(item[1]["description"]["long"])
339 sound = item[1].get("sound", "SILENT")
340 loud = "true" if item[1].get("loud") else "false"
341 loc_str += template.format(i, item[0], short_d, long_d, sound, loud)
342 loc_str = loc_str[:-1] # trim trailing newline
345 def get_objects(obj):
346 template = """ {{ // {}: {}
352 .descriptions = (const char* []) {{
355 .sounds = (const char* []) {{
358 .texts = (const char* []) {{
361 .changes = (const char* []) {{
367 for (i, item) in enumerate(obj):
370 words_str = get_string_group(attr["words"])
372 words_str = get_string_group([])
373 i_msg = make_c_string(attr["inventory"])
374 descriptions_str = ""
375 if attr["descriptions"] == None:
376 descriptions_str = " " * 12 + "NULL,"
379 for l_msg in attr["descriptions"]:
380 descriptions_str += " " * 12 + make_c_string(l_msg) + ",\n"
381 for label in attr.get("states", []):
383 descriptions_str = descriptions_str[:-1] # trim trailing newline
386 statedefines += "/* States for %s */\n" % item[0]
387 for (i, label) in enumerate(labels):
388 statedefines += "#define %s\t%d\n" % (label, i)
391 if attr.get("sounds") == None:
392 sounds_str = " " * 12 + "NULL,"
394 for l_msg in attr["sounds"]:
395 sounds_str += " " * 12 + make_c_string(l_msg) + ",\n"
396 sounds_str = sounds_str[:-1] # trim trailing newline
398 if attr.get("texts") == None:
399 texts_str = " " * 12 + "NULL,"
401 for l_msg in attr["texts"]:
402 texts_str += " " * 12 + make_c_string(l_msg) + ",\n"
403 texts_str = texts_str[:-1] # trim trailing newline
405 if attr.get("changes") == None:
406 changes_str = " " * 12 + "NULL,"
408 for l_msg in attr["changes"]:
409 changes_str += " " * 12 + make_c_string(l_msg) + ",\n"
410 changes_str = changes_str[:-1] # trim trailing newline
411 locs = attr.get("locations", ["LOC_NOWHERE", "LOC_NOWHERE"])
412 immovable = attr.get("immovable", False)
414 if type(locs) == str:
415 locs = [locs, -1 if immovable else 0]
417 sys.stderr.write("dungeon: unknown object location in %s\n" % locs)
419 treasure = "true" if attr.get("treasure") else "false"
420 obj_str += template.format(i, item[0], words_str, i_msg, locs[0], locs[1], treasure, descriptions_str, sounds_str, texts_str, changes_str)
421 obj_str = obj_str[:-1] # trim trailing newline
424 def get_obituaries(obit):
432 query = make_c_string(o["query"])
433 yes = make_c_string(o["yes_response"])
434 obit_str += template.format(query, yes)
435 obit_str = obit_str[:-1] # trim trailing newline
438 def get_hints(hnt, arb):
450 item = member["hint"]
451 number = item["number"]
452 penalty = item["penalty"]
453 turns = item["turns"]
454 question = make_c_string(item["question"])
455 hint = make_c_string(item["hint"])
456 hnt_str += template.format(number, penalty, turns, question, hint)
457 hnt_str = hnt_str[:-1] # trim trailing newline
460 def get_condbits(locations):
462 for (name, loc) in locations:
463 conditions = loc["conditions"]
464 hints = loc.get("hints") or []
466 for flag in conditions:
468 flaglist.append(flag)
469 line = "|".join([("(1<<COND_%s)" % f) for f in flaglist])
470 trail = "|".join([("(1<<COND_H%s)" % f['name']) for f in hints])
473 if line.startswith("|"):
477 cnd_str += " " + line + ",\t// " + name + "\n"
480 def get_motions(motions):
486 for motion in motions:
488 if contents["words"] == None:
489 words_str = get_string_group([])
491 words_str = get_string_group(contents["words"])
492 mot_str += template.format(words_str)
494 if contents.get("oldstyle", True) == False:
495 for word in contents["words"]:
497 ignore += word.upper()
500 def get_actions(actions):
507 for action in actions:
510 if contents["words"] == None:
511 words_str = get_string_group([])
513 words_str = get_string_group(contents["words"])
515 if contents["message"] == None:
516 message = "NO_MESSAGE"
518 message = contents["message"]
520 act_str += template.format(words_str, message)
522 if contents.get("oldstyle", True) == False:
523 for word in contents["words"]:
525 ignore += word.upper()
526 act_str = act_str[:-1] # trim trailing newline
529 def get_specials(specials):
536 for special in specials:
537 contents = special[1]
539 if contents["words"] == None:
540 words_str = get_string_group([])
542 words_str = get_string_group(contents["words"])
544 if contents["message"] == None:
547 message = make_c_string(contents["message"])
549 spc_str += template.format(words_str, message)
551 if contents.get("oldstyle", True) == False:
552 for word in contents["words"]:
554 ignore += word.upper()
555 spc_str = spc_str[:-1] # trim trailing newline
560 for (i, entry) in enumerate(arr):
562 if out and out[-1] == ' ':
565 out += str(arr[i]).lower() + ", "
566 out = out[:-2] + "\n"
569 def buildtravel(locs, objs):
570 assert len(locs) <= 300
571 assert len(objs) <= 100
572 # THIS CODE IS WAAAY MORE COMPLEX THAN IT NEEDS TO BE. It's the
573 # result of a massive refactoring exercise that concentrated all
574 # the old nastiness in one spot. It hasn't been finally simplified
575 # because there's no need to do it until one of the asserions
576 # fails. Hint: if you try cleaning this up, the acceptance test is
577 # simple - the output dungeon.c must not change.
579 # This function first compiles the YAML to a form identical to the
580 # data in section 3 of the old adventure.text file, then a second
581 # stage unpacks that data into the travel array. Here are the
582 # rules of that intermediate form:
584 # Each row of data contains a location number (X), a second
585 # location number (Y), and a list of motion numbers (see section 4).
586 # each motion represents a verb which will go to Y if currently at X.
587 # Y, in turn, is interpreted as follows. Let M=Y/1000, N=Y mod 1000.
588 # If N<=300 it is the location to go to.
589 # If 300<N<=500 N-300 is used in a computed goto to
590 # a section of special code.
591 # If N>500 message N-500 from section 6 is printed,
592 # and he stays wherever he is.
593 # Meanwhile, M specifies the conditions on the motion.
594 # If M=0 it's unconditional.
595 # If 0<M<100 it is done with M% probability.
596 # If M=100 unconditional, but forbidden to dwarves.
597 # If 100<M<=200 he must be carrying object M-100.
598 # If 200<M<=300 must be carrying or in same room as M-200.
599 # If 300<M<=400 game.prop(M % 100) must *not* be 0.
600 # If 400<M<=500 game.prop(M % 100) must *not* be 1.
601 # If 500<M<=600 game.prop(M % 100) must *not* be 2, etc.
602 # If the condition (if any) is not met, then the next *different*
603 # "destination" value is used (unless it fails to meet *its* conditions,
604 # in which case the next is found, etc.). Typically, the next dest will
605 # be for one of the same verbs, so that its only use is as the alternate
606 # destination for those verbs. For instance:
607 # 15 110022 29 31 34 35 23 43
609 # This says that, from loc 15, any of the verbs 29, 31, etc., will take
610 # him to 22 if he's carrying object 10, and otherwise will go to 14.
613 # This says that, from 11, 49 takes him to 8 unless game.prop[3]=0, in which
614 # case he goes to 9. Verb 50 takes him to 9 regardless of game.prop[3].
617 for i, motion in enumerate(db["motions"]):
619 for word in motion[1]["words"]:
620 verbmap[word.upper()] = i
623 def dencode(action, name):
624 "Decode a destination number"
625 if action[0] == "goto":
627 return locnames.index(action[1])
629 sys.stderr.write("dungeon: unknown location %s in goto clause of %s\n" % (action[1], name))
630 elif action[0] == "special":
631 return 300 + action[1]
632 elif action[0] == "speak":
634 return 500 + msgnames.index(action[1])
636 sys.stderr.write("dungeon: unknown location %s in carry clause of %s\n" % (cond[1], name))
640 def cencode(cond, name):
643 elif cond == ["nodwarves"]:
645 elif cond[0] == "pct":
647 elif cond[0] == "carry":
649 return 100 + objnames.index(cond[1])
651 sys.stderr.write("dungeon: unknown object name %s in carry clause of %s\n" % (cond[1], name))
653 elif cond[0] == "with":
655 return 200 + objnames.index(cond[1])
657 sys.stderr.write("dungeon: unknown object name %s in with clause of \n" % (cond[1], name))
659 elif cond[0] == "not":
661 obj = objnames.index(cond[1])
662 if type(cond[2]) == int:
664 elif cond[2] in objs[obj][1].get("states", []):
665 state = objs[obj][1].get("states").index(cond[2])
667 for (i, stateclause) in enumerate(objs[obj][1]["descriptions"]):
668 if type(stateclause) == list:
669 if stateclause[0] == cond[2]:
673 sys.stderr.write("dungeon: unmatched state symbol %s in not clause of %s\n" % (cond[2], name))
675 return 300 + obj + 100 * state
677 sys.stderr.write("dungeon: unknown object name %s in not clause of %s\n" % (cond[1], name))
683 for (i, (name, loc)) in enumerate(locs):
685 for rule in loc["travel"]:
687 dest = dencode(rule["action"], name) + 1000 * cencode(rule.get("cond"), name)
689 tt += [motionnames[verbmap[e]].upper() for e in rule["verbs"]]
690 if not rule["verbs"]:
691 tt.append(1) # Magic dummy entry for null rules
692 ltravel.append(tuple(tt))
694 # At this point the ltravel data is in the Section 3
695 # representation from the FORTRAN version. Next we perform the
696 # same mapping into wgat used to be the runtime format.
698 travel = [[0, "LOC_NOWHERE", 0, 0, 0, 0, 0, 0, "false", "false"]]
702 rule = list(ltravel.pop(0))
706 tkey.append(len(travel))
709 travel[-1][-1] = "false" if travel[-1][-1] == "true" else "true"
711 cond = newloc // 1000
712 nodwarves = (cond == 100)
714 condtype = "cond_goto"
715 condarg1 = condarg2 = 0
717 condtype = "cond_pct"
721 condtype = "cond_goto"
725 condtype = "cond_carry"
726 condarg1 = objnames[cond - 100]
729 condtype = "cond_with"
730 condarg1 = objnames[cond - 200]
733 condtype = "cond_not"
734 condarg1 = cond % 100
735 condarg2 = (cond - 300) // 100.
738 desttype = "dest_goto";
739 destval = locnames[dest]
741 desttype = "dest_speak";
742 destval = msgnames[dest - 500]
744 desttype = "dest_special";
745 destval = locnames[dest - 300]
746 travel.append([len(tkey)-1,
747 locnames[len(tkey)-1],
754 "true" if nodwarves else "false",
756 travel[-1][-1] = "true"
757 return (travel, tkey)
759 def get_travel(travel):
760 template = """ {{ // from {}: {}
773 out += template.format(*entry)
774 out = out[:-1] # trim trailing newline
777 if __name__ == "__main__":
778 with open(yaml_name, "r") as f:
781 locnames = [x[0] for x in db["locations"]]
782 msgnames = [el[0] for el in db["arbitrary_messages"]]
783 objnames = [el[0] for el in db["objects"]]
784 motionnames = [el[0] for el in db["motions"]]
786 (travel, tkey) = buildtravel(db["locations"],
789 c = c_template.format(
791 get_arbitrary_messages(db["arbitrary_messages"]),
792 get_class_messages(db["classes"]),
793 get_turn_thresholds(db["turn_thresholds"]),
794 get_locations(db["locations"]),
795 get_objects(db["objects"]),
796 get_obituaries(db["obituaries"]),
797 get_hints(db["hints"], db["arbitrary_messages"]),
798 get_condbits(db["locations"]),
799 get_motions(db["motions"]),
800 get_specials(db["actions"]),
801 get_specials(db["specials"]),
807 # 0-origin index of birds's last song. Bird should
808 # die after player hears this.
809 deathbird = len(dict(db["objects"])["BIRD"]["sounds"]) - 1
811 h = h_template.format(
812 len(db["locations"])-1,
813 len(db["objects"])-1,
815 len(db["classes"])-1,
816 len(db["obituaries"]),
817 len(db["turn_thresholds"]),
824 get_refs(db["arbitrary_messages"]),
825 get_refs(db["locations"]),
826 get_refs(db["objects"]),
827 get_refs(db["motions"]),
828 get_refs(db["actions"]),
829 get_refs(db["specials"]),
833 with open(h_name, "w") as hf:
836 with open(c_name, "w") as cf: