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