Graph mode for maze all different.
[open-adventure.git] / make_graph.py
1 #!/usr/bin/env python3
2 """\
3 usage: make-graph.py [-a] -d] [-m] [-s]
4
5 Make a DOT graph of Colossal Cave.
6
7 -a = emit graph of entire dungeon
8 -d = emit graoh of mazw all different
9 -m = emit graph of maze all alike
10 -s = emit graph of surface locations
11 """
12 # Copyright (c) 2017 by Eric S. Raymond
13 # SPDX-License-Identifier: BSD-2-clause
14
15 import sys, yaml, getopt
16
17 def allalike(loc):
18     "Select out loci related to the Maze All Alike"
19     return ("ALIKE" in loc) or (loc == "LOC_PITBRINK") or ("MAZEEND" in loc) or ("STALACTITE" in loc)
20
21 def alldifferent(loc):
22     "Select out loci related to the Maze All Alike"
23     return ("DIFFERENT" in loc) or (loc == "LOC_DEADEND13")
24
25 def surface(attrs):
26     "Select out surface locations"
27     if ("ABOVE" in attrs["conditions"]) and attrs["conditions"]["ABOVE"]:
28         return True
29     if ("FOREST" in attrs["conditions"]) and attrs["conditions"]["FOREST"]:
30         return True
31     return False
32
33 def abbreviate(d):
34     m = {"NORTH":"N", "EAST":"E", "SOUTH":"S", "WEST":"W", "UPWAR":"U", "DOWN":"D"}
35     return m.get(d, d)
36
37 def roomlabel(loc):
38     "Generate a room label from the description, if possible"
39     loc_descriptions = location_lookup[loc]['description']
40     description = loc[4:]
41     short = loc_descriptions["short"]
42     maptag = loc_descriptions["maptag"]
43     if short is not None:
44         if short.startswith("You're "):
45             short = short[7:]
46         if short.startswith("You are "):
47             short = short[8 :]
48         if short.startswith("in ") or short.startswith("at ") or short.startswith("on "):
49             short = short[3:]
50         if short[:3] in {"n/s", "e/w"}:
51             short = short[:3].upper() + short[3:]
52         elif short[:2] in {"ne", "sw", "se", "nw"}:
53             short = short[:2].upper() + short[2:]
54         else:
55             short = short[0].upper() + short[1:]
56     elif loc_descriptions["maptag"] is not None:
57         short = loc_descriptions["maptag"]
58     elif loc_descriptions["long"] is not None and len(loc_descriptions["long"]) < 20:
59         short = loc_descriptions["long"]
60     if short is not None:
61         description += "\\n" + short
62     return description
63
64 # A forwarder is a location tat you can't actually stop in - when you go there
65 # it ships some message (which is the point) then shifts you to a nexr location.
66 # A forwarder has a zero-length array of notion verbs in its travel section.
67 #
68 # Here is an examoke forwarder kocation:
69 #
70 # - LOC_GRUESOME:
71 #    description:
72 #      long: 'There is now one more gruesome aspect to the spectacular vista.'
73 #      short: !!null
74 #      maptag: !!null
75 #    conditions: {DEEP: true}
76 #    travel: [
77 #      {verbs: [], action: [goto, LOC_NOWHERE]},
78 #    ]
79
80 def is_forwarder(loc):
81     "Is a location a forwarder?"
82     travel = location_lookup[loc]['travel']
83     return len(travel) == 1 and len(travel[0]['verbs']) == 0
84
85 def forward(loc):
86     "Chase a location through forwarding links."
87     while is_forwarder(loc):
88         loc = location_lookup[loc]["travel"][0]["action"][1]
89     return loc
90
91 if __name__ == "__main__":
92     with open("adventure.yaml", "r") as f:
93         db = yaml.safe_load(f)
94
95     location_lookup = dict(db["locations"])
96
97     try:
98         (options, arguments) = getopt.getopt(sys.argv[1:], "adms")
99     except getopt.GetoptError as e:
100         print(e)
101         sys.exit(1)
102
103     subset = "maze"
104     for (switch, val) in options:
105         if switch == '-a':
106             subset = "all"
107         elif switch == '-d':
108             subset = "different"
109         elif switch == '-m':
110             subset = "maze"
111         elif switch == '-s':
112             subset = "surface"
113         else:
114             sys.stderr.write(__doc__)
115             raise SystemExit(1)        
116
117     startlocs = {}
118     for obj in db["objects"]:
119         objname = obj[0]
120         location = obj[1].get("locations")
121         if "OBJ" not in objname and location != "LOC_NOWHERE" and ("immovable" not in obj[1] or not obj[1]["immovable"]):
122             if location in startlocs:
123                 startlocs[location].append(objname)
124             else:
125                 startlocs[location] = [objname]
126
127     startlocs = {}
128     for obj in db["objects"]:
129         objname = obj[0]
130         location = obj[1].get("locations")
131         if "OBJ" not in objname and location != "LOC_NOWHERE" and ("immovable" not in obj[1] or not obj[1]["immovable"]):
132             if location in startlocs:
133                 startlocs[location].append(objname)
134             else:
135                 startlocs[location] = [objname]
136
137     print("digraph G {")
138     
139     for (loc, attrs) in db["locations"]:
140         if is_forwarder(loc):
141             continue
142         if subset == "surface" and not surface(attrs):
143             continue
144         if subset == "maze" and not allalike(loc):
145             continue;
146         if subset == "different" and not alldifferent(loc):
147             continue;
148         node_label = roomlabel(loc)
149         if loc in startlocs:
150             node_label += "\\n" + ",".join(startlocs[loc]).lower()
151         print('    %s [shape=box,label="%s"]' % (loc[4:], node_label))
152         
153     for (loc, attrs) in db["locations"]:        
154         if subset == "surface" and not surface(attrs):
155             continue
156         travel = attrs["travel"]
157         if len(travel) > 0:
158             for dest in travel:
159                 verbs = [abbreviate(x) for x in dest["verbs"]]
160                 if len(verbs) == 0:
161                     continue
162                 action = dest["action"]
163                 if action[0] == "goto":
164                     dest = forward(action[1])
165                     if subset == "maze" and not (allalike(loc) or allalike(dest)):
166                         continue;
167                     if subset == "different" and not (alldifferent(loc) or alldifferent(dest)):
168                         continue;
169                     arc = "%s -> %s" % (loc[4:], dest[4:])
170                     label=",".join(verbs).lower()
171                     if len(label) > 0:
172                         arc += ' [label="%s"]' % label
173                     print("    " + arc)
174     print("}")
175
176 # end