Introduce and use matags in the YAML.
[open-adventure.git] / make_graph.py
1 #!/usr/bin/env python3
2 """\
3 usage: make-graph.py [-a] [-m] [-s]
4
5 Make a DOT graph of Colossal Cave
6
7 -a = emit graph of entire dungeon
8 -m = emit graph of maze all alike
9 -s = emit graph of surface locations
10 """
11 # Copyright (c) 2017 by Eric S. Raymond
12 # SPDX-License-Identifier: BSD-2-clause
13
14 import sys, yaml, getopt
15
16 def allalike(loc):
17     "Select out loci related to the Maze All Alike"
18     return ("ALIKE" in loc) or (loc == "LOC_PITBRINK") or ("MAZEEND" in loc) or ("STALACTITE" in loc)
19
20 def surface(attrs):
21     "Select out surface locations"
22     if ("ABOVE" in attrs["conditions"]) and attrs["conditions"]["ABOVE"]:
23         return True
24     if ("FOREST" in attrs["conditions"]) and attrs["conditions"]["FOREST"]:
25         return True
26     return False
27
28 def abbreviate(d):
29     m = {"NORTH":"N", "EAST":"E", "SOUTH":"S", "WEST":"W", "UPWAR":"U", "DOWN":"D"}
30     return m.get(d, d)
31
32 def roomlabel(loc):
33     "Generate a room label from the description, if possible"
34     loc_descriptions = dict(db["locations"])[loc]['description']
35     description = loc[4:]
36     short = loc_descriptions["short"]
37     maptag = loc_descriptions["maptag"]
38     if short is not None:
39         if short.startswith("You're "):
40             short = short[7:]
41         if short.startswith("You are "):
42             short = short[8 :]
43         if short.startswith("in ") or short.startswith("at ") or short.startswith("on "):
44             short = short[3:]
45         if short[:3] in {"n/s", "e/w"}:
46             short = short[:3].upper() + short[3:]
47         elif short[:2] in {"ne", "sw", "se", "nw"}:
48             short = short[:2].upper() + short[2:]
49         else:
50             short = short[0].upper() + short[1:]
51     elif loc_descriptions["maptag"] is not None:
52         short = loc_descriptions["maptag"]
53     elif loc_descriptions["long"] is not None and len(loc_descriptions["long"]) < 20:
54         short = loc_descriptions["long"]
55     if short is not None:
56         description += "\\n" + short
57     return description
58
59 if __name__ == "__main__":
60     with open("adventure.yaml", "r") as f:
61         db = yaml.safe_load(f)
62
63     try:
64         (options, arguments) = getopt.getopt(sys.argv[1:], "ams")
65     except getopt.GetoptError as e:
66         print(e)
67         sys.exit(1)
68
69     subset = "maze"
70     for (switch, val) in options:
71         if switch == '-a':
72             subset = "all"
73         elif switch == '-m':
74             subset = "maze"
75         elif switch == '-s':
76             subset = "surface"
77         else:
78             sys.stderr.write(__doc__)
79             raise SystemExit(1)        
80
81     startlocs = {}
82     for obj in db["objects"]:
83         objname = obj[0]
84         location = obj[1].get("locations")
85         if "OBJ" not in objname and location != "LOC_NOWHERE" and ("immovable" not in obj[1] or not obj[1]["immovable"]):
86             if location in startlocs:
87                 startlocs[location].append(objname)
88             else:
89                 startlocs[location] = [objname]
90
91     startlocs = {}
92     for obj in db["objects"]:
93         objname = obj[0]
94         location = obj[1].get("locations")
95         if "OBJ" not in objname and location != "LOC_NOWHERE" and ("immovable" not in obj[1] or not obj[1]["immovable"]):
96             if location in startlocs:
97                 startlocs[location].append(objname)
98             else:
99                 startlocs[location] = [objname]
100
101     print("digraph G {")
102     
103     for (loc, attrs) in db["locations"]:        
104         if subset == "surface" and not surface(attrs):
105             continue
106         if subset == "maze" and not allalike(loc):
107             continue;
108         node_label = roomlabel(loc)
109         if loc in startlocs:
110             node_label += "\\n" + ",".join(startlocs[loc]).lower()
111         print('    %s [shape=box,label="%s"]' % (loc[4:], node_label))
112         
113     for (loc, attrs) in db["locations"]:        
114         if subset == "surface" and not surface(attrs):
115             continue
116         travel = attrs["travel"]
117         if len(travel) > 0:
118             for dest in travel:
119                 verbs = [abbreviate(x) for x in dest["verbs"]]
120                 if len(verbs) == 0:
121                     continue
122                 action = dest["action"]
123                 if action[0] == "goto":
124                     dest = action[1]
125                     if subset == "maze" and not (allalike(loc) or allalike(dest)):
126                         continue;
127                     arc = "%s -> %s" % (loc[4:], dest[4:])
128                     label=",".join(verbs).lower()
129                     if len(label) > 0:
130                         arc += ' [label="%s"]' % label
131                     print("    " + arc)
132     print("}")