close

國內相關的CA in python資源真少。

附上去年年中7th版的Wolfram-style CA code.

如果想要執行的話,會需要python的隨便哪個編譯器
我是覺得陽春版的就很好用了(大羞),
然後還會需要python的image library (PIL)。

載點:
1.http://www.python.org/                  python的官網,有陽春版的編譯器(10MB,裝完約18MB)
2.http://www.badongo.com/file/7565776           PIL的載點,也可以至官網下載(550KB左右)
   http://www.pythonware.com/products/pil/
3.http://www.badongo.com/file/7565777    原碼的文字檔(2k)
4.http://www.badongo.com/file/7565778    原碼.py(3k)

--
這樣以後用google找繁中的資料應該至少找得到這個code吧XD 不想看英文的話。
--
#!/usr/bin/env python
"""
CellularAutomata.py: Wolfram-style cellular automata in Python

Options:
-h #  Use a screen of height # for the simulation
-w #  Use a screen of width # for the simulation
-r      Use a random initial row (rather than the standard single 1 in the middle)
-R #  Use rule # for the simulation

"""


import getopt,sys
from random import randint

def ca_data(height,width,dorandom,rulenum):
    # Create the first row, either randomly, or with a single 1
    if dorandom:
        first_row = [randint(0,1) for i in range(width)]
    else:
        first_row = [0]*width
        first_row[width/2] = 1
    results = [first_row]

    # Convert the rule number to a list of outcomes.
    rule = [(rulenum/pow(2,i)) % 2 for i in range(8)]

    for i in range(height-1):
        data = results[-1]
        # Determine the new row based on the old data. We first make an
        #  integer out of the value of the old row and its two neighbors
        #  and then use that value to get the outcome from the table we
        #  computed earlier
        new = [rule[4*data[(j-1)%width]+2*data[j]+data[(j+1)%width]]
               for j in range(width)]
        results.append(new)
    return results

def pil_render(data,height,width,fname="bs.png"):
    import Image, ImageDraw
    img = Image.new("RGB",(width,height),(255,255,255))
    draw = ImageDraw.Draw(img)

    for y in range(height):
        for x in range(width):
            if data[y][x]: draw.point((x,y),(0,0,0))
    img.save(fname,"PNG")
    return

def main():
    opts,args = getopt.getopt(sys.argv[1:],'h:w:rR:')
    height = 500
    width = 500
    dorandom = 0
    rule = 22
    for key,val in opts:
        if key == '-h': height = int(val)
        if key == '-w': width = int(val)
        if key == '-r': dorandom = 1
        if key == '-R': rule = int(val)
    data = ca_data(height,width,dorandom,rule)
    pil_render(data,height,width)
    return

if __name__ == '__main__': main()
arrow
arrow
    全站熱搜

    鱷魚 發表在 痞客邦 留言(0) 人氣()