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