Created
October 30, 2013 16:23
-
-
Save lesguillemets/7235593 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
class CellularAutomaton(object): | |
def __init__(self, elements, rulecode): | |
self.cells = list(elements) | |
self.rule = CARule(rulecode) | |
self.length = len(elements) | |
def __str__(self): | |
return ''.join(map(lambda x: '#' if x else '.', self.cells)) | |
def next(self): | |
nextgen = [self.rule(self.cells[i:i+3]) for i in xrange(self.length-2)] | |
self.cells = [self.cells[0]] + nextgen + [self.cells[-1]] | |
class CARule(object): | |
def __init__(self, wfcode): | |
''' | |
wolfram code: given as an integer with base 10, not binary. | |
''' | |
self.rulenum = wfcode | |
self.rule = map(lambda n: bool(int(n)), "{0:08b}".format(wfcode)) | |
self.rule.reverse() | |
# self.rule :: [Bool] | |
def __call__(self, conditions): | |
''' conditions : [Bool, Bool, Bool] ''' | |
return self.rule[ | |
sum([int(a) * 2**i for (i,a) in enumerate(conditions)])] | |
def __str__(self): | |
return "Wolfram Code {0}".format(self.rulenum) | |
def main(): | |
import os | |
import random | |
width = int(os.popen('stty size', 'r').read().split()[1]) | |
halflength = (width-1)//2 | |
#firstgen = [0]*halflength+[1]+[0]*halflength | |
firstgen = [random.choice((True, False)) for i in xrange(width)] | |
mycell = CellularAutomaton(firstgen, 90) | |
for i in range(300): | |
print mycell | |
mycell.next() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment