py;imt cleanup.
[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 def reveal(objname):
99     "Should this object be revealed when mappinmg?"
100     if "OBJ_" in objname:
101         return False
102     if objname == "VEND":
103         return True
104     obj = object_lookup[objname]
105     return not obj.get("immovable")
106
107 if __name__ == "__main__":
108     with open("adventure.yaml", "r") as f:
109         db = yaml.safe_load(f)
110
111     location_lookup = dict(db["locations"])
112     object_lookup = dict(db["objects"])
113
114     try:
115         (options, arguments) = getopt.getopt(sys.argv[1:], "admsv")
116     except getopt.GetoptError as e:
117         print(e)
118         sys.exit(1)
119
120     subset = allalike
121     debug = False
122     for (switch, val) in options:
123         if switch == '-a':
124             subset = lambda loc: True
125         elif switch == '-d':
126             subset = alldifferent
127         elif switch == '-m':
128             subset = allalike
129         elif switch == '-s':
130             subset = surface
131         elif switch == '-v':
132             debug = True
133         else:
134             sys.stderr.write(__doc__)
135             raise SystemExit(1)
136
137     startlocs = {}
138     for obj in db["objects"]:
139         objname = obj[0]
140         location = obj[1].get("locations")
141         if location != "LOC_NOWHERE" and reveal(objname):
142             if location in startlocs:
143                 startlocs[location].append(objname)
144             else:
145                 startlocs[location] = [objname]
146
147     # Compute reachability, using forwards.
148     # Dictionary ke6y is (from, to) iff its a valid link,
149     # value is correspoinding motion verbs.
150     links = {}
151     nodes = []
152     for (loc, attrs) in db["locations"]:
153         nodes.append(loc)
154         travel = attrs["travel"]
155         if len(travel) > 0:
156             for dest in travel:
157                 verbs = [abbreviate(x) for x in dest["verbs"]]
158                 if len(verbs) == 0:
159                     continue
160                 action = dest["action"]
161                 if action[0] == "goto":
162                     dest = forward(action[1])
163                     if not (subset(loc) or subset(dest)):
164                         continue
165                     links[(loc, dest)] = verbs
166
167     neighbors = set()
168     for loc in nodes:
169         for (f, t) in links:
170             if f == 'LOC_NOWHERE' or t == 'LOC_NOWHERE':
171                 continue
172             if (f == loc and subset(t)) or (t == loc and subset(f)):
173                 if loc not in neighbors:
174                     neighbors.add(loc)
175
176     print("digraph G {")
177
178     for loc in nodes:
179         if not is_forwarder(loc):
180             node_label = roomlabel(loc)
181             if subset(loc):
182                 print('    %s [shape=box,label="%s"]' % (loc[4:], node_label))
183             elif loc in neighbors:
184                 print('    %s [label="%s"]' % (loc[4:], node_label))
185
186     # Draw arcs
187     for (f, t) in links:
188         arc = "%s -> %s" % (f[4:], t[4:])
189         label=",".join(links[(f, t)]).lower()
190         if len(label) > 0:
191             arc += ' [label="%s"]' % label
192         print("    " + arc)
193     print("}")
194
195 # end