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