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