-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboard.py
More file actions
167 lines (134 loc) · 5.31 KB
/
board.py
File metadata and controls
167 lines (134 loc) · 5.31 KB
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
from time import sleep
from collections import defaultdict
from random import random
from cell import Cell
class Board:
"""Defines a board with multiple cells inside"""
def __init__(self, config, dims=(40, 40), wrap_around=False):
self.set_config(config)
# Physical parameters
self.w, self.h = dims[0], dims[1]
self.wrap_around = wrap_around
# Initialize empty cells
# Dict of the form {coordinate: CellObject)
self.cells = {}
for i in range(self.w):
for j in range(self.h):
self.cells[(i, j)] = Cell(state=self.states[0], coords=(i, j))
# Mark edges
for i in range(self.w):
self.cells[(i, 0)].is_edge = True
self.cells[(i, self.h - 1)].is_edge = True
for j in range(self.h):
self.cells[(0, j)].is_edge = True
self.cells[(self.w - 1, j)].is_edge = True
def __str__(self):
s = ""
for i in range(self.w):
for j in range(self.h):
s += str(self.cells[(i, j)].current_state) # MAKE THIS A JOIN
s += "\n"
return s
def iter_cells(self):
for i in range(self.w):
for j in range(self.h):
yield self.cells[(i, j)]
def set_config(self, config):
# Cell state and rule settings
self.config = config
self.states = config.possible_states # For convenience
def copy_board(self):
"""Generates a copy of the current board and all its cells"""
new_board = Board(self.config, (self.w, self.h), self.wrap_around)
for cell in new_board.iter_cells():
cell.current_state = self.cells[cell.coords].current_state
return new_board
def replace_board(self, other_board):
"""Replaces all of this board's cells with the other_board's cells"""
for cell in self.iter_cells():
cell.current_state = other_board.cells[cell.coords].current_state
def fill(self, state):
"""Fill every cell on board with given state"""
for cell in self.iter_cells():
cell.current_state = state
def random_fill(self, state_back, state_front, p):
"""Fill the board randomly (uniform p) with the given state"""
self.fill(state=state_back)
for cell in self.iter_cells():
if random() < p:
cell.current_state = state_front
def random_add(self, state, p):
for cell in self.iter_cells():
if random() < p:
cell.current_state = state
def fill_edges(self, state):
for cell in self.iter_cells():
if cell.is_edge:
cell.current_state = state
def add_pattern(self, coords, pattern):
for j, row in enumerate(pattern.split(",")):
for i, state in enumerate((int(s) for s in row.strip())):
try:
self.cells[(coords[0]+i, coords[1]+j)
].current_state = state
except IndexError:
raise Exception("Pattern out of bounds")
def update(self):
"""Apply config-rules to update cell states"""
for coord, cell in self.cells.items():
if cell.is_edge:
continue
# Get neighbor rules
try:
rules = self.config.rules[cell.current_state]
# Get cell neighbor information
for neigh_state, count in self.acquire_neighbor_info(coord).items():
# Check if neighbor rule can be applied
if neigh_state in rules and count in rules[neigh_state][0]:
# Apply the rule
cell.next_state = rules[neigh_state][1]
except KeyError:
pass
# Get switching rule if it exists
try:
sw_rule = self.config.switching_rules[cell.current_state]
if random() < sw_rule[1]:
cell.next_state = sw_rule[0]
except KeyError:
continue
self.update_cell_states()
def acquire_neighbor_info(self, coord):
i, j = coord
neighs = (self.cells[i-1, j-1],
self.cells[i, j-1],
self.cells[i+1, j-1],
self.cells[i-1, j],
self.cells[i+1, j],
self.cells[i-1, j+1],
self.cells[i, j+1],
self.cells[i+1, j+1])
neighs = (i.current_state for i in neighs)
cell = self.cells[coord]
cell.reset_neighbors()
for i in neighs:
cell.neighbors[i] += 1
return cell.neighbors
def update_cell_states(self):
for cell in self.cells.values():
if not cell.next_state:
cell.current_state = cell.next_state
cell.next_state = None
def run(self, graphics, pause=0):
"""Simulation loop. Check for events and updates cells"""
graphics.initialize()
print(self.config.rules)
step = 0
while True:
if not graphics.check_input():
graphics.close()
print("Generations run: %i" % step)
break
graphics.draw_board()
self.update()
sleep(pause)
step += 1