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 motion_t motions[];
109 extern const action_t actions[];
111 #define NLOCATIONS {}
116 #define NTHRESHOLDS {}
120 enum arbitrary_messages_refs {{
124 enum locations_refs {{
140 /* State definitions */
143 #endif /* end NEWDB_H */
146 c_template = """/* Generated from adventure.yaml - do not hand-hack! */
151 const char* arbitrary_messages[] = {{
155 const class_t classes[] = {{
159 const turn_threshold_t turn_thresholds[] = {{
163 const location_t locations[] = {{
167 const object_t objects[] = {{
171 const obituary_t obituaries[] = {{
175 const hint_t hints[] = {{
179 long conditions[] = {{
183 const motion_t motions[] = {{
187 const action_t actions[] = {{
194 def make_c_string(string):
195 """Render a Python string into C string literal format."""
198 string = string.replace("\n", "\\n")
199 string = string.replace("\t", "\\t")
200 string = string.replace('"', '\\"')
201 string = string.replace("'", "\\'")
202 string = '"' + string + '"'
206 reflist = [x[0] for x in l]
209 ref_str += " {},\n".format(ref)
210 ref_str = ref_str[:-1] # trim trailing newline
213 def get_arbitrary_messages(arb):
218 arb_str += template.format(make_c_string(item[1]))
219 arb_str = arb_str[:-1] # trim trailing newline
222 def get_class_messages(cls):
230 threshold = item["threshold"]
231 message = make_c_string(item["message"])
232 cls_str += template.format(threshold, message)
233 cls_str = cls_str[:-1] # trim trailing newline
236 def get_turn_thresholds(trn):
245 threshold = item["threshold"]
246 point_loss = item["point_loss"]
247 message = make_c_string(item["message"])
248 trn_str += template.format(threshold, point_loss, message)
249 trn_str = trn_str[:-1] # trim trailing newline
252 def get_locations(loc):
253 template = """ {{ // {}
263 for (i, item) in enumerate(loc):
264 short_d = make_c_string(item[1]["description"]["short"])
265 long_d = make_c_string(item[1]["description"]["long"])
266 sound = item[1].get("sound", "SILENT")
267 loud = "true" if item[1].get("loud") else "false"
268 loc_str += template.format(i, short_d, long_d, sound, loud)
269 loc_str = loc_str[:-1] # trim trailing newline
272 def get_objects(obj):
273 template = """ {{ // {}
278 .longs = (const char* []) {{
281 .sounds = (const char* []) {{
284 .texts = (const char* []) {{
290 for (i, item) in enumerate(obj):
292 i_msg = make_c_string(attr["inventory"])
294 if attr["longs"] == None:
295 longs_str = " " * 12 + "NULL,"
298 for l_msg in attr["longs"]:
299 if not isinstance(l_msg, str):
302 longs_str += " " * 12 + make_c_string(l_msg) + ",\n"
303 longs_str = longs_str[:-1] # trim trailing newline
306 statedefines += "/* States for %s */\n" % item[0]
307 for (i, (label, message)) in enumerate(labels):
308 if len(message) >= 45:
309 message = message[:45] + "..."
310 statedefines += "#define %s\t%d /* %s */\n" % (label, i, message)
313 if attr.get("sounds") == None:
314 sounds_str = " " * 12 + "NULL,"
316 for l_msg in attr["sounds"]:
317 sounds_str += " " * 12 + make_c_string(l_msg) + ",\n"
318 sounds_str = sounds_str[:-1] # trim trailing newline
320 if attr.get("texts") == None:
321 texts_str = " " * 12 + "NULL,"
323 for l_msg in attr["texts"]:
324 texts_str += " " * 12 + make_c_string(l_msg) + ",\n"
325 texts_str = texts_str[:-1] # trim trailing newline
326 locs = attr.get("locations", ["LOC_NOWHERE", "LOC_NOWHERE"])
327 immovable = attr.get("immovable", False)
329 if type(locs) == str:
330 locs = [locnames.index(locs), -1 if immovable else 0]
332 locs = [locnames.index(x) for x in locs]
334 sys.stderr.write("dungeon: unknown object location in %s\n" % locs)
336 treasure = "true" if attr.get("treasure") else "false"
337 obj_str += template.format(i, i_msg, locs[0], locs[1], treasure, longs_str, sounds_str, texts_str)
338 obj_str = obj_str[:-1] # trim trailing newline
341 def get_obituaries(obit):
349 query = make_c_string(o["query"])
350 yes = make_c_string(o["yes_response"])
351 obit_str += template.format(query, yes)
352 obit_str = obit_str[:-1] # trim trailing newline
355 def get_hints(hnt, arb):
367 item = member["hint"]
368 number = item["number"]
369 penalty = item["penalty"]
370 turns = item["turns"]
371 question = make_c_string(item["question"])
372 hint = make_c_string(item["hint"])
373 hnt_str += template.format(number, penalty, turns, question, hint)
374 hnt_str = hnt_str[:-1] # trim trailing newline
377 def get_condbits(locations):
379 for (name, loc) in locations:
380 conditions = loc["conditions"]
381 hints = loc.get("hints") or []
383 for flag in conditions:
385 flaglist.append(flag)
386 line = "|".join([("(1<<COND_%s)" % f) for f in flaglist])
387 trail = "|".join([("(1<<COND_H%s)" % f['name']) for f in hints])
390 if line.startswith("|"):
394 cnd_str += " " + line + ",\t// " + name + "\n"
397 def recompose(type_word, value):
398 "Compose the internal code for a vocabulary word from its YAML entry"
399 parts = ("motion", "action", "object", "special")
401 return value + 1000 * parts.index(type_word)
403 sys.stderr.write("dungeon: %s is not a known word\n" % word)
406 sys.stderr.write("%s is not a known word classifier\n" % attrs["type"])
409 def buildtravel(locs, objs, voc):
413 for entry in db["vocabulary"]:
414 if entry["type"] == "motion" and entry["value"] not in verbmap:
415 verbmap[entry["word"]] = entry["value"]
416 def dencode(action, name):
417 "Decode a destination number"
418 if action[0] == "goto":
420 return locnames.index(action[1])
422 sys.stderr.write("dungeon: unknown location %s in goto clause of %s\n" % (cond[1], name))
423 elif action[0] == "special":
424 return 300 + action[1]
425 elif action[0] == "speak":
427 return 500 + msgnames.index(action[1])
429 sys.stderr.write("dungeon: unknown location %s in carry clause of %s\n" % (cond[1], name))
433 def cencode(cond, name):
436 elif cond[0] == "pct":
438 elif cond[0] == "carry":
440 return 100 + objnames.index(cond[1])
442 sys.stderr.write("dungeon: unknown object name %s in carry clause of %s\n" % (cond[1], name))
444 elif cond[0] == "with":
446 return 200 + objnames.index(cond[1])
448 sys.stderr.write("dungeon: unknown object name %s in with clause of \n" % (cond[1], name))
450 elif cond[0] == "not":
451 # FIXME: Allow named as well as numbered states
453 return 300 + objnames.index(cond[1]) + 100 * cond[2]
455 sys.stderr.write("dungeon: unknown object name %s in not clause of %s\n" % (cond[1], name))
460 # Much more to be done here
461 for (i, (name, loc)) in enumerate(locs):
463 for rule in loc["travel"]:
465 dest = dencode(rule["action"], name) + 1000 * cencode(rule.get("cond"), name)
467 tt += [verbmap[e] for e in rule["verbs"]]
468 if not rule["verbs"]:
470 ltravel.append(tuple(tt))
471 return (tuple(ltravel), lkeys)
473 def get_motions(motions):
479 for motion in motions:
481 if contents["words"] == None:
482 mot_str += template.format("NULL")
484 c_words = [make_c_string(s) for s in contents["words"]]
485 words_str = "(const char* []) {" + ", ".join(c_words) + "}"
486 mot_str += template.format(words_str)
489 def get_actions(actions):
496 for action in actions:
499 if contents["words"] == None:
502 c_words = [make_c_string(s) for s in contents["words"]]
503 words_str = "(const char* []) {" + ", ".join(c_words) + "}"
505 if contents["message"] == None:
506 message = "NO_MESSAGE"
508 message = contents["message"]
510 act_str += template.format(words_str, message)
511 act_str = act_str[:-1] # trim trailing newline
514 if __name__ == "__main__":
515 with open(yaml_name, "r") as f:
518 locnames = [x[0] for x in db["locations"]]
519 msgnames = [el[0] for el in db["arbitrary_messages"]]
520 objnames = [el[0] for el in db["objects"]]
521 (travel, key) = buildtravel(db["locations"], db["objects"], db["vocabulary"])
522 # FIXME: pack the Section 3 representation into the runtime format.
524 c = c_template.format(
526 get_arbitrary_messages(db["arbitrary_messages"]),
527 get_class_messages(db["classes"]),
528 get_turn_thresholds(db["turn_thresholds"]),
529 get_locations(db["locations"]),
530 get_objects(db["objects"]),
531 get_obituaries(db["obituaries"]),
532 get_hints(db["hints"], db["arbitrary_messages"]),
533 get_condbits(db["locations"]),
534 get_motions(db["motions"]),
535 get_actions(db["actions"]),
538 h = h_template.format(
539 len(db["locations"])-1,
540 len(db["objects"])-1,
542 len(db["classes"])-1,
543 len(db["obituaries"]),
544 len(db["turn_thresholds"]),
547 get_refs(db["arbitrary_messages"]),
548 get_refs(db["locations"]),
549 get_refs(db["objects"]),
550 get_refs(db["motions"]),
551 get_refs(db["actions"]),
555 with open(h_name, "w") as hf:
558 with open(c_name, "w") as cf: