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