ff48caef108a9a06af49d587b0ec3bd805320a24
[open-adventure.git] / newdungeon.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 import sys, yaml
8
9 yaml_name = "adventure.yaml"
10 h_name = "newdb.h"
11 c_name = "newdb.c"
12
13 statedefines = ""
14
15 h_template = """/* Generated from adventure.yaml - do not hand-hack! */
16 #ifndef NEWDB_H
17 #define NEWDB_H
18
19 #include <stdio.h>
20 #include <stdbool.h>
21
22 #define SILENT  -1      /* no sound */
23
24 /* Symbols for cond bits */
25 #define COND_LIT        0       /* Light */
26 #define COND_OILY       1       /* If bit 2 is on: on for oil, off for water */
27 #define COND_FLUID      2       /* Liquid asset, see bit 1 */
28 #define COND_NOARRR     3       /* Pirate doesn't go here unless following */
29 #define COND_NOBACK     4       /* Cannot use "back" to move away */
30 #define COND_ABOVE      5
31 #define COND_DEEP       6       /* Deep - e.g where dwarves are active */
32 #define COND_FOREST     7       /* In the forest */
33 #define COND_FORCED     8       /* Only one way in or out of here */
34 /* Bits past 10 indicate areas of interest to "hint" routines */
35 #define COND_HBASE      10      /* Base for location hint bits */
36 #define COND_HCAVE      11      /* Trying to get into cave */
37 #define COND_HBIRD      12      /* Trying to catch bird */
38 #define COND_HSNAKE     13      /* Trying to deal with snake */
39 #define COND_HMAZE      14      /* Lost in maze */
40 #define COND_HDARK      15      /* Pondering dark room */
41 #define COND_HWITT      16      /* At Witt's End */
42 #define COND_HCLIFF     17      /* Cliff with urn */
43 #define COND_HWOODS     18      /* Lost in forest */
44 #define COND_HOGRE      19      /* Trying to deal with ogre */
45 #define COND_HJADE      20      /* Found all treasures except jade */
46
47 typedef struct {{
48   const char* inventory;
49   int plac, fixd;
50   bool is_treasure;
51   const char** longs;
52   const char** sounds;
53   const char** texts;
54 }} object_t;
55
56 typedef struct {{
57   const char* small;
58   const char* big;
59 }} descriptions_t;
60
61 typedef struct {{
62   descriptions_t description;
63   const long sound;
64   const bool loud;
65 }} location_t;
66
67 typedef struct {{
68   const char* query;
69   const char* yes_response;
70 }} obituary_t;
71
72 typedef struct {{
73   const int threshold;
74   const int point_loss;
75   const char* message;
76 }} turn_threshold_t;
77
78 typedef struct {{
79   const int threshold;
80   const char* message;
81 }} class_t;
82
83 typedef struct {{
84   const int number;
85   const int turns;
86   const int penalty;
87   const char* question;
88   const char* hint;
89 }} hint_t;
90
91 typedef struct {{
92   const char** words;
93 }} motion_t;
94
95 typedef struct {{
96   const char** words;
97   const long message;
98 }} action_t;
99
100 extern const location_t locations[];
101 extern const object_t objects[];
102 extern const char* arbitrary_messages[];
103 extern const class_t classes[];
104 extern const turn_threshold_t turn_thresholds[];
105 extern const obituary_t obituaries[];
106 extern const hint_t hints[];
107 extern long conditions[];
108 extern const long actspk[];
109 extern const motion_t motions[];
110
111 #define NLOCATIONS      {}
112 #define NOBJECTS        {}
113 #define NHINTS          {}
114 #define NCLASSES        {}
115 #define NDEATHS         {}
116 #define NTHRESHOLDS     {}
117 #define NACTIONS        {}
118 #define NTRAVEL         {}
119
120 enum arbitrary_messages_refs {{
121 {}
122 }};
123
124 enum locations_refs {{
125 {}
126 }};
127
128 enum object_refs {{
129 {}
130 }};
131
132 enum motion_refs {{
133 {}
134 }};
135
136 enum action_refs {{
137 {}
138 }};
139
140 /* State definitions */
141
142 {}
143 #endif /* end NEWDB_H */
144 """
145
146 c_template = """/* Generated from adventure.yaml - do not hand-hack! */
147
148 #include "common.h"
149 #include "{}"
150
151 const char* arbitrary_messages[] = {{
152 {}
153 }};
154
155 const class_t classes[] = {{
156 {}
157 }};
158
159 const turn_threshold_t turn_thresholds[] = {{
160 {}
161 }};
162
163 const location_t locations[] = {{
164 {}
165 }};
166
167 const object_t objects[] = {{
168 {}
169 }};
170
171 const obituary_t obituaries[] = {{
172 {}
173 }};
174
175 const hint_t hints[] = {{
176 {}
177 }};
178
179 long conditions[] = {{
180 {}
181 }};
182
183 const long actspk[] = {{
184     NO_MESSAGE,
185 {}
186 }};
187
188 const motion_t motions[] = {{
189 {}
190 }};
191
192 const action_t actions[] = {{
193 {}
194 }};
195
196 /* end */
197 """
198
199 def make_c_string(string):
200     """Render a Python string into C string literal format."""
201     if string == None:
202         return "NULL"
203     string = string.replace("\n", "\\n")
204     string = string.replace("\t", "\\t")
205     string = string.replace('"', '\\"')
206     string = string.replace("'", "\\'")
207     string = '"' + string + '"'
208     return string
209
210 def get_refs(l):
211     reflist = [x[0] for x in l]
212     ref_str = ""
213     for ref in reflist:
214         ref_str += "    {},\n".format(ref)
215     ref_str = ref_str[:-1] # trim trailing newline
216     return ref_str
217
218 def get_arbitrary_messages(arb):
219     template = """    {},
220 """
221     arb_str = ""
222     for item in arb:
223         arb_str += template.format(make_c_string(item[1]))
224     arb_str = arb_str[:-1] # trim trailing newline
225     return arb_str
226
227 def get_class_messages(cls):
228     template = """    {{
229         .threshold = {},
230         .message = {},
231     }},
232 """
233     cls_str = ""
234     for item in cls:
235         threshold = item["threshold"]
236         message = make_c_string(item["message"])
237         cls_str += template.format(threshold, message)
238     cls_str = cls_str[:-1] # trim trailing newline
239     return cls_str
240
241 def get_turn_thresholds(trn):
242     template = """    {{
243         .threshold = {},
244         .point_loss = {},
245         .message = {},
246     }},
247 """
248     trn_str = ""
249     for item in trn:
250         threshold = item["threshold"]
251         point_loss = item["point_loss"]
252         message = make_c_string(item["message"])
253         trn_str += template.format(threshold, point_loss, message)
254     trn_str = trn_str[:-1] # trim trailing newline
255     return trn_str
256
257 def get_locations(loc):
258     template = """    {{ // {}
259         .description = {{
260             .small = {},
261             .big = {},
262         }},
263         .sound = {},
264         .loud = {},
265     }},
266 """
267     loc_str = ""
268     for (i, item) in enumerate(loc):
269         short_d = make_c_string(item[1]["description"]["short"])
270         long_d = make_c_string(item[1]["description"]["long"])
271         sound = item[1].get("sound", "SILENT")
272         loud = "true" if item[1].get("loud") else "false"
273         loc_str += template.format(i, short_d, long_d, sound, loud)
274     loc_str = loc_str[:-1] # trim trailing newline
275     return loc_str
276
277 def get_objects(obj):
278     template = """    {{ // {}
279         .inventory = {},
280         .plac = {},
281         .fixd = {},
282         .is_treasure = {},
283         .longs = (const char* []) {{
284 {}
285         }},
286         .sounds = (const char* []) {{
287 {}
288         }},
289         .texts = (const char* []) {{
290 {}
291         }},
292     }},
293 """
294     obj_str = ""
295     for (i, item) in enumerate(obj):
296         attr = item[1]
297         i_msg = make_c_string(attr["inventory"])
298         longs_str = ""
299         if attr["longs"] == None:
300             longs_str = " " * 12 + "NULL,"
301         else:
302             labels = []
303             for l_msg in attr["longs"]:
304                 if not isinstance(l_msg, str):
305                     labels.append(l_msg)
306                     l_msg = l_msg[1]
307                 longs_str += " " * 12 + make_c_string(l_msg) + ",\n"
308             longs_str = longs_str[:-1] # trim trailing newline
309             if labels:
310                 global statedefines
311                 statedefines += "/* States for %s */\n" % item[0]
312                 for (i, (label, message)) in enumerate(labels):
313                     if len(message) >= 45:
314                         message = message[:45] + "..."
315                     statedefines += "#define %s\t%d /* %s */\n" % (label, i, message)
316                 statedefines += "\n"
317         sounds_str = ""
318         if attr.get("sounds") == None:
319             sounds_str = " " * 12 + "NULL,"
320         else:
321              for l_msg in attr["sounds"]:
322                  sounds_str += " " * 12 + make_c_string(l_msg) + ",\n"
323              sounds_str = sounds_str[:-1] # trim trailing newline
324         texts_str = ""
325         if attr.get("texts") == None:
326             texts_str = " " * 12 + "NULL,"
327         else:
328              for l_msg in attr["texts"]:
329                  texts_str += " " * 12 + make_c_string(l_msg) + ",\n"
330              texts_str = texts_str[:-1] # trim trailing newline
331         locs = attr.get("locations", ["LOC_NOWHERE", "LOC_NOWHERE"])
332         immovable = attr.get("immovable", False)
333         try:
334             if type(locs) == str:
335                 locs = [locnames.index(locs), -1 if immovable else 0]
336             else:
337                 locs = [locnames.index(x) for x in locs]
338         except IndexError:
339             sys.stderr.write("dungeon: unknown object location in %s\n" % locs)
340             sys.exit(1)
341         treasure = "true" if attr.get("treasure") else "false"
342         obj_str += template.format(i, i_msg, locs[0], locs[1], treasure, longs_str, sounds_str, texts_str)
343     obj_str = obj_str[:-1] # trim trailing newline
344     return obj_str
345
346 def get_obituaries(obit):
347     template = """    {{
348         .query = {},
349         .yes_response = {},
350     }},
351 """
352     obit_str = ""
353     for o in obit:
354         query = make_c_string(o["query"])
355         yes = make_c_string(o["yes_response"])
356         obit_str += template.format(query, yes)
357     obit_str = obit_str[:-1] # trim trailing newline
358     return obit_str
359
360 def get_hints(hnt, arb):
361     template = """    {{
362         .number = {},
363         .penalty = {},
364         .turns = {},
365         .question = {},
366         .hint = {},
367     }},
368 """
369     hnt_str = ""
370     md = dict(arb)
371     for member in hnt:
372         item = member["hint"]
373         number = item["number"]
374         penalty = item["penalty"]
375         turns = item["turns"]
376         question = make_c_string(item["question"])
377         hint = make_c_string(item["hint"])
378         hnt_str += template.format(number, penalty, turns, question, hint)
379     hnt_str = hnt_str[:-1] # trim trailing newline
380     return hnt_str
381
382 def get_condbits(locations):
383     cnd_str = ""
384     for (name, loc) in locations:
385         conditions = loc["conditions"]
386         hints = loc.get("hints") or []
387         flaglist = []
388         for flag in conditions:
389             if conditions[flag]:
390                 flaglist.append(flag)
391         line = "|".join([("(1<<COND_%s)" % f) for f in flaglist])
392         trail = "|".join([("(1<<COND_H%s)" % f['name']) for f in hints])
393         if trail:
394             line += "|" + trail
395         if line.startswith("|"):
396             line = line[1:]
397         if not line:
398             line = "0"
399         cnd_str += "    " + line + ",\t// " + name + "\n"
400     return cnd_str
401
402 def recompose(type_word, value):
403     "Compose the internal code for a vocabulary word from its YAML entry"
404     parts = ("motion", "action", "object", "special")
405     try:
406         return value + 1000 * parts.index(type_word)
407     except KeyError:
408         sys.stderr.write("dungeon: %s is not a known word\n" % word)
409         sys.exit(1)
410     except IndexError:
411         sys.stderr.write("%s is not a known word classifier\n" % attrs["type"])
412         sys.exit(1)
413
414 def get_actspk(actspk):
415     res = ""
416     for (i, word) in actspk.items():
417         res += "    %s,\n" % word
418     return res
419
420 def buildtravel(locs, objs, voc):
421     ltravel = []
422     lkeys = []
423     verbmap = {}
424     for entry in db["vocabulary"]:
425         if entry["type"] == "motion" and entry["value"] not in verbmap:
426             verbmap[entry["word"]] = entry["value"]
427     def dencode(action, name):
428         "Decode a destination number"
429         if action[0] == "goto":
430             try:
431                 return locnames.index(action[1])
432             except ValueError:
433                 sys.stderr.write("dungeon: unknown location %s in goto clause of %s\n" % (cond[1], name))
434         elif action[0] == "special":
435             return 300 + action[1]
436         elif action[0] == "speak":
437             try:
438                 return 500 + msgnames.index(action[1])
439             except ValueError:
440                 sys.stderr.write("dungeon: unknown location %s in carry clause of %s\n" % (cond[1], name))
441         else:
442             print(cond)
443             raise ValueError
444     def cencode(cond, name):
445         if cond is None:
446             return 0;
447         elif cond[0] == "pct":
448             return cond[1]
449         elif cond[0] == "carry":
450             try:
451                 return 100 + objnames.index(cond[1])
452             except ValueError:
453                 sys.stderr.write("dungeon: unknown object name %s in carry clause of %s\n" % (cond[1], name))
454                 sys.exit(1)
455         elif cond[0] == "with":
456             try:
457                 return 200 + objnames.index(cond[1])
458             except IndexError:
459                 sys.stderr.write("dungeon: unknown object name %s in with clause of \n" % (cond[1], name))
460                 sys.exit(1)
461         elif cond[0] == "not":
462             # FIXME: Allow named as well as numbered states
463             try:
464                 return 300 + objnames.index(cond[1]) + 100 * cond[2]
465             except ValueError:
466                 sys.stderr.write("dungeon: unknown object name %s in not clause of %s\n" % (cond[1], name))
467                 sys.exit(1)
468         else:
469             print(cond)
470             raise ValueError
471     # Much more to be done here
472     for (i, (name, loc)) in enumerate(locs):
473         if "travel" in loc:
474             for rule in loc["travel"]:
475                 tt = [i]
476                 dest = dencode(rule["action"], name) + 1000 * cencode(rule.get("cond"), name)
477                 tt.append(dest)
478                 tt += [verbmap[e] for e in rule["verbs"]]
479                 if not rule["verbs"]:
480                     tt.append(1)
481                 ltravel.append(tuple(tt))
482     return (tuple(ltravel), lkeys)
483
484 def get_motions(motions):
485     template = """    {{
486         .words = {},
487     }},
488 """
489     mot_str = ""
490     for motion in motions:
491         contents = motion[1]
492         if contents["words"] == None:
493             mot_str += template.format("NULL")
494             continue
495         c_words = [make_c_string(s) for s in contents["words"]]
496         words_str = "(const char* []) {" + ", ".join(c_words) + "}"
497         mot_str += template.format(words_str)
498     return mot_str
499
500 def get_actions(actions):
501     template = """    {{
502         .words = {},
503         .message = {},
504     }},
505 """
506     act_str = ""
507     for action in actions:
508         contents = action[1]
509         
510         if contents["words"] == None:
511             words_str = "NULL"
512         else:
513             c_words = [make_c_string(s) for s in contents["words"]]
514             words_str = "(const char* []) {" + ", ".join(c_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     act_str = act_str[:-1] # trim trailing newline
523     return act_str
524
525 if __name__ == "__main__":
526     with open(yaml_name, "r") as f:
527         db = yaml.load(f)
528
529     locnames = [x[0] for x in db["locations"]]
530     msgnames = [el[0] for el in db["arbitrary_messages"]]
531     objnames = [el[0] for el in db["objects"]]
532     (travel, key) = buildtravel(db["locations"], db["objects"], db["vocabulary"])
533     # FIXME: pack the Section 3 representation into the runtime format.
534
535     c = c_template.format(
536         h_name,
537         get_arbitrary_messages(db["arbitrary_messages"]),
538         get_class_messages(db["classes"]),
539         get_turn_thresholds(db["turn_thresholds"]),
540         get_locations(db["locations"]),
541         get_objects(db["objects"]),
542         get_obituaries(db["obituaries"]),
543         get_hints(db["hints"], db["arbitrary_messages"]),
544         get_condbits(db["locations"]),
545         get_actspk(db["actspk"]),
546         get_motions(db["motions"]),
547         get_actions(db["actions"]),
548     )
549
550     h = h_template.format(
551         len(db["locations"])-1,
552         len(db["objects"])-1,
553         len(db["hints"]),
554         len(db["classes"])-1,
555         len(db["obituaries"]),
556         len(db["turn_thresholds"]),
557         len(db["actspk"]),
558         len(travel),
559         get_refs(db["arbitrary_messages"]),
560         get_refs(db["locations"]),
561         get_refs(db["objects"]),
562         get_refs(db["motions"]),
563         get_refs(db["actions"]),
564         statedefines,
565     )
566
567     with open(h_name, "w") as hf:
568         hf.write(h)
569
570     with open(c_name, "w") as cf:
571         cf.write(c)
572
573 # end