Welcome, guest | Sign In | My Account | Store | Cart

It draws a random Diffusion Limited Aggregation fractal each time. (Wait until the percentage reaches 100.)

Python, 52 lines
 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
# Diffusion Limited Aggregation fractal
# FB - 201004036
from PIL import Image
import random
import math

imgx = 256
imgy = 256
image = Image.new("L", (imgx, imgy))

# neighbor pixel directions
nx = [-1, -1, 0, 1, 1, 1, 0, -1]
ny = [0, 1, 1, 1, 0, -1, -1, -1]

maxIt = 256

xc = (imgx - 1) / 2
yc = (imgy - 1) / 2
rmax = min(xc, yc) - 1
# seed
image.putpixel((xc, yc), 255) 

rm = 1.0
while rm < rmax:
    a = random.random() * math.pi * 2.0
    x = xc + rm * math.cos(a)
    y = yc + rm * math.sin(a)
    # random walk
    flag = False
    for i in range(maxIt):
        a = random.randint(0, 7)
        x = x + nx[a]
        y = y + ny[a]
        if x < 0 or x > (imgx - 1) or y < 0 or y > (imgy - 1):
            break
        if image.getpixel((x, y)) == 0:
            # check the neighbors
            for k in range(8):
                xn = x + nx[k]
                yn = y + ny[k]
                if image.getpixel((xn, yn)) > 0:
                    image.putpixel((x, y), 255)
                    r = math.sqrt((x - xc) ** 2.0 + (y - yc) ** 2.0)
                    if r > rm:
                        rm = r
                        print "%" + str(int(100 * rm / rmax))
                    flag = True
                    break
        if flag == True:
            break

image.save("DLA.png", "PNG")

1 comment

FB36 (author) 14 years ago  # | flag

Here is another version that grows from the edges instead of the center:

# Diffusion Limited Aggregation fractals
# FB - 201004077
from PIL import Image
import random
imgx = 100
imgy = 100
image = Image.new("L", (imgx, imgy))

# neighbor pixel directions
nx = [-1, -1, 0, 1, 1, 1, 0, -1]
ny = [0, 1, 1, 1, 0, -1, -1, -1]

while True:
    # start random walk
    x = imgx / 2
    y = imgy / 2
    steps = 0
    flag = False
    while True:
        if image.getpixel((x, y)) == 0:
            # check the neighbors
            for k in range(8):
                xn = x + nx[k]
                yn = y + ny[k]
                if xn < 0 or xn > (imgx - 1) or yn < 0 or yn > (imgy - 1):
                    image.putpixel((x, y), 255)
                    flag = True
                    break
                if image.getpixel((xn, yn)) > 0:
                    image.putpixel((x, y), 255)
                    flag = True
                    break
        if flag == True:
            break
        a = random.randint(0, 7)
        x = x + nx[a]
        y = y + ny[a]
        steps += 1
    if steps < 2:
        break

image.save("DLA_.png", "PNG")