Forther break apart the magic enconding of travel arrays.
[open-adventure.git] / make_dungeon.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 = "dungeon.h"
51 c_name = "dungeon.c"
52
53 statedefines = ""
54
55 h_template = """/* Generated from adventure.yaml - do not hand-hack! */
56 #ifndef DUNGEON_H
57 #define DUNGEON_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** strs;
89   const int n;
90 }} string_group_t;
91
92 typedef struct {{
93   const string_group_t words;
94   const char* inventory;
95   int plac, fixd;
96   bool is_treasure;
97   const char** descriptions;
98   const char** sounds;
99   const char** texts;
100   const char** changes;
101 }} object_t;
102
103 typedef struct {{
104   const char* small;
105   const char* big;
106 }} descriptions_t;
107
108 typedef struct {{
109   descriptions_t description;
110   const long sound;
111   const bool loud;
112 }} location_t;
113
114 typedef struct {{
115   const char* query;
116   const char* yes_response;
117 }} obituary_t;
118
119 typedef struct {{
120   const int threshold;
121   const int point_loss;
122   const char* message;
123 }} turn_threshold_t;
124
125 typedef struct {{
126   const int threshold;
127   const char* message;
128 }} class_t;
129
130 typedef struct {{
131   const int number;
132   const int turns;
133   const int penalty;
134   const char* question;
135   const char* hint;
136 }} hint_t;
137
138 typedef struct {{
139   const string_group_t words;
140 }} motion_t;
141
142 typedef struct {{
143   const string_group_t words;
144   const long message;
145 }} action_t;
146
147 typedef struct {{
148   const long motion;
149   const long cond;
150   const long dest;
151   const bool stop;
152 }} travelop_t;
153
154 /* Abstract out the encoding of words in the travel array.  Gives us
155  * some hope of getting to a less cryptic representation than we
156  * inherited from FORTRAN, someday. To understand these, read the
157  * encoding description for travel.
158  */
159 #define T_DESTINATION(entry)    (entry).dest
160 #define T_CONDITION(entry)      (entry).cond
161 #define T_NODWARVES(entry)      (T_CONDITION(entry) == 100)
162 #define T_TERMINATE(entry)      ((entry).motion == 1)
163 #define L_SPEAK(loc)            ((loc) - 500)
164
165 extern const location_t locations[];
166 extern const object_t objects[];
167 extern const char* arbitrary_messages[];
168 extern const class_t classes[];
169 extern const turn_threshold_t turn_thresholds[];
170 extern const obituary_t obituaries[];
171 extern const hint_t hints[];
172 extern long conditions[];
173 extern const motion_t motions[];
174 extern const action_t actions[];
175 extern const action_t specials[];
176 extern const travelop_t travel[];
177 extern const long tkey[];
178 extern const char *ignore;
179
180 #define NLOCATIONS      {}
181 #define NOBJECTS        {}
182 #define NHINTS          {}
183 #define NCLASSES        {}
184 #define NDEATHS         {}
185 #define NTHRESHOLDS     {}
186 #define NMOTIONS        {}
187 #define NACTIONS        {}
188 #define NSPECIALS       {}
189 #define NTRAVEL         {}
190 #define NKEYS           {}
191
192 enum arbitrary_messages_refs {{
193 {}
194 }};
195
196 enum locations_refs {{
197 {}
198 }};
199
200 enum object_refs {{
201 {}
202 }};
203
204 enum motion_refs {{
205 {}
206 }};
207
208 enum action_refs {{
209 {}
210 }};
211
212 enum special_refs {{
213 {}
214 }};
215
216 /* State definitions */
217
218 {}
219 #endif /* end DUNGEON_H */
220 """
221
222 c_template = """/* Generated from adventure.yaml - do not hand-hack! */
223
224 #include "{}"
225
226 const char* arbitrary_messages[] = {{
227 {}
228 }};
229
230 const class_t classes[] = {{
231 {}
232 }};
233
234 const turn_threshold_t turn_thresholds[] = {{
235 {}
236 }};
237
238 const location_t locations[] = {{
239 {}
240 }};
241
242 const object_t objects[] = {{
243 {}
244 }};
245
246 const obituary_t obituaries[] = {{
247 {}
248 }};
249
250 const hint_t hints[] = {{
251 {}
252 }};
253
254 long conditions[] = {{
255 {}
256 }};
257
258 const motion_t motions[] = {{
259 {}
260 }};
261
262 const action_t actions[] = {{
263 {}
264 }};
265
266 const action_t specials[] = {{
267 {}
268 }};
269
270 const long tkey[] = {{{}}};
271
272 const travelop_t travel[] = {{
273 {}
274 }};
275
276 const char *ignore = \"{}\";
277
278 /* end */
279 """
280
281 def make_c_string(string):
282     """Render a Python string into C string literal format."""
283     if string == None:
284         return "NULL"
285     string = string.replace("\n", "\\n")
286     string = string.replace("\t", "\\t")
287     string = string.replace('"', '\\"')
288     string = string.replace("'", "\\'")
289     string = '"' + string + '"'
290     return string
291
292 def get_refs(l):
293     reflist = [x[0] for x in l]
294     ref_str = ""
295     for ref in reflist:
296         ref_str += "    {},\n".format(ref)
297     ref_str = ref_str[:-1] # trim trailing newline
298     return ref_str
299
300 def get_string_group(strings):
301     template = """{{
302             .strs = {},
303             .n = {},
304         }}"""
305     if strings == []:
306         strs = "NULL"
307     else:
308         strs = "(const char* []) {" + ", ".join([make_c_string(s) for s in strings]) + "}"
309     n = len(strings)
310     sg_str = template.format(strs, n)
311     return sg_str
312
313 def get_arbitrary_messages(arb):
314     template = """    {},
315 """
316     arb_str = ""
317     for item in arb:
318         arb_str += template.format(make_c_string(item[1]))
319     arb_str = arb_str[:-1] # trim trailing newline
320     return arb_str
321
322 def get_class_messages(cls):
323     template = """    {{
324         .threshold = {},
325         .message = {},
326     }},
327 """
328     cls_str = ""
329     for item in cls:
330         threshold = item["threshold"]
331         message = make_c_string(item["message"])
332         cls_str += template.format(threshold, message)
333     cls_str = cls_str[:-1] # trim trailing newline
334     return cls_str
335
336 def get_turn_thresholds(trn):
337     template = """    {{
338         .threshold = {},
339         .point_loss = {},
340         .message = {},
341     }},
342 """
343     trn_str = ""
344     for item in trn:
345         threshold = item["threshold"]
346         point_loss = item["point_loss"]
347         message = make_c_string(item["message"])
348         trn_str += template.format(threshold, point_loss, message)
349     trn_str = trn_str[:-1] # trim trailing newline
350     return trn_str
351
352 def get_locations(loc):
353     template = """    {{ // {}
354         .description = {{
355             .small = {},
356             .big = {},
357         }},
358         .sound = {},
359         .loud = {},
360     }},
361 """
362     loc_str = ""
363     for (i, item) in enumerate(loc):
364         short_d = make_c_string(item[1]["description"]["short"])
365         long_d = make_c_string(item[1]["description"]["long"])
366         sound = item[1].get("sound", "SILENT")
367         loud = "true" if item[1].get("loud") else "false"
368         loc_str += template.format(i, short_d, long_d, sound, loud)
369     loc_str = loc_str[:-1] # trim trailing newline
370     return loc_str
371
372 def get_objects(obj):
373     template = """    {{ // {}
374         .words = {},
375         .inventory = {},
376         .plac = {},
377         .fixd = {},
378         .is_treasure = {},
379         .descriptions = (const char* []) {{
380 {}
381         }},
382         .sounds = (const char* []) {{
383 {}
384         }},
385         .texts = (const char* []) {{
386 {}
387         }},
388         .changes = (const char* []) {{
389 {}
390         }},
391     }},
392 """
393     obj_str = ""
394     for (i, item) in enumerate(obj):
395         attr = item[1]
396         try:
397             words_str = get_string_group(attr["words"])
398         except KeyError:
399             words_str = get_string_group([])
400         i_msg = make_c_string(attr["inventory"])
401         descriptions_str = ""
402         if attr["descriptions"] == None:
403             descriptions_str = " " * 12 + "NULL,"
404         else:
405             labels = []
406             for l_msg in attr["descriptions"]:
407                 if not isinstance(l_msg, str):
408                     labels.append(l_msg)
409                     l_msg = l_msg[1]
410                 descriptions_str += " " * 12 + make_c_string(l_msg) + ",\n"
411             descriptions_str = descriptions_str[:-1] # trim trailing newline
412             if labels:
413                 global statedefines
414                 statedefines += "/* States for %s */\n" % item[0]
415                 for (i, (label, message)) in enumerate(labels):
416                     if len(message) >= 45:
417                         message = message[:45] + "..."
418                     statedefines += "#define %s\t%d /* %s */\n" % (label, i, message)
419                 statedefines += "\n"
420         sounds_str = ""
421         if attr.get("sounds") == None:
422             sounds_str = " " * 12 + "NULL,"
423         else:
424              for l_msg in attr["sounds"]:
425                  sounds_str += " " * 12 + make_c_string(l_msg) + ",\n"
426              sounds_str = sounds_str[:-1] # trim trailing newline
427         texts_str = ""
428         if attr.get("texts") == None:
429             texts_str = " " * 12 + "NULL,"
430         else:
431              for l_msg in attr["texts"]:
432                  texts_str += " " * 12 + make_c_string(l_msg) + ",\n"
433              texts_str = texts_str[:-1] # trim trailing newline
434         changes_str = ""
435         if attr.get("changes") == None:
436             changes_str = " " * 12 + "NULL,"
437         else:
438              for l_msg in attr["changes"]:
439                  changes_str += " " * 12 + make_c_string(l_msg) + ",\n"
440              changes_str = changes_str[:-1] # trim trailing newline
441         locs = attr.get("locations", ["LOC_NOWHERE", "LOC_NOWHERE"])
442         immovable = attr.get("immovable", False)
443         try:
444             if type(locs) == str:
445                 locs = [locnames.index(locs), -1 if immovable else 0]
446             else:
447                 locs = [locnames.index(x) for x in locs]
448         except IndexError:
449             sys.stderr.write("dungeon: unknown object location in %s\n" % locs)
450             sys.exit(1)
451         treasure = "true" if attr.get("treasure") else "false"
452         obj_str += template.format(i, words_str, i_msg, locs[0], locs[1], treasure, descriptions_str, sounds_str, texts_str, changes_str)
453     obj_str = obj_str[:-1] # trim trailing newline
454     return obj_str
455
456 def get_obituaries(obit):
457     template = """    {{
458         .query = {},
459         .yes_response = {},
460     }},
461 """
462     obit_str = ""
463     for o in obit:
464         query = make_c_string(o["query"])
465         yes = make_c_string(o["yes_response"])
466         obit_str += template.format(query, yes)
467     obit_str = obit_str[:-1] # trim trailing newline
468     return obit_str
469
470 def get_hints(hnt, arb):
471     template = """    {{
472         .number = {},
473         .penalty = {},
474         .turns = {},
475         .question = {},
476         .hint = {},
477     }},
478 """
479     hnt_str = ""
480     md = dict(arb)
481     for member in hnt:
482         item = member["hint"]
483         number = item["number"]
484         penalty = item["penalty"]
485         turns = item["turns"]
486         question = make_c_string(item["question"])
487         hint = make_c_string(item["hint"])
488         hnt_str += template.format(number, penalty, turns, question, hint)
489     hnt_str = hnt_str[:-1] # trim trailing newline
490     return hnt_str
491
492 def get_condbits(locations):
493     cnd_str = ""
494     for (name, loc) in locations:
495         conditions = loc["conditions"]
496         hints = loc.get("hints") or []
497         flaglist = []
498         for flag in conditions:
499             if conditions[flag]:
500                 flaglist.append(flag)
501         line = "|".join([("(1<<COND_%s)" % f) for f in flaglist])
502         trail = "|".join([("(1<<COND_H%s)" % f['name']) for f in hints])
503         if trail:
504             line += "|" + trail
505         if line.startswith("|"):
506             line = line[1:]
507         if not line:
508             line = "0"
509         cnd_str += "    " + line + ",\t// " + name + "\n"
510     return cnd_str
511
512 def get_motions(motions):
513     template = """    {{
514         .words = {},
515     }},
516 """
517     mot_str = ""
518     for motion in motions:
519         contents = motion[1]
520         if contents["words"] == None:
521             words_str = get_string_group([])
522         else:
523             words_str = get_string_group(contents["words"])
524         mot_str += template.format(words_str)
525         global ignore
526         if contents.get("oldstyle", True) == False:
527             for word in contents["words"]:
528                 if len(word) == 1:
529                     ignore += word.upper()
530     return mot_str
531
532 def get_actions(actions):
533     template = """    {{
534         .words = {},
535         .message = {},
536     }},
537 """
538     act_str = ""
539     for action in actions:
540         contents = action[1]
541         
542         if contents["words"] == None:
543             words_str = get_string_group([])
544         else:
545             words_str = get_string_group(contents["words"])
546
547         if contents["message"] == None:
548             message = "NO_MESSAGE"
549         else:
550             message = contents["message"]
551             
552         act_str += template.format(words_str, message)
553         global ignore
554         if contents.get("oldstyle", True) == False:
555             for word in contents["words"]:
556                 if len(word) == 1:
557                     ignore += word.upper()
558     act_str = act_str[:-1] # trim trailing newline
559     return act_str
560
561 def bigdump(arr):
562     out = ""
563     for (i, entry) in enumerate(arr):
564         if i % 10 == 0:
565             if out and out[-1] == ' ':
566                 out = out[:-1]
567             out += "\n    "
568         out += str(arr[i]).lower() + ", "
569     out = out[:-2] + "\n"
570     return out
571
572 def buildtravel(locs, objs):
573     ltravel = []
574     verbmap = {}
575     for i, motion in enumerate(db["motions"]):
576         try:
577             for word in motion[1]["words"]:
578                 verbmap[word.upper()] = i
579         except TypeError:
580             pass
581     def dencode(action, name):
582         "Decode a destination number"
583         if action[0] == "goto":
584             try:
585                 return locnames.index(action[1])
586             except ValueError:
587                 sys.stderr.write("dungeon: unknown location %s in goto clause of %s\n" % (cond[1], name))
588         elif action[0] == "special":
589             return 300 + action[1]
590         elif action[0] == "speak":
591             try:
592                 return 500 + msgnames.index(action[1])
593             except ValueError:
594                 sys.stderr.write("dungeon: unknown location %s in carry clause of %s\n" % (cond[1], name))
595         else:
596             print(cond)
597             raise ValueError
598     def cencode(cond, name):
599         if cond is None:
600             return 0;
601         elif cond[0] == "pct":
602             return cond[1]
603         elif cond[0] == "carry":
604             try:
605                 return 100 + objnames.index(cond[1])
606             except ValueError:
607                 sys.stderr.write("dungeon: unknown object name %s in carry clause of %s\n" % (cond[1], name))
608                 sys.exit(1)
609         elif cond[0] == "with":
610             try:
611                 return 200 + objnames.index(cond[1])
612             except IndexError:
613                 sys.stderr.write("dungeon: unknown object name %s in with clause of \n" % (cond[1], name))
614                 sys.exit(1)
615         elif cond[0] == "not":
616             # FIXME: Allow named as well as numbered states
617             try:
618                 obj = objnames.index(cond[1])
619                 if type(cond[2]) == int:
620                     state = cond[2]
621                 else:
622                     for (i, stateclause) in enumerate(objs[obj][1]["descriptions"]):
623                         if type(stateclause) == list:
624                             if stateclause[0] == cond[2]:
625                                 state = i
626                                 break
627                     else:
628                         sys.stderr.write("dungeon: unmatched state symbol %s in not clause of %s\n" % (cond[2], name))
629                         sys.exit(0);
630                 return 300 + obj + 100 * state
631             except ValueError:
632                 sys.stderr.write("dungeon: unknown object name %s in not clause of %s\n" % (cond[1], name))
633                 sys.exit(1)
634         else:
635             print(cond)
636             raise ValueError
637
638     for (i, (name, loc)) in enumerate(locs):
639         if "travel" in loc:
640             for rule in loc["travel"]:
641                 tt = [i]
642                 dest = dencode(rule["action"], name) + 1000 * cencode(rule.get("cond"), name)
643                 tt.append(dest)
644                 tt += [verbmap[e] for e in rule["verbs"]]
645                 if not rule["verbs"]:
646                     tt.append(1)
647                 ltravel.append(tuple(tt))
648
649     # At this point the ltravel data is in the Section 3
650     # representation from the FORTRAN version.  Next we perform the
651     # same mapping into the runtime format.  This was the C translation
652     # of the FORTRAN code:
653     # long loc;
654     # while ((loc = GETNUM(database)) != -1) {
655     #     long newloc = GETNUM(NULL);
656     #     long L;
657     #     if (TKEY[loc] == 0) {
658     #         TKEY[loc] = TRVS;
659     #     } else {
660     #         TRAVEL[TRVS - 1] = -TRAVEL[TRVS - 1];
661     #     }
662     #     while ((L = GETNUM(NULL)) != 0) {
663     #         TRAVEL[TRVS] = newloc * 1000 + L;
664     #         TRVS = TRVS + 1;
665     #         if (TRVS == TRVSIZ)
666     #             BUG(TOO_MANY_TRAVEL_OPTIONS);
667     #     }
668     #     TRAVEL[TRVS - 1] = -TRAVEL[TRVS - 1];
669     # }
670     #
671     # In order to de-crypticize the runtime code, we're going to break these
672     # magic numbers up into a struct.
673     travel = [[0, 0, 0, False]]
674     tkey = [0]
675     oldloc = 0
676     while ltravel:
677         rule = list(ltravel.pop(0))
678         loc = rule.pop(0)
679         newloc = rule.pop(0)
680         if loc != oldloc:
681             tkey.append(len(travel))
682             oldloc = loc 
683         elif travel:
684             travel[-1][-1] = not travel[-1][-1]
685         while rule:
686             travel.append([rule.pop(0), newloc // 1000, newloc % 1000, False])
687         travel[-1][-1] = True
688     return (travel, tkey)
689
690 def get_travel(travel):
691     template = """    {{
692         .motion = {},
693         .cond = {},
694         .dest = {},
695         .stop = {},
696     }},
697 """
698     out = ""
699     for entry in travel:
700         out += template.format(entry[0], entry[1], entry[2], entry[3]).lower()
701     out = out[:-1] # trim trailing newline
702     return out
703
704 if __name__ == "__main__":
705     with open(yaml_name, "r") as f:
706         db = yaml.load(f)
707
708     locnames = [x[0] for x in db["locations"]]
709     msgnames = [el[0] for el in db["arbitrary_messages"]]
710     objnames = [el[0] for el in db["objects"]]
711
712     (travel, tkey) = buildtravel(db["locations"],
713                                  db["objects"])
714     ignore = ""
715     c = c_template.format(
716         h_name,
717         get_arbitrary_messages(db["arbitrary_messages"]),
718         get_class_messages(db["classes"]),
719         get_turn_thresholds(db["turn_thresholds"]),
720         get_locations(db["locations"]),
721         get_objects(db["objects"]),
722         get_obituaries(db["obituaries"]),
723         get_hints(db["hints"], db["arbitrary_messages"]),
724         get_condbits(db["locations"]),
725         get_motions(db["motions"]),
726         get_actions(db["actions"]),
727         get_actions(db["specials"]),
728         bigdump(tkey),
729         get_travel(travel), 
730         ignore,
731     )
732
733     h = h_template.format(
734         len(db["locations"])-1,
735         len(db["objects"])-1,
736         len(db["hints"]),
737         len(db["classes"])-1,
738         len(db["obituaries"]),
739         len(db["turn_thresholds"]),
740         len(db["motions"]),
741         len(db["actions"]),
742         len(db["specials"]),
743         len(travel),
744         len(tkey),
745         get_refs(db["arbitrary_messages"]),
746         get_refs(db["locations"]),
747         get_refs(db["objects"]),
748         get_refs(db["motions"]),
749         get_refs(db["actions"]),
750         get_refs(db["specials"]),
751         statedefines,
752     )
753
754     with open(h_name, "w") as hf:
755         hf.write(h)
756
757     with open(c_name, "w") as cf:
758         cf.write(c)
759
760 # end