... | ... |
@@ -48,50 +48,22 @@ class Cell: |
48 | 48 |
|
49 | 49 |
def get_neighbours(self, cell_array): |
50 | 50 |
''' |
51 |
- Given the array of cells, count this cell's living neighbours |
|
51 |
+ Count the cell's neighbours |
|
52 | 52 |
''' |
53 |
+ num_of_neighbours = 0 |
|
53 | 54 |
|
54 |
- # Check if cell is on an edge |
|
55 |
- l_edge = self.col == 0 |
|
56 |
- r_edge = self.col == len(cell_array) - 1 |
|
57 |
- t_edge = self.row == 0 |
|
58 |
- b_edge = self.row == len(cell_array) - 1 |
|
55 |
+ neighbour_positions = [[-1, -1], [-1, 0], [-1, 1], |
|
56 |
+ [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]] |
|
59 | 57 |
|
60 |
- # Count neighbours |
|
61 |
- num_of_neighbours = 0 |
|
58 |
+ for position in neighbour_positions: |
|
59 |
+ nr = position[0] |
|
60 |
+ nc = position[1] |
|
62 | 61 |
|
63 |
- # Check left |
|
64 |
- if not l_edge: |
|
65 |
- if cell_array[self.row][self.col - 1].is_living: |
|
66 |
- num_of_neighbours += 1 |
|
67 |
- # Check top-left |
|
68 |
- if not l_edge and not t_edge: |
|
69 |
- if cell_array[self.row - 1][self.col - 1].is_living: |
|
70 |
- num_of_neighbours += 1 |
|
71 |
- # Check bottom-left |
|
72 |
- if not l_edge and not b_edge: |
|
73 |
- if cell_array[self.row + 1][self.col - 1].is_living: |
|
74 |
- num_of_neighbours += 1 |
|
75 |
- # Check top |
|
76 |
- if not t_edge: |
|
77 |
- if cell_array[self.row - 1][self.col].is_living: |
|
78 |
- num_of_neighbours += 1 |
|
79 |
- # Check bottom |
|
80 |
- if not b_edge: |
|
81 |
- if cell_array[self.row + 1][self.col].is_living: |
|
82 |
- num_of_neighbours += 1 |
|
83 |
- # Check right |
|
84 |
- if not r_edge: |
|
85 |
- if cell_array[self.row][self.col + 1].is_living: |
|
86 |
- num_of_neighbours += 1 |
|
87 |
- # Check top-right |
|
88 |
- if not r_edge and not t_edge: |
|
89 |
- if cell_array[self.row - 1][self.col + 1].is_living: |
|
90 |
- num_of_neighbours += 1 |
|
91 |
- # Check bottom-right |
|
92 |
- if not r_edge and not b_edge: |
|
93 |
- if cell_array[self.row + 1][self.col + 1].is_living: |
|
94 |
- num_of_neighbours += 1 |
|
62 |
+ try: |
|
63 |
+ if cell_array[self.row + nr][self.col + nc].is_living: |
|
64 |
+ num_of_neighbours += 1 |
|
65 |
+ except IndexError: |
|
66 |
+ continue |
|
95 | 67 |
|
96 | 68 |
self.neighbours = num_of_neighbours |
97 | 69 |
|