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;
112 const string_group_t words;
117 enum condtype_t {{cond_goto, cond_pct, cond_carry, cond_with, cond_not}};
118 enum desttype_t {{dest_goto, dest_special, dest_speak}};
125 const enum desttype_t desttype;
127 const bool nodwarves;
131 /* Abstract out the encoding of words in the travel array. Gives us
132 * some hope of getting to a less cryptic representation than we
133 * inherited from FORTRAN, someday. To understand these, read the
134 * encoding description for travel.
136 #define T_TERMINATE(entry) ((entry).motion == 1)
138 extern const location_t locations[];
139 extern const object_t objects[];
140 extern const char* arbitrary_messages[];
141 extern const class_t classes[];
142 extern const turn_threshold_t turn_thresholds[];
143 extern const obituary_t obituaries[];
144 extern const hint_t hints[];
145 extern long conditions[];
146 extern const motion_t motions[];
147 extern const action_t actions[];
148 extern const special_t specials[];
149 extern const travelop_t travel[];
150 extern const long tkey[];
151 extern const char *ignore;
153 #define NLOCATIONS {}
158 #define NTHRESHOLDS {}
165 #define BIRD_ENDSTATE {}
167 enum arbitrary_messages_refs {{
171 enum locations_refs {{
191 /* State definitions */
194 #endif /* end DUNGEON_H */
197 c_template = """/* Generated from adventure.yaml - do not hand-hack! */
201 const char* arbitrary_messages[] = {{
205 const class_t classes[] = {{
209 const turn_threshold_t turn_thresholds[] = {{
213 const location_t locations[] = {{
217 const object_t objects[] = {{
221 const obituary_t obituaries[] = {{
225 const hint_t hints[] = {{
229 long conditions[] = {{
233 const motion_t motions[] = {{
237 const action_t actions[] = {{
241 const special_t specials[] = {{
245 const long tkey[] = {{{}}};
247 const travelop_t travel[] = {{
251 const char *ignore = \"{}\";
256 def make_c_string(string):
257 """Render a Python string into C string literal format."""
260 string = string.replace("\n", "\\n")
261 string = string.replace("\t", "\\t")
262 string = string.replace('"', '\\"')
263 string = string.replace("'", "\\'")
264 string = '"' + string + '"'
268 reflist = [x[0] for x in l]
271 ref_str += " {},\n".format(ref)
272 ref_str = ref_str[:-1] # trim trailing newline
275 def get_string_group(strings):
283 strs = "(const char* []) {" + ", ".join([make_c_string(s) for s in strings]) + "}"
285 sg_str = template.format(strs, n)
288 def get_arbitrary_messages(arb):
293 arb_str += template.format(make_c_string(item[1]))
294 arb_str = arb_str[:-1] # trim trailing newline
297 def get_class_messages(cls):
305 threshold = item["threshold"]
306 message = make_c_string(item["message"])
307 cls_str += template.format(threshold, message)
308 cls_str = cls_str[:-1] # trim trailing newline
311 def get_turn_thresholds(trn):
320 threshold = item["threshold"]
321 point_loss = item["point_loss"]
322 message = make_c_string(item["message"])
323 trn_str += template.format(threshold, point_loss, message)
324 trn_str = trn_str[:-1] # trim trailing newline
327 def get_locations(loc):
328 template = """ {{ // {}: {}
338 for (i, item) in enumerate(loc):
339 short_d = make_c_string(item[1]["description"]["short"])
340 long_d = make_c_string(item[1]["description"]["long"])
341 sound = item[1].get("sound", "SILENT")
342 loud = "true" if item[1].get("loud") else "false"
343 loc_str += template.format(i, item[0], short_d, long_d, sound, loud)
344 loc_str = loc_str[:-1] # trim trailing newline
347 def get_objects(obj):
348 template = """ {{ // {}: {}
354 .descriptions = (const char* []) {{
357 .sounds = (const char* []) {{
360 .texts = (const char* []) {{
363 .changes = (const char* []) {{
369 for (i, item) in enumerate(obj):
372 words_str = get_string_group(attr["words"])
374 words_str = get_string_group([])
375 i_msg = make_c_string(attr["inventory"])
376 descriptions_str = ""
377 if attr["descriptions"] == None:
378 descriptions_str = " " * 12 + "NULL,"
381 for l_msg in attr["descriptions"]:
382 descriptions_str += " " * 12 + make_c_string(l_msg) + ",\n"
383 for label in attr.get("states", []):
385 descriptions_str = descriptions_str[:-1] # trim trailing newline
388 statedefines += "/* States for %s */\n" % item[0]
389 for (j, label) in enumerate(labels):
390 statedefines += "#define %s\t%d\n" % (label, j)
393 if attr.get("sounds") == None:
394 sounds_str = " " * 12 + "NULL,"
396 for l_msg in attr["sounds"]:
397 sounds_str += " " * 12 + make_c_string(l_msg) + ",\n"
398 sounds_str = sounds_str[:-1] # trim trailing newline
400 if attr.get("texts") == None:
401 texts_str = " " * 12 + "NULL,"
403 for l_msg in attr["texts"]:
404 texts_str += " " * 12 + make_c_string(l_msg) + ",\n"
405 texts_str = texts_str[:-1] # trim trailing newline
407 if attr.get("changes") == None:
408 changes_str = " " * 12 + "NULL,"
410 for l_msg in attr["changes"]:
411 changes_str += " " * 12 + make_c_string(l_msg) + ",\n"
412 changes_str = changes_str[:-1] # trim trailing newline
413 locs = attr.get("locations", ["LOC_NOWHERE", "LOC_NOWHERE"])
414 immovable = attr.get("immovable", False)
416 if type(locs) == str:
417 locs = [locs, -1 if immovable else 0]
419 sys.stderr.write("dungeon: unknown object location in %s\n" % locs)
421 treasure = "true" if attr.get("treasure") else "false"
422 obj_str += template.format(i, item[0], words_str, i_msg, locs[0], locs[1], treasure, descriptions_str, sounds_str, texts_str, changes_str)
423 obj_str = obj_str[:-1] # trim trailing newline
426 def get_obituaries(obit):
434 query = make_c_string(o["query"])
435 yes = make_c_string(o["yes_response"])
436 obit_str += template.format(query, yes)
437 obit_str = obit_str[:-1] # trim trailing newline
440 def get_hints(hnt, arb):
452 item = member["hint"]
453 number = item["number"]
454 penalty = item["penalty"]
455 turns = item["turns"]
456 question = make_c_string(item["question"])
457 hint = make_c_string(item["hint"])
458 hnt_str += template.format(number, penalty, turns, question, hint)
459 hnt_str = hnt_str[:-1] # trim trailing newline
462 def get_condbits(locations):
464 for (name, loc) in locations:
465 conditions = loc["conditions"]
466 hints = loc.get("hints") or []
468 for flag in conditions:
470 flaglist.append(flag)
471 line = "|".join([("(1<<COND_%s)" % f) for f in flaglist])
472 trail = "|".join([("(1<<COND_H%s)" % f['name']) for f in hints])
475 if line.startswith("|"):
479 cnd_str += " " + line + ",\t// " + name + "\n"
482 def get_motions(motions):
488 for motion in motions:
490 if contents["words"] == None:
491 words_str = get_string_group([])
493 words_str = get_string_group(contents["words"])
494 mot_str += template.format(words_str)
496 if contents.get("oldstyle", True) == False:
497 for word in contents["words"]:
499 ignore += word.upper()
502 def get_specials(specials):
510 for special in specials:
511 contents = special[1]
513 if contents["words"] == None:
514 words_str = get_string_group([])
516 words_str = get_string_group(contents["words"])
518 if contents["message"] == None:
521 message = make_c_string(contents["message"])
523 if contents.get("noaction") == None:
528 spc_str += template.format(words_str, message, noaction)
530 if contents.get("oldstyle", True) == False:
531 for word in contents["words"]:
533 ignore += word.upper()
534 spc_str = spc_str[:-1] # trim trailing newline
539 for (i, entry) in enumerate(arr):
541 if out and out[-1] == ' ':
544 out += str(arr[i]).lower() + ", "
545 out = out[:-2] + "\n"
548 def buildtravel(locs, objs):
549 assert len(locs) <= 300
550 assert len(objs) <= 100
551 # THIS CODE IS WAAAY MORE COMPLEX THAN IT NEEDS TO BE. It's the
552 # result of a massive refactoring exercise that concentrated all
553 # the old nastiness in one spot. It hasn't been finally simplified
554 # because there's no need to do it until one of the asserions
555 # fails. Hint: if you try cleaning this up, the acceptance test is
556 # simple - the output dungeon.c must not change.
558 # This function first compiles the YAML to a form identical to the
559 # data in section 3 of the old adventure.text file, then a second
560 # stage unpacks that data into the travel array. Here are the
561 # rules of that intermediate form:
563 # Each row of data contains a location number (X), a second
564 # location number (Y), and a list of motion numbers (see section 4).
565 # each motion represents a verb which will go to Y if currently at X.
566 # Y, in turn, is interpreted as follows. Let M=Y/1000, N=Y mod 1000.
567 # If N<=300 it is the location to go to.
568 # If 300<N<=500 N-300 is used in a computed goto to
569 # a section of special code.
570 # If N>500 message N-500 from section 6 is printed,
571 # and he stays wherever he is.
572 # Meanwhile, M specifies the conditions on the motion.
573 # If M=0 it's unconditional.
574 # If 0<M<100 it is done with M% probability.
575 # If M=100 unconditional, but forbidden to dwarves.
576 # If 100<M<=200 he must be carrying object M-100.
577 # If 200<M<=300 must be carrying or in same room as M-200.
578 # If 300<M<=400 game.prop(M % 100) must *not* be 0.
579 # If 400<M<=500 game.prop(M % 100) must *not* be 1.
580 # If 500<M<=600 game.prop(M % 100) must *not* be 2, etc.
581 # If the condition (if any) is not met, then the next *different*
582 # "destination" value is used (unless it fails to meet *its* conditions,
583 # in which case the next is found, etc.). Typically, the next dest will
584 # be for one of the same verbs, so that its only use is as the alternate
585 # destination for those verbs. For instance:
586 # 15 110022 29 31 34 35 23 43
588 # This says that, from loc 15, any of the verbs 29, 31, etc., will take
589 # him to 22 if he's carrying object 10, and otherwise will go to 14.
592 # This says that, from 11, 49 takes him to 8 unless game.prop[3]=0, in which
593 # case he goes to 9. Verb 50 takes him to 9 regardless of game.prop[3].
596 for i, motion in enumerate(db["motions"]):
598 for word in motion[1]["words"]:
599 verbmap[word.upper()] = i
602 def dencode(action, name):
603 "Decode a destination number"
604 if action[0] == "goto":
606 return locnames.index(action[1])
608 sys.stderr.write("dungeon: unknown location %s in goto clause of %s\n" % (action[1], name))
609 elif action[0] == "special":
610 return 300 + action[1]
611 elif action[0] == "speak":
613 return 500 + msgnames.index(action[1])
615 sys.stderr.write("dungeon: unknown location %s in carry clause of %s\n" % (cond[1], name))
619 def cencode(cond, name):
622 elif cond == ["nodwarves"]:
624 elif cond[0] == "pct":
626 elif cond[0] == "carry":
628 return 100 + objnames.index(cond[1])
630 sys.stderr.write("dungeon: unknown object name %s in carry clause of %s\n" % (cond[1], name))
632 elif cond[0] == "with":
634 return 200 + objnames.index(cond[1])
636 sys.stderr.write("dungeon: unknown object name %s in with clause of \n" % (cond[1], name))
638 elif cond[0] == "not":
640 obj = objnames.index(cond[1])
641 if type(cond[2]) == int:
643 elif cond[2] in objs[obj][1].get("states", []):
644 state = objs[obj][1].get("states").index(cond[2])
646 for (i, stateclause) in enumerate(objs[obj][1]["descriptions"]):
647 if type(stateclause) == list:
648 if stateclause[0] == cond[2]:
652 sys.stderr.write("dungeon: unmatched state symbol %s in not clause of %s\n" % (cond[2], name))
654 return 300 + obj + 100 * state
656 sys.stderr.write("dungeon: unknown object name %s in not clause of %s\n" % (cond[1], name))
662 for (i, (name, loc)) in enumerate(locs):
664 for rule in loc["travel"]:
666 dest = dencode(rule["action"], name) + 1000 * cencode(rule.get("cond"), name)
668 tt += [motionnames[verbmap[e]].upper() for e in rule["verbs"]]
669 if not rule["verbs"]:
670 tt.append(1) # Magic dummy entry for null rules
671 ltravel.append(tuple(tt))
673 # At this point the ltravel data is in the Section 3
674 # representation from the FORTRAN version. Next we perform the
675 # same mapping into wgat used to be the runtime format.
677 travel = [[0, "LOC_NOWHERE", 0, 0, 0, 0, 0, 0, "false", "false"]]
681 rule = list(ltravel.pop(0))
685 tkey.append(len(travel))
688 travel[-1][-1] = "false" if travel[-1][-1] == "true" else "true"
690 cond = newloc // 1000
691 nodwarves = (cond == 100)
693 condtype = "cond_goto"
694 condarg1 = condarg2 = 0
696 condtype = "cond_pct"
700 condtype = "cond_goto"
704 condtype = "cond_carry"
705 condarg1 = objnames[cond - 100]
708 condtype = "cond_with"
709 condarg1 = objnames[cond - 200]
712 condtype = "cond_not"
713 condarg1 = cond % 100
714 condarg2 = (cond - 300) // 100.
717 desttype = "dest_goto";
718 destval = locnames[dest]
720 desttype = "dest_speak";
721 destval = msgnames[dest - 500]
723 desttype = "dest_special";
724 destval = locnames[dest - 300]
725 travel.append([len(tkey)-1,
726 locnames[len(tkey)-1],
733 "true" if nodwarves else "false",
735 travel[-1][-1] = "true"
736 return (travel, tkey)
738 def get_travel(travel):
739 template = """ {{ // from {}: {}
752 out += template.format(*entry)
753 out = out[:-1] # trim trailing newline
756 if __name__ == "__main__":
757 with open(yaml_name, "r") as f:
760 locnames = [x[0] for x in db["locations"]]
761 msgnames = [el[0] for el in db["arbitrary_messages"]]
762 objnames = [el[0] for el in db["objects"]]
763 motionnames = [el[0] for el in db["motions"]]
765 (travel, tkey) = buildtravel(db["locations"],
768 c = c_template.format(
770 get_arbitrary_messages(db["arbitrary_messages"]),
771 get_class_messages(db["classes"]),
772 get_turn_thresholds(db["turn_thresholds"]),
773 get_locations(db["locations"]),
774 get_objects(db["objects"]),
775 get_obituaries(db["obituaries"]),
776 get_hints(db["hints"], db["arbitrary_messages"]),
777 get_condbits(db["locations"]),
778 get_motions(db["motions"]),
779 get_specials(db["actions"]),
780 get_specials(db["specials"]),
786 # 0-origin index of birds's last song. Bird should
787 # die after player hears this.
788 deathbird = len(dict(db["objects"])["BIRD"]["sounds"]) - 1
790 h = h_template.format(
791 len(db["locations"])-1,
792 len(db["objects"])-1,
794 len(db["classes"])-1,
795 len(db["obituaries"]),
796 len(db["turn_thresholds"]),
803 get_refs(db["arbitrary_messages"]),
804 get_refs(db["locations"]),
805 get_refs(db["objects"]),
806 get_refs(db["motions"]),
807 get_refs(db["actions"]),
808 get_refs(db["specials"]),
812 with open(h_name, "w") as hf:
815 with open(c_name, "w") as cf: