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;
95 extern const location_t locations[];
96 extern const object_t objects[];
97 extern const char* arbitrary_messages[];
98 extern const class_t classes[];
99 extern const turn_threshold_t turn_thresholds[];
100 extern const obituary_t obituaries[];
101 extern const hint_t hints[];
102 extern long conditions[];
103 extern const long actspk[];
104 extern const motion_t motions[];
106 #define NLOCATIONS {}
111 #define NTHRESHOLDS {}
115 enum arbitrary_messages_refs {{
119 enum locations_refs {{
131 /* State definitions */
134 #endif /* end NEWDB_H */
137 c_template = """/* Generated from adventure.yaml - do not hand-hack! */
142 const char* arbitrary_messages[] = {{
146 const class_t classes[] = {{
150 const turn_threshold_t turn_thresholds[] = {{
154 const location_t locations[] = {{
158 const object_t objects[] = {{
162 const obituary_t obituaries[] = {{
166 const hint_t hints[] = {{
170 long conditions[] = {{
174 const long actspk[] = {{
179 const motion_t motions[] = {{
186 def make_c_string(string):
187 """Render a Python string into C string literal format."""
190 string = string.replace("\n", "\\n")
191 string = string.replace("\t", "\\t")
192 string = string.replace('"', '\\"')
193 string = string.replace("'", "\\'")
194 string = '"' + string + '"'
198 reflist = [x[0] for x in l]
201 ref_str += " {},\n".format(ref)
202 ref_str = ref_str[:-1] # trim trailing newline
205 def get_arbitrary_messages(arb):
210 arb_str += template.format(make_c_string(item[1]))
211 arb_str = arb_str[:-1] # trim trailing newline
214 def get_class_messages(cls):
222 threshold = item["threshold"]
223 message = make_c_string(item["message"])
224 cls_str += template.format(threshold, message)
225 cls_str = cls_str[:-1] # trim trailing newline
228 def get_turn_thresholds(trn):
237 threshold = item["threshold"]
238 point_loss = item["point_loss"]
239 message = make_c_string(item["message"])
240 trn_str += template.format(threshold, point_loss, message)
241 trn_str = trn_str[:-1] # trim trailing newline
244 def get_locations(loc):
245 template = """ {{ // {}
255 for (i, item) in enumerate(loc):
256 short_d = make_c_string(item[1]["description"]["short"])
257 long_d = make_c_string(item[1]["description"]["long"])
258 sound = item[1].get("sound", "SILENT")
259 loud = "true" if item[1].get("loud") else "false"
260 loc_str += template.format(i, short_d, long_d, sound, loud)
261 loc_str = loc_str[:-1] # trim trailing newline
264 def get_objects(obj):
265 template = """ {{ // {}
270 .longs = (const char* []) {{
273 .sounds = (const char* []) {{
276 .texts = (const char* []) {{
282 for (i, item) in enumerate(obj):
284 i_msg = make_c_string(attr["inventory"])
286 if attr["longs"] == None:
287 longs_str = " " * 12 + "NULL,"
290 for l_msg in attr["longs"]:
291 if not isinstance(l_msg, str):
294 longs_str += " " * 12 + make_c_string(l_msg) + ",\n"
295 longs_str = longs_str[:-1] # trim trailing newline
298 statedefines += "/* States for %s */\n" % item[0]
299 for (i, (label, message)) in enumerate(labels):
300 if len(message) >= 45:
301 message = message[:45] + "..."
302 statedefines += "#define %s\t%d /* %s */\n" % (label, i, message)
305 if attr.get("sounds") == None:
306 sounds_str = " " * 12 + "NULL,"
308 for l_msg in attr["sounds"]:
309 sounds_str += " " * 12 + make_c_string(l_msg) + ",\n"
310 sounds_str = sounds_str[:-1] # trim trailing newline
312 if attr.get("texts") == None:
313 texts_str = " " * 12 + "NULL,"
315 for l_msg in attr["texts"]:
316 texts_str += " " * 12 + make_c_string(l_msg) + ",\n"
317 texts_str = texts_str[:-1] # trim trailing newline
318 locs = attr.get("locations", ["LOC_NOWHERE", "LOC_NOWHERE"])
319 immovable = attr.get("immovable", False)
321 if type(locs) == str:
322 locs = [locnames.index(locs), -1 if immovable else 0]
324 locs = [locnames.index(x) for x in locs]
326 sys.stderr.write("dungeon: unknown object location in %s\n" % locs)
328 treasure = "true" if attr.get("treasure") else "false"
329 obj_str += template.format(i, i_msg, locs[0], locs[1], treasure, longs_str, sounds_str, texts_str)
330 obj_str = obj_str[:-1] # trim trailing newline
333 def get_obituaries(obit):
341 query = make_c_string(o["query"])
342 yes = make_c_string(o["yes_response"])
343 obit_str += template.format(query, yes)
344 obit_str = obit_str[:-1] # trim trailing newline
347 def get_hints(hnt, arb):
359 item = member["hint"]
360 number = item["number"]
361 penalty = item["penalty"]
362 turns = item["turns"]
363 question = make_c_string(item["question"])
364 hint = make_c_string(item["hint"])
365 hnt_str += template.format(number, penalty, turns, question, hint)
366 hnt_str = hnt_str[:-1] # trim trailing newline
369 def get_condbits(locations):
371 for (name, loc) in locations:
372 conditions = loc["conditions"]
373 hints = loc.get("hints") or []
375 for flag in conditions:
377 flaglist.append(flag)
378 line = "|".join([("(1<<COND_%s)" % f) for f in flaglist])
379 trail = "|".join([("(1<<COND_H%s)" % f['name']) for f in hints])
382 if line.startswith("|"):
386 cnd_str += " " + line + ",\t// " + name + "\n"
389 def recompose(type_word, value):
390 "Compose the internal code for a vocabulary word from its YAML entry"
391 parts = ("motion", "action", "object", "special")
393 return value + 1000 * parts.index(type_word)
395 sys.stderr.write("dungeon: %s is not a known word\n" % word)
398 sys.stderr.write("%s is not a known word classifier\n" % attrs["type"])
401 def get_actspk(actspk):
403 for (i, word) in actspk.items():
404 res += " %s,\n" % word
407 def buildtravel(locs, objs, voc):
411 for entry in db["vocabulary"]:
412 if entry["type"] == "motion" and entry["value"] not in verbmap:
413 verbmap[entry["word"]] = entry["value"]
414 def dencode(action, name):
415 "Decode a destination number"
416 if action[0] == "goto":
418 return locnames.index(action[1])
420 sys.stderr.write("dungeon: unknown location %s in goto clause of %s\n" % (cond[1], name))
421 elif action[0] == "special":
422 return 300 + action[1]
423 elif action[0] == "speak":
425 return 500 + msgnames.index(action[1])
427 sys.stderr.write("dungeon: unknown location %s in carry clause of %s\n" % (cond[1], name))
431 def cencode(cond, name):
434 elif cond[0] == "pct":
436 elif cond[0] == "carry":
438 return 100 + objnames.index(cond[1])
440 sys.stderr.write("dungeon: unknown object name %s in carry clause of %s\n" % (cond[1], name))
442 elif cond[0] == "with":
444 return 200 + objnames.index(cond[1])
446 sys.stderr.write("dungeon: unknown object name %s in with clause of \n" % (cond[1], name))
448 elif cond[0] == "not":
449 # FIXME: Allow named as well as numbered states
451 return 300 + objnames.index(cond[1]) + 100 * cond[2]
453 sys.stderr.write("dungeon: unknown object name %s in not clause of %s\n" % (cond[1], name))
458 # Much more to be done here
459 for (i, (name, loc)) in enumerate(locs):
461 for rule in loc["travel"]:
463 dest = dencode(rule["action"], name) + 1000 * cencode(rule.get("cond"), name)
465 tt += [verbmap[e] for e in rule["verbs"]]
466 if not rule["verbs"]:
469 return (ltravel, lkeys)
471 def get_motions(motions):
477 for motion in motions:
479 if contents["words"] == None:
480 mot_str += template.format("NULL")
482 c_words = [make_c_string(s) for s in contents["words"]]
483 words_str = "(const char* []) {" + ", ".join(c_words) + "}"
484 mot_str += template.format(words_str)
487 if __name__ == "__main__":
488 with open(yaml_name, "r") as f:
491 locnames = [x[0] for x in db["locations"]]
492 msgnames = [el[0] for el in db["arbitrary_messages"]]
493 objnames = [el[0] for el in db["objects"]]
494 (travel, key) = buildtravel(db["locations"], db["objects"], db["vocabulary"])
496 c = c_template.format(
498 get_arbitrary_messages(db["arbitrary_messages"]),
499 get_class_messages(db["classes"]),
500 get_turn_thresholds(db["turn_thresholds"]),
501 get_locations(db["locations"]),
502 get_objects(db["objects"]),
503 get_obituaries(db["obituaries"]),
504 get_hints(db["hints"], db["arbitrary_messages"]),
505 get_condbits(db["locations"]),
506 get_actspk(db["actspk"]),
507 get_motions(db["motions"]),
510 h = h_template.format(
511 len(db["locations"])-1,
512 len(db["objects"])-1,
514 len(db["classes"])-1,
515 len(db["obituaries"]),
516 len(db["turn_thresholds"]),
519 get_refs(db["arbitrary_messages"]),
520 get_refs(db["locations"]),
521 get_refs(db["objects"]),
522 get_refs(db["motions"]),
526 with open(h_name, "w") as hf:
529 with open(c_name, "w") as cf: