refactored fallback_handler() to use command_t, isolating from side effects
[open-adventure.git] / make_dungeon.py
1 #!/usr/bin/python3
2
3 # This is the open-adventure dungeon generator. It consumes a YAML description of
4 # the dungeon and outputs a dungeon.h and dungeon.c pair of C code files.
5 #
6 # The nontrivial part of this is the compilation of the YAML for
7 # movement rules to the travel array that's actually used by
8 # playermove().
9
10 import sys, yaml
11
12 yaml_name = "adventure.yaml"
13 h_name = "dungeon.h"
14 c_name = "dungeon.c"
15
16 statedefines = ""
17
18 h_template = """/* Generated from adventure.yaml - do not hand-hack! */
19 #ifndef DUNGEON_H
20 #define DUNGEON_H
21
22 #include <stdio.h>
23 #include <stdbool.h>
24
25 #define SILENT  -1      /* no sound */
26
27 /* Symbols for cond bits */
28 #define COND_LIT        0       /* Light */
29 #define COND_OILY       1       /* If bit 2 is on: on for oil, off for water */
30 #define COND_FLUID      2       /* Liquid asset, see bit 1 */
31 #define COND_NOARRR     3       /* Pirate doesn't go here unless following */
32 #define COND_NOBACK     4       /* Cannot use "back" to move away */
33 #define COND_ABOVE      5
34 #define COND_DEEP       6       /* Deep - e.g where dwarves are active */
35 #define COND_FOREST     7       /* In the forest */
36 #define COND_FORCED     8       /* Only one way in or out of here */
37 /* Bits past 10 indicate areas of interest to "hint" routines */
38 #define COND_HBASE      10      /* Base for location hint bits */
39 #define COND_HCAVE      11      /* Trying to get into cave */
40 #define COND_HBIRD      12      /* Trying to catch bird */
41 #define COND_HSNAKE     13      /* Trying to deal with snake */
42 #define COND_HMAZE      14      /* Lost in maze */
43 #define COND_HDARK      15      /* Pondering dark room */
44 #define COND_HWITT      16      /* At Witt's End */
45 #define COND_HCLIFF     17      /* Cliff with urn */
46 #define COND_HWOODS     18      /* Lost in forest */
47 #define COND_HOGRE      19      /* Trying to deal with ogre */
48 #define COND_HJADE      20      /* Found all treasures except jade */
49
50 typedef struct {{
51   const char** strs;
52   const int n;
53 }} string_group_t;
54
55 typedef struct {{
56   const string_group_t words;
57   const char* inventory;
58   int plac, fixd;
59   bool is_treasure;
60   const char** descriptions;
61   const char** sounds;
62   const char** texts;
63   const char** changes;
64 }} object_t;
65
66 typedef struct {{
67   const char* small;
68   const char* big;
69 }} descriptions_t;
70
71 typedef struct {{
72   descriptions_t description;
73   const long sound;
74   const bool loud;
75 }} location_t;
76
77 typedef struct {{
78   const char* query;
79   const char* yes_response;
80 }} obituary_t;
81
82 typedef struct {{
83   const int threshold;
84   const int point_loss;
85   const char* message;
86 }} turn_threshold_t;
87
88 typedef struct {{
89   const int threshold;
90   const char* message;
91 }} class_t;
92
93 typedef struct {{
94   const int number;
95   const int turns;
96   const int penalty;
97   const char* question;
98   const char* hint;
99 }} hint_t;
100
101 typedef struct {{
102   const string_group_t words;
103 }} motion_t;
104
105 typedef struct {{
106   const string_group_t words;
107   const char* message;
108 }} action_t;
109
110 typedef struct {{
111   const string_group_t words;
112   const char* message;
113 }} special_t;
114
115 enum condtype_t {{cond_goto, cond_pct, cond_carry, cond_with, cond_not}};
116 enum desttype_t {{dest_goto, dest_special, dest_speak}};
117
118 typedef struct {{
119   const long motion;
120   const long condtype;
121   const long condarg1;
122   const long condarg2;
123   const enum desttype_t desttype;
124   const long destval;
125   const bool nodwarves;
126   const bool stop;
127 }} travelop_t;
128
129 /* Abstract out the encoding of words in the travel array.  Gives us
130  * some hope of getting to a less cryptic representation than we
131  * inherited from FORTRAN, someday. To understand these, read the
132  * encoding description for travel.
133  */
134 #define T_TERMINATE(entry)      ((entry).motion == 1)
135
136 extern const location_t locations[];
137 extern const object_t objects[];
138 extern const char* arbitrary_messages[];
139 extern const class_t classes[];
140 extern const turn_threshold_t turn_thresholds[];
141 extern const obituary_t obituaries[];
142 extern const hint_t hints[];
143 extern long conditions[];
144 extern const motion_t motions[];
145 extern const action_t actions[];
146 extern const special_t specials[];
147 extern const travelop_t travel[];
148 extern const long tkey[];
149 extern const char *ignore;
150
151 #define NLOCATIONS      {}
152 #define NOBJECTS        {}
153 #define NHINTS          {}
154 #define NCLASSES        {}
155 #define NDEATHS         {}
156 #define NTHRESHOLDS     {}
157 #define NMOTIONS        {}
158 #define NACTIONS        {}
159 #define NSPECIALS       {}
160 #define NTRAVEL         {}
161 #define NKEYS           {}
162
163 #define BIRD_ENDSTATE   {}
164
165 enum arbitrary_messages_refs {{
166 {}
167 }};
168
169 enum locations_refs {{
170 {}
171 }};
172
173 enum object_refs {{
174 {}
175 }};
176
177 enum motion_refs {{
178 {}
179 }};
180
181 enum action_refs {{
182 {}
183 }};
184
185 enum special_refs {{
186 {}
187 }};
188
189 /* State definitions */
190
191 {}
192 #endif /* end DUNGEON_H */
193 """
194
195 c_template = """/* Generated from adventure.yaml - do not hand-hack! */
196
197 #include "{}"
198
199 const char* arbitrary_messages[] = {{
200 {}
201 }};
202
203 const class_t classes[] = {{
204 {}
205 }};
206
207 const turn_threshold_t turn_thresholds[] = {{
208 {}
209 }};
210
211 const location_t locations[] = {{
212 {}
213 }};
214
215 const object_t objects[] = {{
216 {}
217 }};
218
219 const obituary_t obituaries[] = {{
220 {}
221 }};
222
223 const hint_t hints[] = {{
224 {}
225 }};
226
227 long conditions[] = {{
228 {}
229 }};
230
231 const motion_t motions[] = {{
232 {}
233 }};
234
235 const action_t actions[] = {{
236 {}
237 }};
238
239 const special_t specials[] = {{
240 {}
241 }};
242
243 const long tkey[] = {{{}}};
244
245 const travelop_t travel[] = {{
246 {}
247 }};
248
249 const char *ignore = \"{}\";
250
251 /* end */
252 """
253
254 def make_c_string(string):
255     """Render a Python string into C string literal format."""
256     if string == None:
257         return "NULL"
258     string = string.replace("\n", "\\n")
259     string = string.replace("\t", "\\t")
260     string = string.replace('"', '\\"')
261     string = string.replace("'", "\\'")
262     string = '"' + string + '"'
263     return string
264
265 def get_refs(l):
266     reflist = [x[0] for x in l]
267     ref_str = ""
268     for ref in reflist:
269         ref_str += "    {},\n".format(ref)
270     ref_str = ref_str[:-1] # trim trailing newline
271     return ref_str
272
273 def get_string_group(strings):
274     template = """{{
275             .strs = {},
276             .n = {},
277         }}"""
278     if strings == []:
279         strs = "NULL"
280     else:
281         strs = "(const char* []) {" + ", ".join([make_c_string(s) for s in strings]) + "}"
282     n = len(strings)
283     sg_str = template.format(strs, n)
284     return sg_str
285
286 def get_arbitrary_messages(arb):
287     template = """    {},
288 """
289     arb_str = ""
290     for item in arb:
291         arb_str += template.format(make_c_string(item[1]))
292     arb_str = arb_str[:-1] # trim trailing newline
293     return arb_str
294
295 def get_class_messages(cls):
296     template = """    {{
297         .threshold = {},
298         .message = {},
299     }},
300 """
301     cls_str = ""
302     for item in cls:
303         threshold = item["threshold"]
304         message = make_c_string(item["message"])
305         cls_str += template.format(threshold, message)
306     cls_str = cls_str[:-1] # trim trailing newline
307     return cls_str
308
309 def get_turn_thresholds(trn):
310     template = """    {{
311         .threshold = {},
312         .point_loss = {},
313         .message = {},
314     }},
315 """
316     trn_str = ""
317     for item in trn:
318         threshold = item["threshold"]
319         point_loss = item["point_loss"]
320         message = make_c_string(item["message"])
321         trn_str += template.format(threshold, point_loss, message)
322     trn_str = trn_str[:-1] # trim trailing newline
323     return trn_str
324
325 def get_locations(loc):
326     template = """    {{ // {}: {}
327         .description = {{
328             .small = {},
329             .big = {},
330         }},
331         .sound = {},
332         .loud = {},
333     }},
334 """
335     loc_str = ""
336     for (i, item) in enumerate(loc):
337         short_d = make_c_string(item[1]["description"]["short"])
338         long_d = make_c_string(item[1]["description"]["long"])
339         sound = item[1].get("sound", "SILENT")
340         loud = "true" if item[1].get("loud") else "false"
341         loc_str += template.format(i, item[0], short_d, long_d, sound, loud)
342     loc_str = loc_str[:-1] # trim trailing newline
343     return loc_str
344
345 def get_objects(obj):
346     template = """    {{ // {}: {}
347         .words = {},
348         .inventory = {},
349         .plac = {},
350         .fixd = {},
351         .is_treasure = {},
352         .descriptions = (const char* []) {{
353 {}
354         }},
355         .sounds = (const char* []) {{
356 {}
357         }},
358         .texts = (const char* []) {{
359 {}
360         }},
361         .changes = (const char* []) {{
362 {}
363         }},
364     }},
365 """
366     obj_str = ""
367     for (i, item) in enumerate(obj):
368         attr = item[1]
369         try:
370             words_str = get_string_group(attr["words"])
371         except KeyError:
372             words_str = get_string_group([])
373         i_msg = make_c_string(attr["inventory"])
374         descriptions_str = ""
375         if attr["descriptions"] == None:
376             descriptions_str = " " * 12 + "NULL,"
377         else:
378             labels = []
379             for l_msg in attr["descriptions"]:
380                 descriptions_str += " " * 12 + make_c_string(l_msg) + ",\n"
381             for label in attr.get("states", []):
382                 labels.append(label)
383             descriptions_str = descriptions_str[:-1] # trim trailing newline
384             if labels:
385                 global statedefines
386                 statedefines += "/* States for %s */\n" % item[0]
387                 for (i, label) in enumerate(labels):
388                     statedefines += "#define %s\t%d\n" % (label, i)
389                 statedefines += "\n"
390         sounds_str = ""
391         if attr.get("sounds") == None:
392             sounds_str = " " * 12 + "NULL,"
393         else:
394              for l_msg in attr["sounds"]:
395                  sounds_str += " " * 12 + make_c_string(l_msg) + ",\n"
396              sounds_str = sounds_str[:-1] # trim trailing newline
397         texts_str = ""
398         if attr.get("texts") == None:
399             texts_str = " " * 12 + "NULL,"
400         else:
401              for l_msg in attr["texts"]:
402                  texts_str += " " * 12 + make_c_string(l_msg) + ",\n"
403              texts_str = texts_str[:-1] # trim trailing newline
404         changes_str = ""
405         if attr.get("changes") == None:
406             changes_str = " " * 12 + "NULL,"
407         else:
408              for l_msg in attr["changes"]:
409                  changes_str += " " * 12 + make_c_string(l_msg) + ",\n"
410              changes_str = changes_str[:-1] # trim trailing newline
411         locs = attr.get("locations", ["LOC_NOWHERE", "LOC_NOWHERE"])
412         immovable = attr.get("immovable", False)
413         try:
414             if type(locs) == str:
415                 locs = [locs, -1 if immovable else 0]
416         except IndexError:
417             sys.stderr.write("dungeon: unknown object location in %s\n" % locs)
418             sys.exit(1)
419         treasure = "true" if attr.get("treasure") else "false"
420         obj_str += template.format(i, item[0], words_str, i_msg, locs[0], locs[1], treasure, descriptions_str, sounds_str, texts_str, changes_str)
421     obj_str = obj_str[:-1] # trim trailing newline
422     return obj_str
423
424 def get_obituaries(obit):
425     template = """    {{
426         .query = {},
427         .yes_response = {},
428     }},
429 """
430     obit_str = ""
431     for o in obit:
432         query = make_c_string(o["query"])
433         yes = make_c_string(o["yes_response"])
434         obit_str += template.format(query, yes)
435     obit_str = obit_str[:-1] # trim trailing newline
436     return obit_str
437
438 def get_hints(hnt, arb):
439     template = """    {{
440         .number = {},
441         .penalty = {},
442         .turns = {},
443         .question = {},
444         .hint = {},
445     }},
446 """
447     hnt_str = ""
448     md = dict(arb)
449     for member in hnt:
450         item = member["hint"]
451         number = item["number"]
452         penalty = item["penalty"]
453         turns = item["turns"]
454         question = make_c_string(item["question"])
455         hint = make_c_string(item["hint"])
456         hnt_str += template.format(number, penalty, turns, question, hint)
457     hnt_str = hnt_str[:-1] # trim trailing newline
458     return hnt_str
459
460 def get_condbits(locations):
461     cnd_str = ""
462     for (name, loc) in locations:
463         conditions = loc["conditions"]
464         hints = loc.get("hints") or []
465         flaglist = []
466         for flag in conditions:
467             if conditions[flag]:
468                 flaglist.append(flag)
469         line = "|".join([("(1<<COND_%s)" % f) for f in flaglist])
470         trail = "|".join([("(1<<COND_H%s)" % f['name']) for f in hints])
471         if trail:
472             line += "|" + trail
473         if line.startswith("|"):
474             line = line[1:]
475         if not line:
476             line = "0"
477         cnd_str += "    " + line + ",\t// " + name + "\n"
478     return cnd_str
479
480 def get_motions(motions):
481     template = """    {{
482         .words = {},
483     }},
484 """
485     mot_str = ""
486     for motion in motions:
487         contents = motion[1]
488         if contents["words"] == None:
489             words_str = get_string_group([])
490         else:
491             words_str = get_string_group(contents["words"])
492         mot_str += template.format(words_str)
493         global ignore
494         if contents.get("oldstyle", True) == False:
495             for word in contents["words"]:
496                 if len(word) == 1:
497                     ignore += word.upper()
498     return mot_str
499
500 def get_actions(actions):
501     template = """    {{
502         .words = {},
503         .message = {},
504     }},
505 """
506     act_str = ""
507     for action in actions:
508         contents = action[1]
509         
510         if contents["words"] == None:
511             words_str = get_string_group([])
512         else:
513             words_str = get_string_group(contents["words"])
514
515         if contents["message"] == None:
516             message = "NO_MESSAGE"
517         else:
518             message = contents["message"]
519             
520         act_str += template.format(words_str, message)
521         global ignore
522         if contents.get("oldstyle", True) == False:
523             for word in contents["words"]:
524                 if len(word) == 1:
525                     ignore += word.upper()
526     act_str = act_str[:-1] # trim trailing newline
527     return act_str
528
529 def get_specials(specials):
530     template = """    {{
531         .words = {},
532         .message = {},
533     }},
534 """
535     spc_str = ""
536     for special in specials:
537         contents = special[1]
538
539         if contents["words"] == None:
540             words_str = get_string_group([])
541         else:
542             words_str = get_string_group(contents["words"])
543
544         if contents["message"] == None:
545             message = "NULL"
546         else:
547             message = make_c_string(contents["message"])
548
549         spc_str += template.format(words_str, message)
550         global ignore
551         if contents.get("oldstyle", True) == False:
552             for word in contents["words"]:
553                 if len(word) == 1:
554                     ignore += word.upper()
555     spc_str = spc_str[:-1] # trim trailing newline
556     return spc_str
557
558 def bigdump(arr):
559     out = ""
560     for (i, entry) in enumerate(arr):
561         if i % 10 == 0:
562             if out and out[-1] == ' ':
563                 out = out[:-1]
564             out += "\n    "
565         out += str(arr[i]).lower() + ", "
566     out = out[:-2] + "\n"
567     return out
568
569 def buildtravel(locs, objs):
570     assert len(locs) <= 300
571     assert len(objs) <= 100
572     # THIS CODE IS WAAAY MORE COMPLEX THAN IT NEEDS TO BE.  It's the
573     # result of a massive refactoring exercise that concentrated all
574     # the old nastiness in one spot. It hasn't been finally simplified
575     # because there's no need to do it until one of the asserions
576     # fails. Hint: if you try cleaning this up, the acceptance test is
577     # simple - the output dungeon.c must not change.
578     #
579     # This function first compiles the YAML to a form identical to the
580     # data in section 3 of the old adventure.text file, then a second
581     # stage unpacks that data into the travel array.  Here are the
582     # rules of that intermediate form:
583     #
584     # Each row of data contains a location number (X), a second
585     # location number (Y), and a list of motion numbers (see section 4).
586     # each motion represents a verb which will go to Y if currently at X.
587     # Y, in turn, is interpreted as follows.  Let M=Y/1000, N=Y mod 1000.
588     #           If N<=300       it is the location to go to.
589     #           If 300<N<=500   N-300 is used in a computed goto to
590     #                                   a section of special code.
591     #           If N>500        message N-500 from section 6 is printed,
592     #                                   and he stays wherever he is.
593     # Meanwhile, M specifies the conditions on the motion.
594     #           If M=0          it's unconditional.
595     #           If 0<M<100      it is done with M% probability.
596     #           If M=100        unconditional, but forbidden to dwarves.
597     #           If 100<M<=200   he must be carrying object M-100.
598     #           If 200<M<=300   must be carrying or in same room as M-200.
599     #           If 300<M<=400   game.prop(M % 100) must *not* be 0.
600     #           If 400<M<=500   game.prop(M % 100) must *not* be 1.
601     #           If 500<M<=600   game.prop(M % 100) must *not* be 2, etc.
602     # If the condition (if any) is not met, then the next *different*
603     # "destination" value is used (unless it fails to meet *its* conditions,
604     # in which case the next is found, etc.).  Typically, the next dest will
605     # be for one of the same verbs, so that its only use is as the alternate
606     # destination for those verbs.  For instance:
607     #           15      110022  29      31      34      35      23      43
608     #           15      14      29
609     # This says that, from loc 15, any of the verbs 29, 31, etc., will take
610     # him to 22 if he's carrying object 10, and otherwise will go to 14.
611     #           11      303008  49
612     #           11      9       50
613     # This says that, from 11, 49 takes him to 8 unless game.prop[3]=0, in which
614     # case he goes to 9.  Verb 50 takes him to 9 regardless of game.prop[3].
615     ltravel = []
616     verbmap = {}
617     for i, motion in enumerate(db["motions"]):
618         try:
619             for word in motion[1]["words"]:
620                 verbmap[word.upper()] = i
621         except TypeError:
622             pass
623     def dencode(action, name):
624         "Decode a destination number"
625         if action[0] == "goto":
626             try:
627                 return locnames.index(action[1])
628             except ValueError:
629                 sys.stderr.write("dungeon: unknown location %s in goto clause of %s\n" % (cond[1], name))
630         elif action[0] == "special":
631             return 300 + action[1]
632         elif action[0] == "speak":
633             try:
634                 return 500 + msgnames.index(action[1])
635             except ValueError:
636                 sys.stderr.write("dungeon: unknown location %s in carry clause of %s\n" % (cond[1], name))
637         else:
638             print(cond)
639             raise ValueError
640     def cencode(cond, name):
641         if cond is None:
642             return 0
643         elif cond == ["nodwarves"]:
644             return 100
645         elif cond[0] == "pct":
646             return cond[1]
647         elif cond[0] == "carry":
648             try:
649                 return 100 + objnames.index(cond[1])
650             except ValueError:
651                 sys.stderr.write("dungeon: unknown object name %s in carry clause of %s\n" % (cond[1], name))
652                 sys.exit(1)
653         elif cond[0] == "with":
654             try:
655                 return 200 + objnames.index(cond[1])
656             except IndexError:
657                 sys.stderr.write("dungeon: unknown object name %s in with clause of \n" % (cond[1], name))
658                 sys.exit(1)
659         elif cond[0] == "not":
660             try:
661                 obj = objnames.index(cond[1])
662                 if type(cond[2]) == int:
663                     state = cond[2]
664                 elif cond[2] in objs[obj][1].get("states", []):
665                     state = objs[obj][1].get("states").index(cond[2])
666                 else:
667                     for (i, stateclause) in enumerate(objs[obj][1]["descriptions"]):
668                         if type(stateclause) == list:
669                             if stateclause[0] == cond[2]:
670                                 state = i
671                                 break
672                     else:
673                         sys.stderr.write("dungeon: unmatched state symbol %s in not clause of %s\n" % (cond[2], name))
674                         sys.exit(0);
675                 return 300 + obj + 100 * state
676             except ValueError:
677                 sys.stderr.write("dungeon: unknown object name %s in not clause of %s\n" % (cond[1], name))
678                 sys.exit(1)
679         else:
680             print(cond)
681             raise ValueError
682
683     for (i, (name, loc)) in enumerate(locs):
684         if "travel" in loc:
685             for rule in loc["travel"]:
686                 tt = [i]
687                 dest = dencode(rule["action"], name) + 1000 * cencode(rule.get("cond"), name)
688                 tt.append(dest)
689                 tt += [motionnames[verbmap[e]].upper() for e in rule["verbs"]]
690                 if not rule["verbs"]:
691                     tt.append(1)        # Magic dummy entry for null rules
692                 ltravel.append(tuple(tt))
693
694     # At this point the ltravel data is in the Section 3
695     # representation from the FORTRAN version.  Next we perform the
696     # same mapping into wgat used to be the runtime format.
697
698     travel = [[0, "LOC_NOWHERE", 0, 0, 0, 0, 0, 0, "false", "false"]]
699     tkey = [0]
700     oldloc = 0
701     while ltravel:
702         rule = list(ltravel.pop(0))
703         loc = rule.pop(0)
704         newloc = rule.pop(0)
705         if loc != oldloc:
706             tkey.append(len(travel))
707             oldloc = loc 
708         elif travel:
709             travel[-1][-1] = "false" if travel[-1][-1] == "true" else "true" 
710         while rule:
711             cond = newloc // 1000
712             nodwarves = (cond == 100)
713             if cond == 0:
714                 condtype = "cond_goto"
715                 condarg1 = condarg2 = 0
716             elif cond < 100:
717                 condtype = "cond_pct"
718                 condarg1 = cond
719                 condarg2 = 0
720             elif cond == 100:
721                 condtype = "cond_goto"
722                 condarg1 = 100
723                 condarg2 = 0
724             elif cond <= 200:
725                 condtype = "cond_carry"
726                 condarg1 = objnames[cond - 100]
727                 condarg2 = 0
728             elif cond <= 300:
729                 condtype = "cond_with"
730                 condarg1 = objnames[cond - 200]
731                 condarg2 = 0
732             else:
733                 condtype = "cond_not"
734                 condarg1 = cond % 100
735                 condarg2 = (cond - 300) // 100.
736             dest = newloc % 1000
737             if dest <= 300:
738                 desttype = "dest_goto";
739                 destval = locnames[dest]
740             elif dest > 500:
741                 desttype = "dest_speak";
742                 destval = msgnames[dest - 500]
743             else:
744                 desttype = "dest_special";
745                 destval = locnames[dest - 300]
746             travel.append([len(tkey)-1,
747                            locnames[len(tkey)-1],
748                            rule.pop(0),
749                            condtype,
750                            condarg1,
751                            condarg2,
752                            desttype,
753                            destval,
754                            "true" if nodwarves else "false",
755                            "false"])
756         travel[-1][-1] = "true"
757     return (travel, tkey)
758
759 def get_travel(travel):
760     template = """    {{ // from {}: {}
761         .motion = {},
762         .condtype = {},
763         .condarg1 = {},
764         .condarg2 = {},
765         .desttype = {},
766         .destval = {},
767         .nodwarves = {},
768         .stop = {},
769     }},
770 """
771     out = ""
772     for entry in travel:
773         out += template.format(*entry)
774     out = out[:-1] # trim trailing newline
775     return out
776
777 if __name__ == "__main__":
778     with open(yaml_name, "r") as f:
779         db = yaml.load(f)
780
781     locnames = [x[0] for x in db["locations"]]
782     msgnames = [el[0] for el in db["arbitrary_messages"]]
783     objnames = [el[0] for el in db["objects"]]
784     motionnames = [el[0] for el in db["motions"]]
785
786     (travel, tkey) = buildtravel(db["locations"],
787                                  db["objects"])
788     ignore = ""
789     c = c_template.format(
790         h_name,
791         get_arbitrary_messages(db["arbitrary_messages"]),
792         get_class_messages(db["classes"]),
793         get_turn_thresholds(db["turn_thresholds"]),
794         get_locations(db["locations"]),
795         get_objects(db["objects"]),
796         get_obituaries(db["obituaries"]),
797         get_hints(db["hints"], db["arbitrary_messages"]),
798         get_condbits(db["locations"]),
799         get_motions(db["motions"]),
800         get_specials(db["actions"]),
801         get_specials(db["specials"]),
802         bigdump(tkey),
803         get_travel(travel), 
804         ignore,
805     )
806
807     # 0-origin index of birds's last song.  Bird should
808     # die after player hears this.
809     deathbird = len(dict(db["objects"])["BIRD"]["sounds"]) - 1
810
811     h = h_template.format(
812         len(db["locations"])-1,
813         len(db["objects"])-1,
814         len(db["hints"]),
815         len(db["classes"])-1,
816         len(db["obituaries"]),
817         len(db["turn_thresholds"]),
818         len(db["motions"]),
819         len(db["actions"]),
820         len(db["specials"]),
821         len(travel),
822         len(tkey),
823         deathbird,
824         get_refs(db["arbitrary_messages"]),
825         get_refs(db["locations"]),
826         get_refs(db["objects"]),
827         get_refs(db["motions"]),
828         get_refs(db["actions"]),
829         get_refs(db["specials"]),
830         statedefines,
831     )
832
833     with open(h_name, "w") as hf:
834         hf.write(h)
835
836     with open(c_name, "w") as cf:
837         cf.write(c)
838
839 # end