-
Notifications
You must be signed in to change notification settings - Fork 2
/
cellular.py
311 lines (267 loc) · 8.92 KB
/
cellular.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
import random
import sys
neighbour_synonyms = ('neighbours', 'neighbors', 'neighbour', 'neighbor')
class Cell:
wall = False
def __getattr__(self, key):
if key in neighbour_synonyms:
pts = [self.world.get_point_in_direction(
self.x, self.y, dir) for dir in range(self.world.directions)]
ns = tuple([self.world.grid[y][x] for (x, y) in pts])
for n in neighbour_synonyms:
self.__dict__[n] = ns
return ns
raise AttributeError(key)
class Agent:
world = None
cell = None
def __setattr__(self, key, val):
if key == 'cell':
old = self.__dict__.get(key, None)
if old is not None:
old.agents.remove(self)
if val is not None:
val.agents.append(self)
self.__dict__[key] = val
def __getattr__(self, key):
if key == 'left_cell':
return self.get_cell_on_left()
elif key == 'right_cell':
return self.get_cell_on_right()
elif key == 'ahead_cell':
return self.get_cell_ahead()
raise AttributeError(key)
def turn(self, amount):
self.dir = (self.dir + amount) % self.world.directions
def turn_left(self):
self.turn(-1)
def turn_right(self):
self.turn(1)
def turn_around(self):
self.turn(self.world.directions / 2)
def go_in_direction(self, dir):
target = self.cell.neighbour[dir]
if getattr(target, 'wall', False):
return False
self.cell = target
return True
def go_forward(self):
if self.world is None:
raise CellularException('Agent has not been put in a World')
return self.go_in_direction(self.dir)
def go_backward(self):
self.turn_around()
r = self.go_forward()
self.turn_around()
return r
def get_cell_ahead(self):
return self.cell.neighbour[self.dir]
def get_cell_on_left(self):
return self.cell.neighbour[(self.dir - 1) % self.world.directions]
def get_cell_on_right(self):
return self.cell.neighbour[(self.dir + 1) % self.world.directions]
def go_towards(self, target, y=None):
if not isinstance(target, Cell):
target = self.world.grid[int(y)][int(target)]
if self.world is None:
raise CellularException('Agent has not been put in a World')
if self.cell == target:
return
best = None
for i, n in enumerate(self.cell.neighbours):
if n == target:
best = target
bestDir = i
break
if getattr(n, 'wall', False):
continue
dist = (n.x - target.x) ** 2 + (n.y - target.y) ** 2
if best is None or bestDist > dist:
best = n
bestDist = dist
bestDir = i
if best is not None:
if getattr(best, 'wall', False):
return False
self.cell = best
self.dir = bestDir
return True
def update(self):
pass
class World:
def __init__(self, cell=None, width=None, height=None, directions=8, filename=None, map=None):
if cell is None:
cell = Cell
self.Cell = cell
self.directions = directions
if filename or map:
if filename:
data = file(filename).readlines()
else:
data = map.splitlines()
if len(data[0]) == 0:
del data[0]
if height is None:
height = len(data)
if width is None:
width = max([len(x.rstrip()) for x in data])
if width is None:
width = 20
if height is None:
height = 20
self.width = width
self.height = height
self.image = None
self.reset()
if filename or map:
self.load(filename=filename, map=map)
def get_cell(self, x, y):
return self.grid[y][x]
def find_cells(self, filter):
for row in self.grid:
for cell in row:
if filter(cell):
yield cell
def reset(self):
self.grid = [[self._make_cell(
i, j) for i in range(self.width)] for j in range(self.height)]
self.dictBackup = [[{} for i in range(self.width)]
for j in range(self.height)]
self.agents = []
self.age = 0
def _make_cell(self, x, y):
c = self.Cell()
c.x = x
c.y = y
c.world = self
c.agents = []
return c
def randomize(self):
if not hasattr(self.Cell, 'randomize'):
return
for row in self.grid:
for cell in row:
cell.randomize()
def save(self, f=None):
if not hasattr(self.Cell, 'save'):
return
if isinstance(f, type('')):
f = file(f, 'w')
total = ''
for j in range(self.height):
line = ''
for i in range(self.width):
line += self.grid[j][i].save()
total += '%s\n' % line
if f is not None:
f.write(total)
f.close()
else:
return total
def load(self, filename=None, map=None):
if not hasattr(self.Cell, 'load'):
return
if filename:
if isinstance(filename, type('')):
filename = file(filename)
lines = filename.readlines()
else:
lines = map.splitlines()
if len(lines[0]) == 0:
del lines[0]
lines = [x.rstrip() for x in lines]
fh = len(lines)
fw = max([len(x) for x in lines])
if fh > self.height:
fh = self.height
starty = 0
else:
starty = (self.height - fh) / 2
if fw > self.width:
fw = self.width
startx = 0
else:
startx = (self.width - fw) / 2
self.reset()
for j in range(fh):
line = lines[j]
for i in range(min(fw, len(line))):
self.grid[starty + j][startx + i].load(line[i])
def update(self):
if hasattr(self.Cell, 'update'):
for j, row in enumerate(self.grid):
for i, c in enumerate(row):
self.dictBackup[j][i].update(c.__dict__)
c.update()
c.__dict__, self.dictBackup[j][
i] = self.dictBackup[j][i], c.__dict__
for j, row in enumerate(self.grid):
for i, c in enumerate(row):
c.__dict__, self.dictBackup[j][
i] = self.dictBackup[j][i], c.__dict__
for a in self.agents:
a.update()
else:
for a in self.agents:
oldCell = a.cell
a.update()
self.age += 1
def get_offset_in_direction(self, x, y, dir):
if self.directions == 8:
dx, dy = [(0, -1), (1, -1), (
1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1)][dir]
elif self.directions == 4:
dx, dy = [(0, -1), (1, 0), (0, 1), (-1, 0)][dir]
elif self.directions == 6:
if y % 2 == 0:
dx, dy = [(1, 0), (0, 1), (-1, 1), (-1, 0),
(-1, -1), (0, -1)][dir]
else:
dx, dy = [(1, 0), (1, 1), (0, 1), (-1, 0),
(0, -1), (1, -1)][dir]
return dx, dy
def get_point_in_direction(self, x, y, dir):
dx, dy = self.get_offset_in_direction(x, y, dir)
x2 = x + dx
y2 = y + dy
if x2 < 0:
x2 += self.width
if y2 < 0:
y2 += self.height
if x2 >= self.width:
x2 -= self.width
if y2 >= self.height:
y2 -= self.height
return (x2, y2)
def remove(self, agent):
self.agents.remove(agent)
agent.world = None
agent.cell = None
def add(self, agent, x=None, y=None, cell=None, dir=None):
self.agents.append(agent)
if x is not None and y is not None:
cell = self.grid[y][x]
if cell is None:
while True:
xx = x
yy = y
if xx is None:
xx = random.randrange(self.width)
if yy is None:
yy = random.randrange(self.height)
if not getattr(self.grid[yy][xx], 'wall', False):
y = yy
x = xx
break
else:
x = cell.x
y = cell.y
if dir is None:
dir = random.randrange(self.directions)
agent.cell = self.grid[y][x]
agent.dir = dir
agent.world = self
agent.x = x
agent.y = y
class CellularException(Exception):
pass