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
9 yaml_name = "adventure.yaml"
15 h_template = """/* Generated from adventure.yaml - do not hand-hack! */
22 #define SILENT -1 /* no sound */
24 /* Symbols for cond bits */
25 #define COND_LIT 0 /* Light */
26 #define COND_OILY 1 /* If bit 2 is on: on for oil, off for water */
27 #define COND_FLUID 2 /* Liquid asset, see bit 1 */
28 #define COND_NOARRR 3 /* Pirate doesn't go here unless following */
29 #define COND_NOBACK 4 /* Cannot use "back" to move away */
31 #define COND_DEEP 6 /* Deep - e.g where dwarves are active */
32 #define COND_FOREST 7 /* In the forest */
33 #define COND_FORCED 8 /* Only one way in or out of here */
34 /* Bits past 10 indicate areas of interest to "hint" routines */
35 #define COND_HBASE 10 /* Base for location hint bits */
36 #define COND_HCAVE 11 /* Trying to get into cave */
37 #define COND_HBIRD 12 /* Trying to catch bird */
38 #define COND_HSNAKE 13 /* Trying to deal with snake */
39 #define COND_HMAZE 14 /* Lost in maze */
40 #define COND_HDARK 15 /* Pondering dark room */
41 #define COND_HWITT 16 /* At Witt's End */
42 #define COND_HCLIFF 17 /* Cliff with urn */
43 #define COND_HWOODS 18 /* Lost in forest */
44 #define COND_HOGRE 19 /* Trying to deal with ogre */
45 #define COND_HJADE 20 /* Found all treasures except jade */
48 const char* inventory;
62 descriptions_t description;
69 const char* yes_response;
100 extern const location_t locations[];
101 extern const object_t objects[];
102 extern const char* arbitrary_messages[];
103 extern const class_t classes[];
104 extern const turn_threshold_t turn_thresholds[];
105 extern const obituary_t obituaries[];
106 extern const hint_t hints[];
107 extern long conditions[];
108 extern const long actspk[];
109 extern const motion_t motions[];
110 extern const action_t actions[];
112 #define NLOCATIONS {}
117 #define NTHRESHOLDS {}
121 enum arbitrary_messages_refs {{
125 enum locations_refs {{
141 /* State definitions */
144 #endif /* end NEWDB_H */
147 c_template = """/* Generated from adventure.yaml - do not hand-hack! */
152 const char* arbitrary_messages[] = {{
156 const class_t classes[] = {{
160 const turn_threshold_t turn_thresholds[] = {{
164 const location_t locations[] = {{
168 const object_t objects[] = {{
172 const obituary_t obituaries[] = {{
176 const hint_t hints[] = {{
180 long conditions[] = {{
184 const long actspk[] = {{
189 const motion_t motions[] = {{
193 const action_t actions[] = {{
200 def make_c_string(string):
201 """Render a Python string into C string literal format."""
204 string = string.replace("\n", "\\n")
205 string = string.replace("\t", "\\t")
206 string = string.replace('"', '\\"')
207 string = string.replace("'", "\\'")
208 string = '"' + string + '"'
212 reflist = [x[0] for x in l]
215 ref_str += " {},\n".format(ref)
216 ref_str = ref_str[:-1] # trim trailing newline
219 def get_arbitrary_messages(arb):
224 arb_str += template.format(make_c_string(item[1]))
225 arb_str = arb_str[:-1] # trim trailing newline
228 def get_class_messages(cls):
236 threshold = item["threshold"]
237 message = make_c_string(item["message"])
238 cls_str += template.format(threshold, message)
239 cls_str = cls_str[:-1] # trim trailing newline
242 def get_turn_thresholds(trn):
251 threshold = item["threshold"]
252 point_loss = item["point_loss"]
253 message = make_c_string(item["message"])
254 trn_str += template.format(threshold, point_loss, message)
255 trn_str = trn_str[:-1] # trim trailing newline
258 def get_locations(loc):
259 template = """ {{ // {}
269 for (i, item) in enumerate(loc):
270 short_d = make_c_string(item[1]["description"]["short"])
271 long_d = make_c_string(item[1]["description"]["long"])
272 sound = item[1].get("sound", "SILENT")
273 loud = "true" if item[1].get("loud") else "false"
274 loc_str += template.format(i, short_d, long_d, sound, loud)
275 loc_str = loc_str[:-1] # trim trailing newline
278 def get_objects(obj):
279 template = """ {{ // {}
284 .longs = (const char* []) {{
287 .sounds = (const char* []) {{
290 .texts = (const char* []) {{
296 for (i, item) in enumerate(obj):
298 i_msg = make_c_string(attr["inventory"])
300 if attr["longs"] == None:
301 longs_str = " " * 12 + "NULL,"
304 for l_msg in attr["longs"]:
305 if not isinstance(l_msg, str):
308 longs_str += " " * 12 + make_c_string(l_msg) + ",\n"
309 longs_str = longs_str[:-1] # trim trailing newline
312 statedefines += "/* States for %s */\n" % item[0]
313 for (i, (label, message)) in enumerate(labels):
314 if len(message) >= 45:
315 message = message[:45] + "..."
316 statedefines += "#define %s\t%d /* %s */\n" % (label, i, message)
319 if attr.get("sounds") == None:
320 sounds_str = " " * 12 + "NULL,"
322 for l_msg in attr["sounds"]:
323 sounds_str += " " * 12 + make_c_string(l_msg) + ",\n"
324 sounds_str = sounds_str[:-1] # trim trailing newline
326 if attr.get("texts") == None:
327 texts_str = " " * 12 + "NULL,"
329 for l_msg in attr["texts"]:
330 texts_str += " " * 12 + make_c_string(l_msg) + ",\n"
331 texts_str = texts_str[:-1] # trim trailing newline
332 locs = attr.get("locations", ["LOC_NOWHERE", "LOC_NOWHERE"])
333 immovable = attr.get("immovable", False)
335 if type(locs) == str:
336 locs = [locnames.index(locs), -1 if immovable else 0]
338 locs = [locnames.index(x) for x in locs]
340 sys.stderr.write("dungeon: unknown object location in %s\n" % locs)
342 treasure = "true" if attr.get("treasure") else "false"
343 obj_str += template.format(i, i_msg, locs[0], locs[1], treasure, longs_str, sounds_str, texts_str)
344 obj_str = obj_str[:-1] # trim trailing newline
347 def get_obituaries(obit):
355 query = make_c_string(o["query"])
356 yes = make_c_string(o["yes_response"])
357 obit_str += template.format(query, yes)
358 obit_str = obit_str[:-1] # trim trailing newline
361 def get_hints(hnt, arb):
373 item = member["hint"]
374 number = item["number"]
375 penalty = item["penalty"]
376 turns = item["turns"]
377 question = make_c_string(item["question"])
378 hint = make_c_string(item["hint"])
379 hnt_str += template.format(number, penalty, turns, question, hint)
380 hnt_str = hnt_str[:-1] # trim trailing newline
383 def get_condbits(locations):
385 for (name, loc) in locations:
386 conditions = loc["conditions"]
387 hints = loc.get("hints") or []
389 for flag in conditions:
391 flaglist.append(flag)
392 line = "|".join([("(1<<COND_%s)" % f) for f in flaglist])
393 trail = "|".join([("(1<<COND_H%s)" % f['name']) for f in hints])
396 if line.startswith("|"):
400 cnd_str += " " + line + ",\t// " + name + "\n"
403 def recompose(type_word, value):
404 "Compose the internal code for a vocabulary word from its YAML entry"
405 parts = ("motion", "action", "object", "special")
407 return value + 1000 * parts.index(type_word)
409 sys.stderr.write("dungeon: %s is not a known word\n" % word)
412 sys.stderr.write("%s is not a known word classifier\n" % attrs["type"])
415 def get_actspk(actspk):
417 for (i, word) in actspk.items():
418 res += " %s,\n" % word
421 def buildtravel(locs, objs, voc):
425 for entry in db["vocabulary"]:
426 if entry["type"] == "motion" and entry["value"] not in verbmap:
427 verbmap[entry["word"]] = entry["value"]
428 def dencode(action, name):
429 "Decode a destination number"
430 if action[0] == "goto":
432 return locnames.index(action[1])
434 sys.stderr.write("dungeon: unknown location %s in goto clause of %s\n" % (cond[1], name))
435 elif action[0] == "special":
436 return 300 + action[1]
437 elif action[0] == "speak":
439 return 500 + msgnames.index(action[1])
441 sys.stderr.write("dungeon: unknown location %s in carry clause of %s\n" % (cond[1], name))
445 def cencode(cond, name):
448 elif cond[0] == "pct":
450 elif cond[0] == "carry":
452 return 100 + objnames.index(cond[1])
454 sys.stderr.write("dungeon: unknown object name %s in carry clause of %s\n" % (cond[1], name))
456 elif cond[0] == "with":
458 return 200 + objnames.index(cond[1])
460 sys.stderr.write("dungeon: unknown object name %s in with clause of \n" % (cond[1], name))
462 elif cond[0] == "not":
463 # FIXME: Allow named as well as numbered states
465 return 300 + objnames.index(cond[1]) + 100 * cond[2]
467 sys.stderr.write("dungeon: unknown object name %s in not clause of %s\n" % (cond[1], name))
472 # Much more to be done here
473 for (i, (name, loc)) in enumerate(locs):
475 for rule in loc["travel"]:
477 dest = dencode(rule["action"], name) + 1000 * cencode(rule.get("cond"), name)
479 tt += [verbmap[e] for e in rule["verbs"]]
480 if not rule["verbs"]:
482 ltravel.append(tuple(tt))
483 return (tuple(ltravel), lkeys)
485 def get_motions(motions):
491 for motion in motions:
493 if contents["words"] == None:
494 mot_str += template.format("NULL")
496 c_words = [make_c_string(s) for s in contents["words"]]
497 words_str = "(const char* []) {" + ", ".join(c_words) + "}"
498 mot_str += template.format(words_str)
501 def get_actions(actions):
508 for action in actions:
511 if contents["words"] == None:
514 c_words = [make_c_string(s) for s in contents["words"]]
515 words_str = "(const char* []) {" + ", ".join(c_words) + "}"
517 if contents["message"] == None:
518 message = "NO_MESSAGE"
520 message = contents["message"]
522 act_str += template.format(words_str, message)
523 act_str = act_str[:-1] # trim trailing newline
526 if __name__ == "__main__":
527 with open(yaml_name, "r") as f:
530 locnames = [x[0] for x in db["locations"]]
531 msgnames = [el[0] for el in db["arbitrary_messages"]]
532 objnames = [el[0] for el in db["objects"]]
533 (travel, key) = buildtravel(db["locations"], db["objects"], db["vocabulary"])
534 # FIXME: pack the Section 3 representation into the runtime format.
536 c = c_template.format(
538 get_arbitrary_messages(db["arbitrary_messages"]),
539 get_class_messages(db["classes"]),
540 get_turn_thresholds(db["turn_thresholds"]),
541 get_locations(db["locations"]),
542 get_objects(db["objects"]),
543 get_obituaries(db["obituaries"]),
544 get_hints(db["hints"], db["arbitrary_messages"]),
545 get_condbits(db["locations"]),
546 get_actspk(db["actspk"]),
547 get_motions(db["motions"]),
548 get_actions(db["actions"]),
551 h = h_template.format(
552 len(db["locations"])-1,
553 len(db["objects"])-1,
555 len(db["classes"])-1,
556 len(db["obituaries"]),
557 len(db["turn_thresholds"]),
560 get_refs(db["arbitrary_messages"]),
561 get_refs(db["locations"]),
562 get_refs(db["objects"]),
563 get_refs(db["motions"]),
564 get_refs(db["actions"]),
568 with open(h_name, "w") as hf:
571 with open(c_name, "w") as cf: