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