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