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