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