Improve documentation if the *most* obscure span of code.
[open-adventure.git] / newdungeon.py
1 #!/usr/bin/python3
2
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
5 # for C code.
6 #
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
9 # playermove().  This program first compiles the YAML to a form
10 # identical to the data in section 3 of the old adventure.text file,
11 # then a second stage unpacks that data into the travel array.
12 #
13 # Here are the rules of the intermediate form:
14 #
15 # Each row of data contains a location number (X), a second
16 # location number (Y), and a list of motion numbers (see section 4).
17 # each motion represents a verb which will go to Y if currently at X.
18 # Y, in turn, is interpreted as follows.  Let M=Y/1000, N=Y mod 1000.
19 #               If N<=300       it is the location to go to.
20 #               If 300<N<=500   N-300 is used in a computed goto to
21 #                                       a section of special code.
22 #               If N>500        message N-500 from section 6 is printed,
23 #                                       and he stays wherever he is.
24 # Meanwhile, M specifies the conditions on the motion.
25 #               If M=0          it's unconditional.
26 #               If 0<M<100      it is done with M% probability.
27 #               If M=100        unconditional, but forbidden to dwarves.
28 #               If 100<M<=200   he must be carrying object M-100.
29 #               If 200<M<=300   must be carrying or in same room as M-200.
30 #               If 300<M<=400   game.prop(M % 100) must *not* be 0.
31 #               If 400<M<=500   game.prop(M % 100) must *not* be 1.
32 #               If 500<M<=600   game.prop(M % 100) must *not* be 2, etc.
33 # If the condition (if any) is not met, then the next *different*
34 # "destination" value is used (unless it fails to meet *its* conditions,
35 # in which case the next is found, etc.).  Typically, the next dest will
36 # be for one of the same verbs, so that its only use is as the alternate
37 # destination for those verbs.  For instance:
38 #               15      110022  29      31      34      35      23      43
39 #               15      14      29
40 # This says that, from loc 15, any of the verbs 29, 31, etc., will take
41 # him to 22 if he's carrying object 10, and otherwise will go to 14.
42 #               11      303008  49
43 #               11      9       50
44 # This says that, from 11, 49 takes him to 8 unless game.prop(3)=0, in which
45 # case he goes to 9.  Verb 50 takes him to 9 regardless of game.prop(3).
46
47 import sys, yaml
48
49 yaml_name = "adventure.yaml"
50 h_name = "newdb.h"
51 c_name = "newdb.c"
52
53 statedefines = ""
54
55 h_template = """/* Generated from adventure.yaml - do not hand-hack! */
56 #ifndef NEWDB_H
57 #define NEWDB_H
58
59 #include <stdio.h>
60 #include <stdbool.h>
61
62 #define SILENT  -1      /* no sound */
63
64 /* Symbols for cond bits */
65 #define COND_LIT        0       /* Light */
66 #define COND_OILY       1       /* If bit 2 is on: on for oil, off for water */
67 #define COND_FLUID      2       /* Liquid asset, see bit 1 */
68 #define COND_NOARRR     3       /* Pirate doesn't go here unless following */
69 #define COND_NOBACK     4       /* Cannot use "back" to move away */
70 #define COND_ABOVE      5
71 #define COND_DEEP       6       /* Deep - e.g where dwarves are active */
72 #define COND_FOREST     7       /* In the forest */
73 #define COND_FORCED     8       /* Only one way in or out of here */
74 /* Bits past 10 indicate areas of interest to "hint" routines */
75 #define COND_HBASE      10      /* Base for location hint bits */
76 #define COND_HCAVE      11      /* Trying to get into cave */
77 #define COND_HBIRD      12      /* Trying to catch bird */
78 #define COND_HSNAKE     13      /* Trying to deal with snake */
79 #define COND_HMAZE      14      /* Lost in maze */
80 #define COND_HDARK      15      /* Pondering dark room */
81 #define COND_HWITT      16      /* At Witt's End */
82 #define COND_HCLIFF     17      /* Cliff with urn */
83 #define COND_HWOODS     18      /* Lost in forest */
84 #define COND_HOGRE      19      /* Trying to deal with ogre */
85 #define COND_HJADE      20      /* Found all treasures except jade */
86
87 typedef struct {{
88   const char* inventory;
89   int plac, fixd;
90   bool is_treasure;
91   const char** descriptions;
92   const char** sounds;
93   const char** texts;
94   const char** changes;
95 }} object_t;
96
97 typedef struct {{
98   const char* small;
99   const char* big;
100 }} descriptions_t;
101
102 typedef struct {{
103   descriptions_t description;
104   const long sound;
105   const bool loud;
106 }} location_t;
107
108 typedef struct {{
109   const char* query;
110   const char* yes_response;
111 }} obituary_t;
112
113 typedef struct {{
114   const int threshold;
115   const int point_loss;
116   const char* message;
117 }} turn_threshold_t;
118
119 typedef struct {{
120   const int threshold;
121   const char* message;
122 }} class_t;
123
124 typedef struct {{
125   const int number;
126   const int turns;
127   const int penalty;
128   const char* question;
129   const char* hint;
130 }} hint_t;
131
132 typedef struct {{
133   const char** words;
134 }} motion_t;
135
136 typedef struct {{
137   const char** words;
138   const long message;
139 }} action_t;
140
141 typedef struct {{
142   const long motion;
143   const long dest;
144   const bool stop;
145 }} travelop_t;
146
147 /* Abstract out the encoding of words in the travel array.  Gives us
148  * some hope of getting to a less cryptic representation than we
149  * inherited from FORTRAN, someday. To understand these, read the
150  * encoding description for travel.
151  */
152 #define T_DESTINATION(entry)    MOD((entry).dest, 1000)
153 #define T_CONDITION(entry)      ((entry).dest / 1000)
154 #define T_NODWARVES(entry)      (T_CONDITION(entry) == 100)
155 #define T_HIGH(entry)           ((entry).dest)
156 #define T_TERMINATE(entry)      ((entry).motion == 1)
157 #define L_SPEAK(loc)            ((loc) - 500)
158
159 extern const location_t locations[];
160 extern const object_t objects[];
161 extern const char* arbitrary_messages[];
162 extern const class_t classes[];
163 extern const turn_threshold_t turn_thresholds[];
164 extern const obituary_t obituaries[];
165 extern const hint_t hints[];
166 extern long conditions[];
167 extern const motion_t motions[];
168 extern const action_t actions[];
169 extern const travelop_t travel[];
170 extern const long tkey[];
171
172 #define NLOCATIONS      {}
173 #define NOBJECTS        {}
174 #define NHINTS          {}
175 #define NCLASSES        {}
176 #define NDEATHS         {}
177 #define NTHRESHOLDS     {}
178 #define NACTIONS        {}
179 #define NTRAVEL         {}
180 #define NKEYS           {}
181
182 enum arbitrary_messages_refs {{
183 {}
184 }};
185
186 enum locations_refs {{
187 {}
188 }};
189
190 enum object_refs {{
191 {}
192 }};
193
194 enum motion_refs {{
195 {}
196 }};
197
198 enum action_refs {{
199 {}
200 }};
201
202 /* State definitions */
203
204 {}
205 #endif /* end NEWDB_H */
206 """
207
208 c_template = """/* Generated from adventure.yaml - do not hand-hack! */
209
210 #include "common.h"
211 #include "{}"
212
213 const char* arbitrary_messages[] = {{
214 {}
215 }};
216
217 const class_t classes[] = {{
218 {}
219 }};
220
221 const turn_threshold_t turn_thresholds[] = {{
222 {}
223 }};
224
225 const location_t locations[] = {{
226 {}
227 }};
228
229 const object_t objects[] = {{
230 {}
231 }};
232
233 const obituary_t obituaries[] = {{
234 {}
235 }};
236
237 const hint_t hints[] = {{
238 {}
239 }};
240
241 long conditions[] = {{
242 {}
243 }};
244
245 const motion_t motions[] = {{
246 {}
247 }};
248
249 const action_t actions[] = {{
250 {}
251 }};
252
253 {}
254
255 const travelop_t travel[] = {{
256 {}
257 }};
258
259 /* end */
260 """
261
262 def make_c_string(string):
263     """Render a Python string into C string literal format."""
264     if string == None:
265         return "NULL"
266     string = string.replace("\n", "\\n")
267     string = string.replace("\t", "\\t")
268     string = string.replace('"', '\\"')
269     string = string.replace("'", "\\'")
270     string = '"' + string + '"'
271     return string
272
273 def get_refs(l):
274     reflist = [x[0] for x in l]
275     ref_str = ""
276     for ref in reflist:
277         ref_str += "    {},\n".format(ref)
278     ref_str = ref_str[:-1] # trim trailing newline
279     return ref_str
280
281 def get_arbitrary_messages(arb):
282     template = """    {},
283 """
284     arb_str = ""
285     for item in arb:
286         arb_str += template.format(make_c_string(item[1]))
287     arb_str = arb_str[:-1] # trim trailing newline
288     return arb_str
289
290 def get_class_messages(cls):
291     template = """    {{
292         .threshold = {},
293         .message = {},
294     }},
295 """
296     cls_str = ""
297     for item in cls:
298         threshold = item["threshold"]
299         message = make_c_string(item["message"])
300         cls_str += template.format(threshold, message)
301     cls_str = cls_str[:-1] # trim trailing newline
302     return cls_str
303
304 def get_turn_thresholds(trn):
305     template = """    {{
306         .threshold = {},
307         .point_loss = {},
308         .message = {},
309     }},
310 """
311     trn_str = ""
312     for item in trn:
313         threshold = item["threshold"]
314         point_loss = item["point_loss"]
315         message = make_c_string(item["message"])
316         trn_str += template.format(threshold, point_loss, message)
317     trn_str = trn_str[:-1] # trim trailing newline
318     return trn_str
319
320 def get_locations(loc):
321     template = """    {{ // {}
322         .description = {{
323             .small = {},
324             .big = {},
325         }},
326         .sound = {},
327         .loud = {},
328     }},
329 """
330     loc_str = ""
331     for (i, item) in enumerate(loc):
332         short_d = make_c_string(item[1]["description"]["short"])
333         long_d = make_c_string(item[1]["description"]["long"])
334         sound = item[1].get("sound", "SILENT")
335         loud = "true" if item[1].get("loud") else "false"
336         loc_str += template.format(i, short_d, long_d, sound, loud)
337     loc_str = loc_str[:-1] # trim trailing newline
338     return loc_str
339
340 def get_objects(obj):
341     template = """    {{ // {}
342         .inventory = {},
343         .plac = {},
344         .fixd = {},
345         .is_treasure = {},
346         .descriptions = (const char* []) {{
347 {}
348         }},
349         .sounds = (const char* []) {{
350 {}
351         }},
352         .texts = (const char* []) {{
353 {}
354         }},
355         .changes = (const char* []) {{
356 {}
357         }},
358     }},
359 """
360     obj_str = ""
361     for (i, item) in enumerate(obj):
362         attr = item[1]
363         i_msg = make_c_string(attr["inventory"])
364         descriptions_str = ""
365         if attr["descriptions"] == None:
366             descriptions_str = " " * 12 + "NULL,"
367         else:
368             labels = []
369             for l_msg in attr["descriptions"]:
370                 if not isinstance(l_msg, str):
371                     labels.append(l_msg)
372                     l_msg = l_msg[1]
373                 descriptions_str += " " * 12 + make_c_string(l_msg) + ",\n"
374             descriptions_str = descriptions_str[:-1] # trim trailing newline
375             if labels:
376                 global statedefines
377                 statedefines += "/* States for %s */\n" % item[0]
378                 for (i, (label, message)) in enumerate(labels):
379                     if len(message) >= 45:
380                         message = message[:45] + "..."
381                     statedefines += "#define %s\t%d /* %s */\n" % (label, i, message)
382                 statedefines += "\n"
383         sounds_str = ""
384         if attr.get("sounds") == None:
385             sounds_str = " " * 12 + "NULL,"
386         else:
387              for l_msg in attr["sounds"]:
388                  sounds_str += " " * 12 + make_c_string(l_msg) + ",\n"
389              sounds_str = sounds_str[:-1] # trim trailing newline
390         texts_str = ""
391         if attr.get("texts") == None:
392             texts_str = " " * 12 + "NULL,"
393         else:
394              for l_msg in attr["texts"]:
395                  texts_str += " " * 12 + make_c_string(l_msg) + ",\n"
396              texts_str = texts_str[:-1] # trim trailing newline
397         changes_str = ""
398         if attr.get("changes") == None:
399             changes_str = " " * 12 + "NULL,"
400         else:
401              for l_msg in attr["changes"]:
402                  changes_str += " " * 12 + make_c_string(l_msg) + ",\n"
403              changes_str = changes_str[:-1] # trim trailing newline
404         locs = attr.get("locations", ["LOC_NOWHERE", "LOC_NOWHERE"])
405         immovable = attr.get("immovable", False)
406         try:
407             if type(locs) == str:
408                 locs = [locnames.index(locs), -1 if immovable else 0]
409             else:
410                 locs = [locnames.index(x) for x in locs]
411         except IndexError:
412             sys.stderr.write("dungeon: unknown object location in %s\n" % locs)
413             sys.exit(1)
414         treasure = "true" if attr.get("treasure") else "false"
415         obj_str += template.format(i, i_msg, locs[0], locs[1], treasure, descriptions_str, sounds_str, texts_str, changes_str)
416     obj_str = obj_str[:-1] # trim trailing newline
417     return obj_str
418
419 def get_obituaries(obit):
420     template = """    {{
421         .query = {},
422         .yes_response = {},
423     }},
424 """
425     obit_str = ""
426     for o in obit:
427         query = make_c_string(o["query"])
428         yes = make_c_string(o["yes_response"])
429         obit_str += template.format(query, yes)
430     obit_str = obit_str[:-1] # trim trailing newline
431     return obit_str
432
433 def get_hints(hnt, arb):
434     template = """    {{
435         .number = {},
436         .penalty = {},
437         .turns = {},
438         .question = {},
439         .hint = {},
440     }},
441 """
442     hnt_str = ""
443     md = dict(arb)
444     for member in hnt:
445         item = member["hint"]
446         number = item["number"]
447         penalty = item["penalty"]
448         turns = item["turns"]
449         question = make_c_string(item["question"])
450         hint = make_c_string(item["hint"])
451         hnt_str += template.format(number, penalty, turns, question, hint)
452     hnt_str = hnt_str[:-1] # trim trailing newline
453     return hnt_str
454
455 def get_condbits(locations):
456     cnd_str = ""
457     for (name, loc) in locations:
458         conditions = loc["conditions"]
459         hints = loc.get("hints") or []
460         flaglist = []
461         for flag in conditions:
462             if conditions[flag]:
463                 flaglist.append(flag)
464         line = "|".join([("(1<<COND_%s)" % f) for f in flaglist])
465         trail = "|".join([("(1<<COND_H%s)" % f['name']) for f in hints])
466         if trail:
467             line += "|" + trail
468         if line.startswith("|"):
469             line = line[1:]
470         if not line:
471             line = "0"
472         cnd_str += "    " + line + ",\t// " + name + "\n"
473     return cnd_str
474
475 def recompose(type_word, value):
476     "Compose the internal code for a vocabulary word from its YAML entry"
477     parts = ("motion", "action", "object", "special")
478     try:
479         return value + 1000 * parts.index(type_word)
480     except KeyError:
481         sys.stderr.write("dungeon: %s is not a known word\n" % word)
482         sys.exit(1)
483     except IndexError:
484         sys.stderr.write("%s is not a known word classifier\n" % attrs["type"])
485         sys.exit(1)
486
487 def get_motions(motions):
488     template = """    {{
489         .words = {},
490     }},
491 """
492     mot_str = ""
493     for motion in motions:
494         contents = motion[1]
495         if contents["words"] == None:
496             mot_str += template.format("NULL")
497             continue
498         c_words = [make_c_string(s) for s in contents["words"]]
499         words_str = "(const char* []) {" + ", ".join(c_words) + "}"
500         mot_str += template.format(words_str)
501     return mot_str
502
503 def get_actions(actions):
504     template = """    {{
505         .words = {},
506         .message = {},
507     }},
508 """
509     act_str = ""
510     for action in actions:
511         contents = action[1]
512         
513         if contents["words"] == None:
514             words_str = "NULL"
515         else:
516             c_words = [make_c_string(s) for s in contents["words"]]
517             words_str = "(const char* []) {" + ", ".join(c_words) + "}"
518
519         if contents["message"] == None:
520             message = "NO_MESSAGE"
521         else:
522             message = contents["message"]
523             
524         act_str += template.format(words_str, message)
525     act_str = act_str[:-1] # trim trailing newline
526     return act_str
527
528 def bigdump(arr):
529     out = ""
530     for (i, entry) in enumerate(arr):
531         if i % 10 == 0:
532             if out and out[-1] == ' ':
533                 out = out[:-1]
534             out += "\n    "
535         out += str(arr[i]) + ", "
536     out = out[:-2] + "\n"
537     return out
538
539 def buildtravel(locs, objs, voc):
540     ltravel = []
541     verbmap = {}
542     for entry in db["vocabulary"]:
543         if entry["type"] == "motion" and entry["value"] not in verbmap:
544             verbmap[entry["word"]] = entry["value"]
545     def dencode(action, name):
546         "Decode a destination number"
547         if action[0] == "goto":
548             try:
549                 return locnames.index(action[1])
550             except ValueError:
551                 sys.stderr.write("dungeon: unknown location %s in goto clause of %s\n" % (cond[1], name))
552         elif action[0] == "special":
553             return 300 + action[1]
554         elif action[0] == "speak":
555             try:
556                 return 500 + msgnames.index(action[1])
557             except ValueError:
558                 sys.stderr.write("dungeon: unknown location %s in carry clause of %s\n" % (cond[1], name))
559         else:
560             print(cond)
561             raise ValueError
562     def cencode(cond, name):
563         if cond is None:
564             return 0;
565         elif cond[0] == "pct":
566             return cond[1]
567         elif cond[0] == "carry":
568             try:
569                 return 100 + objnames.index(cond[1])
570             except ValueError:
571                 sys.stderr.write("dungeon: unknown object name %s in carry clause of %s\n" % (cond[1], name))
572                 sys.exit(1)
573         elif cond[0] == "with":
574             try:
575                 return 200 + objnames.index(cond[1])
576             except IndexError:
577                 sys.stderr.write("dungeon: unknown object name %s in with clause of \n" % (cond[1], name))
578                 sys.exit(1)
579         elif cond[0] == "not":
580             # FIXME: Allow named as well as numbered states
581             try:
582                 obj = objnames.index(cond[1])
583                 if type(cond[2]) == int:
584                     state = cond[2]
585                 else:
586                     for (i, stateclause) in enumerate(objs[obj][1]["descriptions"]):
587                         if type(stateclause) == list:
588                             if stateclause[0] == cond[2]:
589                                 state = i
590                                 break
591                     else:
592                         sys.stderr.write("dungeon: unmatched state symbol %s in not clause of %s\n" % (cond[2], name))
593                         sys.exit(0);
594                 return 300 + obj + 100 * state
595             except ValueError:
596                 sys.stderr.write("dungeon: unknown object name %s in not clause of %s\n" % (cond[1], name))
597                 sys.exit(1)
598         else:
599             print(cond)
600             raise ValueError
601
602     for (i, (name, loc)) in enumerate(locs):
603         if "travel" in loc:
604             for rule in loc["travel"]:
605                 tt = [i]
606                 dest = dencode(rule["action"], name) + 1000 * cencode(rule.get("cond"), name)
607                 tt.append(dest)
608                 tt += [verbmap[e] for e in rule["verbs"]]
609                 if not rule["verbs"]:
610                     tt.append(1)
611                 ltravel.append(tuple(tt))
612
613     # At this point the ltravel data is in the Section 3
614     # representation from the FORTRAN version.  Next we perform the
615     # same mapping into the runtime format.  This was the C translation
616     # of the FORTRAN code:
617     # long loc;
618     # while ((loc = GETNUM(database)) != -1) {
619     #     long newloc = GETNUM(NULL);
620     #     long L;
621     #     if (TKEY[loc] == 0) {
622     #         TKEY[loc] = TRVS;
623     #     } else {
624     #         TRAVEL[TRVS - 1] = -TRAVEL[TRVS - 1];
625     #     }
626     #     while ((L = GETNUM(NULL)) != 0) {
627     #         TRAVEL[TRVS] = newloc * 1000 + L;
628     #         TRVS = TRVS + 1;
629     #         if (TRVS == TRVSIZ)
630     #             BUG(TOO_MANY_TRAVEL_OPTIONS);
631     #     }
632     #     TRAVEL[TRVS - 1] = -TRAVEL[TRVS - 1];
633     # }
634     #
635     # In order to de-crypticize the runtime code, we're going to break these
636     # magic numbers up into a struct.
637     travel = [[0, 0, False]]
638     tkey = [0]
639     oldloc = 0
640     while ltravel:
641         rule = list(ltravel.pop(0))
642         loc = rule.pop(0)
643         newloc = rule.pop(0)
644         if loc != oldloc:
645             tkey.append(len(travel))
646             oldloc = loc 
647         elif travel:
648             travel[-1][2] = not travel[-1][2]
649         while rule:
650             travel.append([rule.pop(0), newloc, False])
651         travel[-1][2] = True
652     return (travel, tkey)
653
654 def get_travel(travel):
655     template = """    {{
656         .motion = {},
657         .dest = {},
658         .stop = {},
659     }},
660 """
661     out = ""
662     for entry in travel:
663         out += template.format(entry[0], entry[1], entry[2]).lower()
664     out = out[:-1] # trim trailing newline
665     return out
666
667 if __name__ == "__main__":
668     with open(yaml_name, "r") as f:
669         db = yaml.load(f)
670
671     locnames = [x[0] for x in db["locations"]]
672     msgnames = [el[0] for el in db["arbitrary_messages"]]
673     objnames = [el[0] for el in db["objects"]]
674
675     (travel, tkey) = buildtravel(db["locations"],
676                                  db["objects"],
677                                  db["vocabulary"])
678
679     c = c_template.format(
680         h_name,
681         get_arbitrary_messages(db["arbitrary_messages"]),
682         get_class_messages(db["classes"]),
683         get_turn_thresholds(db["turn_thresholds"]),
684         get_locations(db["locations"]),
685         get_objects(db["objects"]),
686         get_obituaries(db["obituaries"]),
687         get_hints(db["hints"], db["arbitrary_messages"]),
688         get_condbits(db["locations"]),
689         get_motions(db["motions"]),
690         get_actions(db["actions"]),
691         "const long tkey[] = {%s};" % bigdump(tkey),
692         get_travel(travel), 
693     )
694
695     h = h_template.format(
696         len(db["locations"])-1,
697         len(db["objects"])-1,
698         len(db["hints"]),
699         len(db["classes"])-1,
700         len(db["obituaries"]),
701         len(db["turn_thresholds"]),
702         len(db["actions"]),
703         len(travel),
704         len(tkey),
705         get_refs(db["arbitrary_messages"]),
706         get_refs(db["locations"]),
707         get_refs(db["objects"]),
708         get_refs(db["motions"]),
709         get_refs(db["actions"]),
710         statedefines,
711     )
712
713     with open(h_name, "w") as hf:
714         hf.write(h)
715
716     with open(c_name, "w") as cf:
717         cf.write(c)
718
719 # end