-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.py
337 lines (283 loc) · 10.8 KB
/
game.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
'''
Module representing in-game objects
* Collectible
|- Expansion
|- Item
* Room
* World
* Database
* Game
'''
import os
import json
from copy import deepcopy
import configuration as config
import parsing
import graph
class Collectible:
'''
Represents an in-game collectible.
A collectible has a kind and possibly a description on collecting
it and a list of dependencies
'''
def __init__(self, kind, room, world,
info=None, weight=None, deps=None):
'''Internalizes parameters'''
self.kind = kind
self.info = info
self.room = room
self.world = world
if weight is not None:
self.weight = weight
else:
self.weight = config.get("WEIGHT_MAP")[self.kind]
self.deps = [] if deps is None else deps
@property
def _extra(self):
'''Returns formatted string of possibly-None variables'''
weight = ' [%d] ' % self.weight
deps = ' (%s)' % ', '.join(str(d) for d in self.deps)
loc = ' in (%s, %s)' % (self.room, self.world)
info = '\n - %s' % self.info if self.info is not None else ''
return weight + deps + loc + info
def __eq__(self, other):
'''Compare self and other for equality'''
if isinstance(other, dict):
return (self.kind == other['kind'] and
(self.info == other['how'] or
self.info is None and other['how'] == '') and
self.room == other['room'] and
self.world == other['world'] and
self.weight == other['weight'])
return (self.kind == other.kind and
self.info == other.info and
self.room == other.room and
self.world == other.world and
self.weight == other.weight and
self.deps == other.deps)
class Expansion(Collectible):
'''
Category of collectibles that appear many times,
each without a specific name
'''
def __init__(self, kind, room, world,
info=None, weight=None, deps=None):
'''Internalizes parameters'''
super().__init__(kind, room, world, info, weight, deps)
def __str__(self):
'''Return formatted string holding contents of self'''
return ' * %s%s' % (self.kind, self._extra)
class Item(Collectible):
'''
Category of unique collectibles that appear once,
each with a specific name
'''
def __init__(self, name, kind, room, world,
info=None, weight=None, deps=None):
'''Internalizes parameters'''
super().__init__(kind, room, world, info, weight, deps)
self.name = name
def __str__(self):
'''Return formatted string holding contents of self'''
return ' * %s: %s%s' % (self.kind, self.name, self._extra)
def __eq__(self, other):
'''Compare self and other for equality'''
if super().__eq__(other):
if isinstance(other, dict):
return self.name == other['name']
return self.name == other.name
return False
class Room:
'''
Represents an in-game Room that holds collectibles and has adjacencies
'''
def __init__(self,
name,
world=None,
collectibles=None,
adjacencies=None,
dependencies=None):
'''Internalizes parameters'''
self.name = name
self.world = world
self.collectibles = collectibles if collectibles is not None else []
self.adjacencies = adjacencies if adjacencies is not None else []
self.dependencies = dependencies if dependencies is not None else []
@property
def numCollectibles(self):
'''Return number of collectibles within self'''
return len(self.collectibles)
@property
def numAdjacencies(self):
'''Return number of rooms adjacent to self'''
return len(self.adjacencies)
@property
def elevator(self):
'''
Return True if self is a room with an adjacent room in another world
'''
return any(r[2] != self.world
for r in self.adjacencies if r[2] is not None)
def addCollectible(self, collectible):
'''Adds collectible to self'''
self.collectibles.append(collectible)
def addAdjacency(self, adjacency):
'''Adds adjacency to self'''
self.adjacencies.append(adjacency)
def __eq__(self, other):
'''Return True iff self is equal to other'''
return self.name == other.name and self.world == other.world
def __str__(self):
'''Return formatted string holding contents of self'''
c = ''
if len(self.collectibles) > 0:
c = '\n'.join(str(c) for c in self.collectibles) + '\n'
return '> %s\n%s | %s\n' % (self.name,
c,
', '.join(str(a) for a in self.adjacencies))
class World:
'''Represents an in-game world - a set of interconnected Rooms'''
def __init__(self, name):
'''Internalizes parameters'''
self.name = name
self.rooms = []
@property
def numRooms(self):
'''Return number of Rooms in self'''
return len(self.rooms)
def addRoom(self, room):
'''Adds room to self'''
self.rooms.append(room)
def __str__(self):
'''Return formatted string holding contents of self'''
return '*** %s ***\n\n%s\n' % (self.name,
'\n'.join(str(r) for r in self.rooms))
def __contains__(self, room):
'''Return True iff room contained in world'''
return room in self.rooms
def __iter__(self):
'''Maintains iteration over self'''
self.rooms.__iter__()
class Database:
'''Mechanism for storing and querying items'''
def __init__(self, entries=None):
'''Initializes query parser and internalizes dictlist'''
self.parser = parsing.QueryParser()
self.entries = entries if entries is not None else []
@staticmethod
def fromWorlds(worlds, assume_not_found=True):
'''Construct and return database from list of worlds'''
entries = []
for world in worlds:
for room in world.rooms:
for c in room.collectibles:
entry = {'found' : not assume_not_found,
'world' : c.world,
'kind' : c.kind,
'room' : c.room}
entry['how'] = c.info if c.info is not None else ''
if isinstance(c, Item):
entry['name'] = c.name
entries.append(entry)
return Database(entries)
@property
def collected(self):
'''Returns list of collected items'''
return self.filter(lambda i: i['found'] == True)
@property
def uncollected(self):
'''Returns list of uncollected items'''
return self.filter(lambda i: i['found'] == False)
@property
def upgrades(self):
'''Returns list of collected upgrades'''
return self.filter(lambda item: item['found'] == True and
item['kind'] == 'Upgrade')
@property
def percent_complete(self):
'''Return percent of collectibles acquired'''
return len(self.collected) / len(self)
@property
def deepcopy(self):
'''Return deep copy of database'''
return Database(deepcopy(self.entries))
def canPickup(self, collectible):
'''
Return True iff collectible can be picked up, that is, all its
dependencies are satisfied
'''
return all(d in self for d in collectible.deps)
def pickup(self, collectible):
'''Update found status of corresponding database entry to True'''
updated = False
for idx, entry in enumerate(self.entries):
if entry['found']:
continue
if collectible.__eq__(entry):
updated = True
entry['found'] = True
break
assert(updated)
def sort(self, key=None, reverse=False):
'''Sort items in-place by key and reverse flag'''
self.entries.sort(key=key, reverse=reverse)
def sorted(self, key=None, reverse=False):
'''Return sorted copy of items by key and reverse flag'''
return sorted(self.entries, key=key, reverse=reverse)
def __contains__(self, collectible):
'''Return True iff collectible in database'''
raise NotImplementedError('TODO')
def __len__(self):
'''Return number of items in self'''
return len(self.entries)
def __str__(self):
'''Return line-separated items in self'''
return '\n'.join(str(i) for i in self.entries)
def __repr__(self):
''''Return database in JSON-like notation'''
core = '\n'.join(str(i) for i in self.entries)
return '{\n\"itemlist\":[\n%s\n]\n}' % core
def read(self, filename):
'''Parse items in filename into database'''
with open(filename, 'r') as f:
self.entries = json.load(f)['itemlist']
def write(self, filename):
'''Write database to source'''
with open(filename, 'w') as f:
json.dump({'itemlist' : self.entries}, f, indent=2)
def query(self, string, exclude_found, update):
'''Query database for all items satisfying constraints'''
func = self.parser.parse(string)
if exclude_found:
test = lambda x : func(x) and x['found'] == False
else:
test = func
if update:
for idx, e in enumerate(self.entries):
if test(e):
self.entries[idx]['found'] = True
return self.filter(test)
def filter(self, func):
'''Filter database for all items for which func returns True'''
return [e for e in self.entries if func(e)]
class Game:
'''
Top-level representation of a game's internals such as
map, collectibles, and player progress
'''
def __init__(self, config_file):
'''Load configuration and load game data as graph'''
config.loadConfiguration(config_file)
worlds = parsing.DataParser(config.get('GAME_DATA')).parse()
self.graph = graph.Graph.fromWorlds(worlds)
if not os.path.exists(config.get('DATABASE')):
self.database = Database.fromWorlds(worlds)
self.database.write(config.get('DATABASE'))
else:
self.database = Database()
self.database.read(config.get('DATABASE'))
@property
def start(self):
'''Return GraphNode representing room player starts in'''
return self.graph.map[(config.get('START_WORLD'),
config.get('START_ROOM'))]