Repository navigation
Expand file tree
/
Copy pathblinky_light_1d.py
More file actions
68 lines (55 loc) · 1.61 KB
/
Copy pathblinky_light_1d.py
File metadata and controls
68 lines (55 loc) · 1.61 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
from random import *
from pdb import set_trace
from time import sleep
SEEDS = [[0] * 30 + [1,1] + [0] * 30, None]
class Blinky():
def __init__(self, seed=None, rule=90):
if seed is None: self.seed_state()
else: self.state = seed
self.rule = self.to_binary(rule)
def seed_state(self):
self.state = []
for i in range(150): # set number of columns.
self.state.append(randint(0,1))
def to_binary(self, num, ary=[]):
num = num % 256 # ensure rule range.
while num > 0:
ary.insert(0, num % 2)
num //= 2
while len(ary) < 8: ary.insert(0,0)
return ary
def to_decimal(self, bry, num=0):
for i in range(0,len(bry)):
num += (2**i * bry.pop())
return num
def apply_rule(self, ury):
rule_hash = {}
val = self.to_decimal(ury)
for i in range(0,8):
rule_hash.update({i: self.rule[i]})
return(rule_hash[val])
def get_neighbors(self):
state_len, ns = len(self.state) - 1, []
for i in range(1, state_len): ns.append(self.state[i-1:i+2])
self.neighborhoods = ns
def blink(self):
new_state = self.state[:1]
self.get_neighbors()
for ury in self.neighborhoods:
cell = self.apply_rule(ury)
new_state.append(cell)
self.state = new_state + self.state[-1:]
def ppblink(self, str=''):
for i in self.state:
if i == 0: str += ' '
else: str += '*'
print(str)
# Execute example automata:
rand_seed = SEEDS[randint(0,1)]
rand_rule = [150, 90, 180, 45][randint(0,3)]
right_assoc = [0] * 140 + [1,1]
it = Blinky(right_assoc, rand_rule)
for i in range(10**3):
it.blink()
it.ppblink()
sleep(0.1)