Add verbose optionm to grapher.
[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 -v = include internal sy,no;s in room labels
12 """
13 # Copyright (c) 2017 by Eric S. Raymond
14 # SPDX-License-Identifier: BSD-2-clause
15
16 import sys, getopt, yaml
17
18 def allalike(loc):
19     "Select out loci related to the Maze All Alike"
20     return ("ALIKE" in loc) or (loc == "LOC_PITBRINK") or ("MAZEEND" in loc) or ("STALACTITE" in loc)
21
22 def alldifferent(loc):
23     "Select out loci related to the Maze All Alike"
24     return ("DIFFERENT" in loc) or (loc == "LOC_DEADEND13")
25
26 def surface(loc):
27     "Select out surface locations"
28     attrs = location_lookup[loc]
29     if ("ABOVE" in attrs["conditions"]) and attrs["conditions"]["ABOVE"]:
30         return True
31     if ("FOREST" in attrs["conditions"]) and attrs["conditions"]["FOREST"]:
32         return True
33     return False
34
35 def abbreviate(d):
36     m = {"NORTH":"N", "EAST":"E", "SOUTH":"S", "WEST":"W", "UPWAR":"U", "DOWN":"D"}
37     return m.get(d, d)
38
39 def roomlabel(loc):
40     "Generate a room label from the description, if possible"
41     loc_descriptions = location_lookup[loc]['description']
42     description = ""
43     if debug:
44         description = loc[4:]
45     longd = loc_descriptions["long"]
46     short = loc_descriptions["maptag"] or loc_descriptions["short"]
47     if short is None and longd is not None and len(longd) < 20:
48         short = loc_descriptions["long"]
49     if short is not None:
50         if short.startswith("You're "):
51             short = short[7:]
52         if short.startswith("You are "):
53             short = short[8 :]
54         if short.startswith("in ") or short.startswith("at ") or short.startswith("on "):
55             short = short[3:]
56         if short.startswith("the "):
57             short = short[4:]
58         if short[:3] in {"n/s", "e/w"}:
59             short = short[:3].upper() + short[3:]
60         elif short[:2] in {"ne", "sw", "se", "nw"}:
61             short = short[:2].upper() + short[2:]
62         else:
63             short = short[0].upper() + short[1:]
64         if debug:
65             description += "\\n"
66         description += short
67         if loc in startlocs:
68             description += "\\n(" + ",".join(startlocs[loc]).lower() + ")"
69     return description
70
71 # A forwarder is a location that you can't actually stop in - when you go there
72 # it ships some message (which is the point) then shifts you to a nexr location.
73 # A forwarder has a zero-length array of notion verbs in its travel section.
74 #
75 # Here is an example forwarder declaration:
76 #
77 # - LOC_GRUESOME:
78 #    description:
79 #      long: 'There is now one more gruesome aspect to the spectacular vista.'
80 #      short: !!null
81 #      maptag: !!null
82 #    conditions: {DEEP: true}
83 #    travel: [
84 #      {verbs: [], action: [goto, LOC_NOWHERE]},
85 #    ]
86
87 def is_forwarder(loc):
88     "Is a location a forwarder?"
89     travel = location_lookup[loc]['travel']
90     return len(travel) == 1 and len(travel[0]['verbs']) == 0
91
92 def forward(loc):
93     "Chase a location through forwarding links."
94     while is_forwarder(loc):
95         loc = location_lookup[loc]["travel"][0]["action"][1]
96     return loc
97
98 if __name__ == "__main__":
99     with open("adventure.yaml", "r") as f:
100         db = yaml.safe_load(f)
101
102     location_lookup = dict(db["locations"])
103
104     try:
105         (options, arguments) = getopt.getopt(sys.argv[1:], "admsv")
106     except getopt.GetoptError as e:
107         print(e)
108         sys.exit(1)
109
110     subset = allalike
111     debug = False
112     for (switch, val) in options:
113         if switch == '-a':
114             subset = lambda loc: True
115         elif switch == '-d':
116             subset = alldifferent
117         elif switch == '-m':
118             subset = allalike
119         elif switch == '-s':
120             subset = surface
121         elif switch == '-v':
122             debug = True
123         else:
124             sys.stderr.write(__doc__)
125             raise SystemExit(1)
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     # Compute reachability, using forwards.
138     # Dictionary ke6y is (from, to) iff its a valid link,
139     # value is correspoinding motion verbs.
140     links = {}
141     nodes = set()
142     for (loc, attrs) in db["locations"]:
143         nodes.add(loc)
144         travel = attrs["travel"]
145         if len(travel) > 0:
146             for dest in travel:
147                 verbs = [abbreviate(x) for x in dest["verbs"]]
148                 if len(verbs) == 0:
149                     continue
150                 action = dest["action"]
151                 if action[0] == "goto":
152                     dest = forward(action[1])
153                     if not (subset(loc) or subset(dest)):
154                         continue
155                     links[(loc, dest)] = verbs
156
157     neighbors = set()
158     for loc in nodes:
159         for (f, t) in links:
160             if f == 'LOC_NOWHERE' or t == 'LOC_NOWHERE':
161                 continue
162             if (f == loc and subset(t)) or (t == loc and subset(f)):
163                 if loc not in neighbors:
164                     neighbors.add(loc)
165
166     print("digraph G {")
167
168     for loc in nodes:
169         if is_forwarder(loc):
170             continue
171         node_label = roomlabel(loc)
172         if subset(loc):
173             print('    %s [shape=box,label="%s"]' % (loc[4:], node_label))
174         elif loc in neighbors:
175             print('    %s [label="%s"]' % (loc[4:], node_label))
176
177     # Draw arcs
178     for (f, t) in links:
179         arc = "%s -> %s" % (f[4:], t[4:])
180         label=",".join(links[(f, t)]).lower()
181         if len(label) > 0:
182             arc += ' [label="%s"]' % label
183         print("    " + arc)
184     print("}")
185
186 # end