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