3 # This is the new open-adventure dungeon generator. It'll eventually
4 # replace the existing dungeon.c It currently outputs a .h and .c pair
7 # The nontrivial part of this is the compilation of the YAML for
8 # movement rules to the travel array that's actually used by
13 yaml_name = "adventure.yaml"
19 h_template = """/* Generated from adventure.yaml - do not hand-hack! */
26 #define SILENT -1 /* no sound */
28 /* Symbols for cond bits */
29 #define COND_LIT 0 /* Light */
30 #define COND_OILY 1 /* If bit 2 is on: on for oil, off for water */
31 #define COND_FLUID 2 /* Liquid asset, see bit 1 */
32 #define COND_NOARRR 3 /* Pirate doesn't go here unless following */
33 #define COND_NOBACK 4 /* Cannot use "back" to move away */
35 #define COND_DEEP 6 /* Deep - e.g where dwarves are active */
36 #define COND_FOREST 7 /* In the forest */
37 #define COND_FORCED 8 /* Only one way in or out of here */
38 /* Bits past 10 indicate areas of interest to "hint" routines */
39 #define COND_HBASE 10 /* Base for location hint bits */
40 #define COND_HCAVE 11 /* Trying to get into cave */
41 #define COND_HBIRD 12 /* Trying to catch bird */
42 #define COND_HSNAKE 13 /* Trying to deal with snake */
43 #define COND_HMAZE 14 /* Lost in maze */
44 #define COND_HDARK 15 /* Pondering dark room */
45 #define COND_HWITT 16 /* At Witt's End */
46 #define COND_HCLIFF 17 /* Cliff with urn */
47 #define COND_HWOODS 18 /* Lost in forest */
48 #define COND_HOGRE 19 /* Trying to deal with ogre */
49 #define COND_HJADE 20 /* Found all treasures except jade */
57 const string_group_t words;
58 const char* inventory;
61 const char** descriptions;
73 descriptions_t description;
80 const char* yes_response;
103 const string_group_t words;
107 const string_group_t words;
112 const string_group_t words;
116 enum condtype_t {{cond_goto, cond_pct, cond_carry, cond_with, cond_not}};
117 enum desttype_t {{dest_goto, dest_special, dest_speak}};
124 const enum desttype_t desttype;
126 const bool nodwarves;
130 /* Abstract out the encoding of words in the travel array. Gives us
131 * some hope of getting to a less cryptic representation than we
132 * inherited from FORTRAN, someday. To understand these, read the
133 * encoding description for travel.
135 #define T_TERMINATE(entry) ((entry).motion == 1)
137 extern const location_t locations[];
138 extern const object_t objects[];
139 extern const char* arbitrary_messages[];
140 extern const class_t classes[];
141 extern const turn_threshold_t turn_thresholds[];
142 extern const obituary_t obituaries[];
143 extern const hint_t hints[];
144 extern long conditions[];
145 extern const motion_t motions[];
146 extern const action_t actions[];
147 extern const special_t specials[];
148 extern const travelop_t travel[];
149 extern const long tkey[];
150 extern const char *ignore;
152 #define NLOCATIONS {}
157 #define NTHRESHOLDS {}
164 #define BIRD_ENDSTATE {}
166 enum arbitrary_messages_refs {{
170 enum locations_refs {{
190 /* State definitions */
193 #endif /* end DUNGEON_H */
196 c_template = """/* Generated from adventure.yaml - do not hand-hack! */
200 const char* arbitrary_messages[] = {{
204 const class_t classes[] = {{
208 const turn_threshold_t turn_thresholds[] = {{
212 const location_t locations[] = {{
216 const object_t objects[] = {{
220 const obituary_t obituaries[] = {{
224 const hint_t hints[] = {{
228 long conditions[] = {{
232 const motion_t motions[] = {{
236 const action_t actions[] = {{
240 const special_t specials[] = {{
244 const long tkey[] = {{{}}};
246 const travelop_t travel[] = {{
250 const char *ignore = \"{}\";
255 def make_c_string(string):
256 """Render a Python string into C string literal format."""
259 string = string.replace("\n", "\\n")
260 string = string.replace("\t", "\\t")
261 string = string.replace('"', '\\"')
262 string = string.replace("'", "\\'")
263 string = '"' + string + '"'
267 reflist = [x[0] for x in l]
270 ref_str += " {},\n".format(ref)
271 ref_str = ref_str[:-1] # trim trailing newline
274 def get_string_group(strings):
282 strs = "(const char* []) {" + ", ".join([make_c_string(s) for s in strings]) + "}"
284 sg_str = template.format(strs, n)
287 def get_arbitrary_messages(arb):
292 arb_str += template.format(make_c_string(item[1]))
293 arb_str = arb_str[:-1] # trim trailing newline
296 def get_class_messages(cls):
304 threshold = item["threshold"]
305 message = make_c_string(item["message"])
306 cls_str += template.format(threshold, message)
307 cls_str = cls_str[:-1] # trim trailing newline
310 def get_turn_thresholds(trn):
319 threshold = item["threshold"]
320 point_loss = item["point_loss"]
321 message = make_c_string(item["message"])
322 trn_str += template.format(threshold, point_loss, message)
323 trn_str = trn_str[:-1] # trim trailing newline
326 def get_locations(loc):
327 template = """ {{ // {}: {}
337 for (i, item) in enumerate(loc):
338 short_d = make_c_string(item[1]["description"]["short"])
339 long_d = make_c_string(item[1]["description"]["long"])
340 sound = item[1].get("sound", "SILENT")
341 loud = "true" if item[1].get("loud") else "false"
342 loc_str += template.format(i, item[0], short_d, long_d, sound, loud)
343 loc_str = loc_str[:-1] # trim trailing newline
346 def get_objects(obj):
347 template = """ {{ // {}: {}
353 .descriptions = (const char* []) {{
356 .sounds = (const char* []) {{
359 .texts = (const char* []) {{
362 .changes = (const char* []) {{
368 for (i, item) in enumerate(obj):
371 words_str = get_string_group(attr["words"])
373 words_str = get_string_group([])
374 i_msg = make_c_string(attr["inventory"])
375 descriptions_str = ""
376 if attr["descriptions"] == None:
377 descriptions_str = " " * 12 + "NULL,"
380 for l_msg in attr["descriptions"]:
381 descriptions_str += " " * 12 + make_c_string(l_msg) + ",\n"
382 for label in attr.get("states", []):
384 descriptions_str = descriptions_str[:-1] # trim trailing newline
387 statedefines += "/* States for %s */\n" % item[0]
388 for (i, label) in enumerate(labels):
389 statedefines += "#define %s\t%d\n" % (label, i)
392 if attr.get("sounds") == None:
393 sounds_str = " " * 12 + "NULL,"
395 for l_msg in attr["sounds"]:
396 sounds_str += " " * 12 + make_c_string(l_msg) + ",\n"
397 sounds_str = sounds_str[:-1] # trim trailing newline
399 if attr.get("texts") == None:
400 texts_str = " " * 12 + "NULL,"
402 for l_msg in attr["texts"]:
403 texts_str += " " * 12 + make_c_string(l_msg) + ",\n"
404 texts_str = texts_str[:-1] # trim trailing newline
406 if attr.get("changes") == None:
407 changes_str = " " * 12 + "NULL,"
409 for l_msg in attr["changes"]:
410 changes_str += " " * 12 + make_c_string(l_msg) + ",\n"
411 changes_str = changes_str[:-1] # trim trailing newline
412 locs = attr.get("locations", ["LOC_NOWHERE", "LOC_NOWHERE"])
413 immovable = attr.get("immovable", False)
415 if type(locs) == str:
416 locs = [locs, -1 if immovable else 0]
418 sys.stderr.write("dungeon: unknown object location in %s\n" % locs)
420 treasure = "true" if attr.get("treasure") else "false"
421 obj_str += template.format(i, item[0], words_str, i_msg, locs[0], locs[1], treasure, descriptions_str, sounds_str, texts_str, changes_str)
422 obj_str = obj_str[:-1] # trim trailing newline
425 def get_obituaries(obit):
433 query = make_c_string(o["query"])
434 yes = make_c_string(o["yes_response"])
435 obit_str += template.format(query, yes)
436 obit_str = obit_str[:-1] # trim trailing newline
439 def get_hints(hnt, arb):
451 item = member["hint"]
452 number = item["number"]
453 penalty = item["penalty"]
454 turns = item["turns"]
455 question = make_c_string(item["question"])
456 hint = make_c_string(item["hint"])
457 hnt_str += template.format(number, penalty, turns, question, hint)
458 hnt_str = hnt_str[:-1] # trim trailing newline
461 def get_condbits(locations):
463 for (name, loc) in locations:
464 conditions = loc["conditions"]
465 hints = loc.get("hints") or []
467 for flag in conditions:
469 flaglist.append(flag)
470 line = "|".join([("(1<<COND_%s)" % f) for f in flaglist])
471 trail = "|".join([("(1<<COND_H%s)" % f['name']) for f in hints])
474 if line.startswith("|"):
478 cnd_str += " " + line + ",\t// " + name + "\n"
481 def get_motions(motions):
487 for motion in motions:
489 if contents["words"] == None:
490 words_str = get_string_group([])
492 words_str = get_string_group(contents["words"])
493 mot_str += template.format(words_str)
495 if contents.get("oldstyle", True) == False:
496 for word in contents["words"]:
498 ignore += word.upper()
501 def get_actions(actions):
508 for action in actions:
511 if contents["words"] == None:
512 words_str = get_string_group([])
514 words_str = get_string_group(contents["words"])
516 if contents["message"] == None:
517 message = "NO_MESSAGE"
519 message = contents["message"]
521 act_str += template.format(words_str, message)
523 if contents.get("oldstyle", True) == False:
524 for word in contents["words"]:
526 ignore += word.upper()
527 act_str = act_str[:-1] # trim trailing newline
530 def get_specials(specials):
537 for special in specials:
538 contents = special[1]
540 if contents["words"] == None:
541 words_str = get_string_group([])
543 words_str = get_string_group(contents["words"])
545 if contents["message"] == None:
548 message = make_c_string(contents["message"])
550 spc_str += template.format(words_str, message)
552 if contents.get("oldstyle", True) == False:
553 for word in contents["words"]:
555 ignore += word.upper()
556 spc_str = spc_str[:-1] # trim trailing newline
561 for (i, entry) in enumerate(arr):
563 if out and out[-1] == ' ':
566 out += str(arr[i]).lower() + ", "
567 out = out[:-2] + "\n"
570 def buildtravel(locs, objs):
571 assert len(locs) <= 300
572 assert len(objs) <= 100
573 # THIS CODE IS WAAAY MORE COMPLEX THAN IT NEEDS TO BE. It's the
574 # result of a massive refactoring exercise that concentrated all
575 # the old nastiness in one spot. It hasn't been finally simplified
576 # because there's no need to do it until one of the asserions
577 # fails. Hint: if you try cleaning this up, the acceptance test is
578 # simple - the output dungeon.c must not change.
580 # This function first compiles the YAML to a form identical to the
581 # data in section 3 of the old adventure.text file, then a second
582 # stage unpacks that data into the travel array. Here are the
583 # rules of that intermediate form:
585 # Each row of data contains a location number (X), a second
586 # location number (Y), and a list of motion numbers (see section 4).
587 # each motion represents a verb which will go to Y if currently at X.
588 # Y, in turn, is interpreted as follows. Let M=Y/1000, N=Y mod 1000.
589 # If N<=300 it is the location to go to.
590 # If 300<N<=500 N-300 is used in a computed goto to
591 # a section of special code.
592 # If N>500 message N-500 from section 6 is printed,
593 # and he stays wherever he is.
594 # Meanwhile, M specifies the conditions on the motion.
595 # If M=0 it's unconditional.
596 # If 0<M<100 it is done with M% probability.
597 # If M=100 unconditional, but forbidden to dwarves.
598 # If 100<M<=200 he must be carrying object M-100.
599 # If 200<M<=300 must be carrying or in same room as M-200.
600 # If 300<M<=400 game.prop(M % 100) must *not* be 0.
601 # If 400<M<=500 game.prop(M % 100) must *not* be 1.
602 # If 500<M<=600 game.prop(M % 100) must *not* be 2, etc.
603 # If the condition (if any) is not met, then the next *different*
604 # "destination" value is used (unless it fails to meet *its* conditions,
605 # in which case the next is found, etc.). Typically, the next dest will
606 # be for one of the same verbs, so that its only use is as the alternate
607 # destination for those verbs. For instance:
608 # 15 110022 29 31 34 35 23 43
610 # This says that, from loc 15, any of the verbs 29, 31, etc., will take
611 # him to 22 if he's carrying object 10, and otherwise will go to 14.
614 # This says that, from 11, 49 takes him to 8 unless game.prop(3)=0, in which
615 # case he goes to 9. Verb 50 takes him to 9 regardless of game.prop(3).
618 for i, motion in enumerate(db["motions"]):
620 for word in motion[1]["words"]:
621 verbmap[word.upper()] = i
624 def dencode(action, name):
625 "Decode a destination number"
626 if action[0] == "goto":
628 return locnames.index(action[1])
630 sys.stderr.write("dungeon: unknown location %s in goto clause of %s\n" % (cond[1], name))
631 elif action[0] == "special":
632 return 300 + action[1]
633 elif action[0] == "speak":
635 return 500 + msgnames.index(action[1])
637 sys.stderr.write("dungeon: unknown location %s in carry clause of %s\n" % (cond[1], name))
641 def cencode(cond, name):
644 elif cond == ["nodwarves"]:
646 elif cond[0] == "pct":
648 elif cond[0] == "carry":
650 return 100 + objnames.index(cond[1])
652 sys.stderr.write("dungeon: unknown object name %s in carry clause of %s\n" % (cond[1], name))
654 elif cond[0] == "with":
656 return 200 + objnames.index(cond[1])
658 sys.stderr.write("dungeon: unknown object name %s in with clause of \n" % (cond[1], name))
660 elif cond[0] == "not":
662 obj = objnames.index(cond[1])
663 if type(cond[2]) == int:
665 elif cond[2] in objs[obj][1].get("states", []):
666 state = objs[obj][1].get("states").index(cond[2])
668 for (i, stateclause) in enumerate(objs[obj][1]["descriptions"]):
669 if type(stateclause) == list:
670 if stateclause[0] == cond[2]:
674 sys.stderr.write("dungeon: unmatched state symbol %s in not clause of %s\n" % (cond[2], name))
676 return 300 + obj + 100 * state
678 sys.stderr.write("dungeon: unknown object name %s in not clause of %s\n" % (cond[1], name))
684 for (i, (name, loc)) in enumerate(locs):
686 for rule in loc["travel"]:
688 dest = dencode(rule["action"], name) + 1000 * cencode(rule.get("cond"), name)
690 tt += [motionnames[verbmap[e]].upper() for e in rule["verbs"]]
691 if not rule["verbs"]:
693 ltravel.append(tuple(tt))
695 # At this point the ltravel data is in the Section 3
696 # representation from the FORTRAN version. Next we perform the
697 # same mapping into wgat used to be the runtime format.
699 travel = [[0, "LOC_NOWHERE", 0, 0, 0, 0, 0, 0, "false", "false"]]
703 rule = list(ltravel.pop(0))
707 tkey.append(len(travel))
710 travel[-1][-1] = "false" if travel[-1][-1] == "true" else "true"
712 cond = newloc // 1000
713 nodwarves = (cond == 100)
715 condtype = "cond_goto"
716 condarg1 = condarg2 = 0
718 condtype = "cond_pct"
722 condtype = "cond_goto"
726 condtype = "cond_carry"
727 condarg1 = objnames[cond - 100]
730 condtype = "cond_with"
731 condarg1 = objnames[cond - 200]
734 condtype = "cond_not"
735 condarg1 = cond % 100
736 condarg2 = (cond - 300) // 100.
739 desttype = "dest_goto";
740 destval = locnames[dest]
742 desttype = "dest_speak";
743 destval = msgnames[dest - 500]
745 desttype = "dest_special";
746 destval = locnames[dest - 300]
747 travel.append([len(tkey)-1,
748 locnames[len(tkey)-1],
755 "true" if nodwarves else "false",
757 travel[-1][-1] = "true"
758 return (travel, tkey)
760 def get_travel(travel):
761 template = """ {{ // from {}: {}
774 out += template.format(*entry)
775 out = out[:-1] # trim trailing newline
778 if __name__ == "__main__":
779 with open(yaml_name, "r") as f:
782 locnames = [x[0] for x in db["locations"]]
783 msgnames = [el[0] for el in db["arbitrary_messages"]]
784 objnames = [el[0] for el in db["objects"]]
785 motionnames = [el[0] for el in db["motions"]]
787 (travel, tkey) = buildtravel(db["locations"],
790 c = c_template.format(
792 get_arbitrary_messages(db["arbitrary_messages"]),
793 get_class_messages(db["classes"]),
794 get_turn_thresholds(db["turn_thresholds"]),
795 get_locations(db["locations"]),
796 get_objects(db["objects"]),
797 get_obituaries(db["obituaries"]),
798 get_hints(db["hints"], db["arbitrary_messages"]),
799 get_condbits(db["locations"]),
800 get_motions(db["motions"]),
801 get_specials(db["actions"]),
802 get_specials(db["specials"]),
808 # 0-origin index of birds's last song. Bird should
809 # die after player hears this.
810 deathbird = len(dict(db["objects"])["BIRD"]["sounds"]) - 1
812 h = h_template.format(
813 len(db["locations"])-1,
814 len(db["objects"])-1,
816 len(db["classes"])-1,
817 len(db["obituaries"]),
818 len(db["turn_thresholds"]),
825 get_refs(db["arbitrary_messages"]),
826 get_refs(db["locations"]),
827 get_refs(db["objects"]),
828 get_refs(db["motions"]),
829 get_refs(db["actions"]),
830 get_refs(db["specials"]),
834 with open(h_name, "w") as hf:
837 with open(c_name, "w") as cf: