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