Taking advantage of the "Drawing ferns programmatically" series, I wrote it in Python as well.
lambda
in the function definition.import random
N = 20
xm = 0
ym = 0.5
h = 0.6
width = 500
height = 500
W1x = lambda x, y: 0.836 * x + 0.044 * y
W1y = lambda x, y: -0.044 * x + 0.836 * y + 0.169
W2x = lambda x, y: -0.141 * x + 0.302 * y
W2y = lambda x, y: 0.302 * x + 0.141 * y + 0.127
W3x = lambda x, y: 0.141 * x - 0.302 * y
W3y = lambda x, y: 0.302 * x + 0.141 * y + 0.169
W4x = lambda x, y: 0
W4y = lambda x, y: 0.175337 * y
def f(im, k, x, y):
if 0 < k:
f(im, k - 1, W1x(x, y), W1y(x, y))
if random.random() < 0.3:
f(im, k - 1, W2x(x, y), W2y(x, y))
if random.random() < 0.3:
f(im, k - 1, W3x(x, y), W3y(x, y))
if random.random() < 0.3:
f(im, k - 1, W4x(x, y), W4y(x, y))
else:
s = 490
im.putpixel((int(x * s + width * 0.5), int(height - y * s)), (0, 128, 0))
if __name__ == '__main__':
from PIL import Image
im = Image.new("RGB", (width, height), (255, 255, 255))
f(im, N, 0, 0)
im.show()
This is a bit unattractive because I have to pass image-related arguments with the function f ()
and write drawing logic inside the function, so I tried to make it a little more Pythonic.
yield
.f ()
.import random
N = 20
xm = 0
ym = 0.5
h = 0.6
width = 500
height = 500
W1x = lambda x, y: 0.836 * x + 0.044 * y
W1y = lambda x, y: -0.044 * x + 0.836 * y + 0.169
W2x = lambda x, y: -0.141 * x + 0.302 * y
W2y = lambda x, y: 0.302 * x + 0.141 * y + 0.127
W3x = lambda x, y: 0.141 * x - 0.302 * y
W3y = lambda x, y: 0.302 * x + 0.141 * y + 0.169
W4x = lambda x, y: 0
W4y = lambda x, y: 0.175337 * y
def f(k, x, y):
if 0 < k:
for p in f(k - 1, W1x(x, y), W1y(x, y)):
yield p
if random.random() < 0.3:
for p in f(k - 1, W2x(x, y), W2y(x, y)):
yield p
if random.random() < 0.3:
for p in f(k - 1, W3x(x, y), W3y(x, y)):
yield p
if random.random() < 0.3:
for p in f(k - 1, W4x(x, y), W4y(x, y)):
yield p
else:
s = 490
yield x * s + width * 0.5, height - y * s
if __name__ == '__main__':
from PIL import Image
im = Image.new("RGB", (width, height), (255, 255, 255))
for p in f(N, 0, 0):
im.putpixel((int(p[0]), int(p[1])), (0, 128, 0))
im.show()
yield
.Recommended Posts