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;
97 extern const location_t locations[];
98 extern const object_t objects[];
99 extern const char* arbitrary_messages[];
100 extern const class_t classes[];
101 extern const turn_threshold_t turn_thresholds[];
102 extern const obituary_t obituaries[];
103 extern const hint_t hints[];
104 extern long conditions[];
105 extern const vocabulary_t vocabulary[];
106 extern const long actspk[];
108 #define NLOCATIONS {}
113 #define NTHRESHOLDS {}
118 enum arbitrary_messages_refs {{
122 enum locations_refs {{
130 /* State definitions */
133 #endif /* end NEWDB_H */
136 c_template = """/* Generated from adventure.yaml - do not hand-hack! */
141 const char* arbitrary_messages[] = {{
145 const class_t classes[] = {{
149 const turn_threshold_t turn_thresholds[] = {{
153 const location_t locations[] = {{
157 const object_t objects[] = {{
161 const obituary_t obituaries[] = {{
165 const hint_t hints[] = {{
169 long conditions[] = {{
173 const vocabulary_t vocabulary[] = {{
177 const long actspk[] = {{
185 def make_c_string(string):
186 """Render a Python string into C string literal format."""
189 string = string.replace("\n", "\\n")
190 string = string.replace("\t", "\\t")
191 string = string.replace('"', '\\"')
192 string = string.replace("'", "\\'")
193 string = '"' + string + '"'
197 reflist = [x[0] for x in l]
200 ref_str += " {},\n".format(ref)
201 ref_str = ref_str[:-1] # trim trailing newline
204 def get_arbitrary_messages(arb):
209 arb_str += template.format(make_c_string(item[1]))
210 arb_str = arb_str[:-1] # trim trailing newline
213 def get_class_messages(cls):
221 threshold = item["threshold"]
222 message = make_c_string(item["message"])
223 cls_str += template.format(threshold, message)
224 cls_str = cls_str[:-1] # trim trailing newline
227 def get_turn_thresholds(trn):
236 threshold = item["threshold"]
237 point_loss = item["point_loss"]
238 message = make_c_string(item["message"])
239 trn_str += template.format(threshold, point_loss, message)
240 trn_str = trn_str[:-1] # trim trailing newline
243 def get_locations(loc):
244 template = """ {{ // {}
254 for (i, item) in enumerate(loc):
255 short_d = make_c_string(item[1]["description"]["short"])
256 long_d = make_c_string(item[1]["description"]["long"])
257 sound = item[1].get("sound", "SILENT")
258 loud = "true" if item[1].get("loud") else "false"
259 loc_str += template.format(i, short_d, long_d, sound, loud)
260 loc_str = loc_str[:-1] # trim trailing newline
263 def get_objects(obj):
264 template = """ {{ // {}
269 .longs = (const char* []) {{
272 .sounds = (const char* []) {{
275 .texts = (const char* []) {{
281 for (i, item) in enumerate(obj):
283 i_msg = make_c_string(attr["inventory"])
285 if attr["longs"] == None:
286 longs_str = " " * 12 + "NULL,"
289 for l_msg in attr["longs"]:
290 if not isinstance(l_msg, str):
293 longs_str += " " * 12 + make_c_string(l_msg) + ",\n"
294 longs_str = longs_str[:-1] # trim trailing newline
297 statedefines += "/* States for %s */\n" % item[0]
298 for (i, (label, message)) in enumerate(labels):
299 if len(message) >= 45:
300 message = message[:45] + "..."
301 statedefines += "#define %s\t%d /* %s */\n" % (label, i, message)
304 if attr.get("sounds") == None:
305 sounds_str = " " * 12 + "NULL,"
307 for l_msg in attr["sounds"]:
308 sounds_str += " " * 12 + make_c_string(l_msg) + ",\n"
309 sounds_str = sounds_str[:-1] # trim trailing newline
311 if attr.get("texts") == None:
312 texts_str = " " * 12 + "NULL,"
314 for l_msg in attr["texts"]:
315 texts_str += " " * 12 + make_c_string(l_msg) + ",\n"
316 texts_str = texts_str[:-1] # trim trailing newline
317 locs = attr.get("locations", ["LOC_NOWHERE", "LOC_NOWHERE"])
318 immovable = attr.get("immovable", False)
320 if type(locs) == str:
321 locs = [locnames.index(locs), -1 if immovable else 0]
323 locs = [locnames.index(x) for x in locs]
325 sys.stderr.write("dungeon: unknown object location in %s\n" % locs)
327 treasure = "true" if attr.get("treasure") else "false"
328 obj_str += template.format(i, i_msg, locs[0], locs[1], treasure, longs_str, sounds_str, texts_str)
329 obj_str = obj_str[:-1] # trim trailing newline
332 def get_obituaries(obit):
340 query = make_c_string(o["query"])
341 yes = make_c_string(o["yes_response"])
342 obit_str += template.format(query, yes)
343 obit_str = obit_str[:-1] # trim trailing newline
346 def get_hints(hnt, arb):
358 item = member["hint"]
359 number = item["number"]
360 penalty = item["penalty"]
361 turns = item["turns"]
362 question = make_c_string(item["question"])
363 hint = make_c_string(item["hint"])
364 hnt_str += template.format(number, penalty, turns, question, hint)
365 hnt_str = hnt_str[:-1] # trim trailing newline
368 def get_condbits(locations):
370 for (name, loc) in locations:
371 conditions = loc["conditions"]
372 hints = loc.get("hints") or []
374 for flag in conditions:
376 flaglist.append(flag)
377 line = "|".join([("(1<<COND_%s)" % f) for f in flaglist])
378 trail = "|".join([("(1<<COND_H%s)" % f['name']) for f in hints])
381 if line.startswith("|"):
385 cnd_str += " " + line + ",\t// " + name + "\n"
388 def recompose(type_word, value):
389 "Compose the internal code for a vocabulary word from its YAML entry"
390 parts = ("motion", "action", "object", "special")
392 return value + 1000 * parts.index(type_word)
394 sys.stderr.write("dungeon: %s is not a known word\n" % word)
397 sys.stderr.write("%s is not a known word classifier\n" % attrs["type"])
400 def get_vocabulary(vocabulary):
408 for vocab in vocabulary:
409 word = make_c_string(vocab["word"])
410 type_code = recompose(vocab["type"], vocab["value"])
411 value = vocab["value"]
412 voc_str += template.format(word, type_code, value)
413 voc_str = voc_str[:-1] # trim trailing newline
416 def get_actspk(actspk):
418 for (i, word) in actspk.items():
419 res += " %s,\n" % word
422 def buildtravel(locs, objs, voc):
426 for entry in db["vocabulary"]:
427 if entry["type"] == "motion" and entry["value"] not in verbmap:
428 verbmap[entry["word"]] = entry["value"]
429 def dencode(action, name):
430 "Decode a destination number"
431 if action[0] == "goto":
433 return locnames.index(action[1])
435 sys.stderr.write("dungeon: unknown location %s in goto clause of %s\n" % (cond[1], name))
436 elif action[0] == "special":
437 return 300 + action[1]
438 elif action[0] == "speak":
440 return 500 + msgnames.index(action[1])
442 sys.stderr.write("dungeon: unknown location %s in carry clause of %s\n" % (cond[1], name))
446 def cencode(cond, name):
449 elif cond[0] == "pct":
451 elif cond[0] == "carry":
453 return 100 + objnames.index(cond[1])
455 sys.stderr.write("dungeon: unknown object name %s in carry clause of %s\n" % (cond[1], name))
457 elif cond[0] == "with":
459 return 200 + objnames.index(cond[1])
461 sys.stderr.write("dungeon: unknown object name %s in with clause of \n" % (cond[1], name))
463 elif cond[0] == "not":
464 # FIXME: Allow named as well as numbered states
466 return 300 + objnames.index(cond[1]) + 100 * cond[2]
468 sys.stderr.write("dungeon: unknown object name %s in not clause of %s\n" % (cond[1], name))
473 # Much more to be done here
474 for (i, (name, loc)) in enumerate(locs):
476 for rule in loc["travel"]:
478 dest = dencode(rule["action"], name) + 1000 * cencode(rule.get("cond"), name)
480 tt += [verbmap[e] for e in rule["verbs"]]
481 if not rule["verbs"]:
484 return (ltravel, lkeys)
486 if __name__ == "__main__":
487 with open(yaml_name, "r") as f:
490 locnames = [x[0] for x in db["locations"]]
491 msgnames = [el[0] for el in db["arbitrary_messages"]]
492 objnames = [el[0] for el in db["objects"]]
493 (travel, key) = buildtravel(db["locations"], db["objects"], db["vocabulary"])
495 c = c_template.format(
497 get_arbitrary_messages(db["arbitrary_messages"]),
498 get_class_messages(db["classes"]),
499 get_turn_thresholds(db["turn_thresholds"]),
500 get_locations(db["locations"]),
501 get_objects(db["objects"]),
502 get_obituaries(db["obituaries"]),
503 get_hints(db["hints"], db["arbitrary_messages"]),
504 get_condbits(db["locations"]),
505 get_vocabulary(db["vocabulary"]),
506 get_actspk(db["actspk"]),
509 h = h_template.format(
510 len(db["locations"])-1,
511 len(db["objects"])-1,
513 len(db["classes"])-1,
514 len(db["obituaries"]),
515 len(db["turn_thresholds"]),
517 len(db["vocabulary"]),
519 get_refs(db["arbitrary_messages"]),
520 get_refs(db["locations"]),
521 get_refs(db["objects"]),
525 with open(h_name, "w") as hf:
528 with open(c_name, "w") as cf: