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