Sierpinski carpet: Difference between revisions

Content added Content deleted
Line 4,977: Line 4,977:
n = 4
n = 4
@limit = width / 3**(n - 1)
@limit = width / 3**(n - 1)
fill(0)
background(255)
no_stroke
# draw first hole
rect(width / 3, height / 3, width / 3, width / 3)
holes(width / 3, height / 3, width / 3)
end
end


def in_carpet?(x, y)
def draw
!(x == 1 && y == 1)
background 0, 0, 200
no_stroke
fill 0
draw_carpet 0, 0, width
end
end


def holes(x, y, s)
private
return if s < limit


xc = x - s
def draw_carpet(x, y, side)
len = side / 3
yc = y - s
grid(3, 3) do |row, col|
rect x + len, y + len, len, len # draw hole
next unless in_carpet?(row, col)
return unless len >= limit


xx = xc + row * s
draw_carpet x, y, len
draw_carpet x + len, y, len
yy = yc + col * s
draw_carpet x + 2 * len, y, len
len = s / 3
draw_carpet x, y + len, len
rect(xx + len, yy + len, len, len)
draw_carpet x + 2 * len, y + len, len
holes(xx + s / 3, yy + s / 3, s / 3)
end
draw_carpet x, y + 2 * len, len
draw_carpet x + len, y + 2 * len, len
draw_carpet x + 2 * len, y + 2 * len, len
end
end

</lang>
</lang>