-
Notifications
You must be signed in to change notification settings - Fork 0
/
grid.py
71 lines (58 loc) · 1.98 KB
/
grid.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
from rules import alive_next_turn
class Grid(object):
def __init__(self, coords=[], bool_grid=None):
self._set = set()
if bool_grid:
coords = [(x, y)
for y, row in enumerate(bool_grid)
for x, cell in enumerate(row)
if cell]
for x, y in coords:
self[(x,y)] = True
def __contains__(self, key):
return key in self._set
__getitem__ = __contains__
def __setitem__(self, key, value):
if value:
self._set.add(key)
else:
self._set.discard(key)
def __delitem__(self, key):
self._set.discard(key)
def __eq__(self, other):
return self._set == other._set
def __repr__(self):
return repr(self._set)
def get_num_of_neighbors(self, x, y):
count = 0
for x2 in xrange(x-1, x+2):
for y2 in xrange(y-1, y+2):
if x2 == x and y2 == y:
continue
if (x2, y2) in self:
count += 1
return count
def iterate(self):
new_grid = Grid()
for x, y in self.get_candidate_cells():
neighbors = self.get_num_of_neighbors(x, y)
alive_now = self[(x, y)]
alive_next = alive_next_turn(neighbors, alive_now)
if alive_next:
new_grid[(x, y)] = True
return new_grid
def get_candidate_cells(self):
candidates = set()
for x, y in self._set:
for x2 in xrange(-1, 2):
for y2 in xrange(-1, 2):
candidates.add((x+x2, y+y2))
return candidates
def render(self, start_point, end_point):
rows = []
for y in xrange(start_point[1], end_point[1]):
cells = []
for x in xrange(start_point[0], end_point[0]):
cells.append("X" if (x, y) in self else "_")
rows.append(" ".join(cells))
return "\n".join(rows)