Below is code for a variant of the project that uses a different approach. It is written for the Processing Python Mode .
Note that the code does not contain any for
loops. Instead, it uses recursion, whereby a function calls itself. The concept behind this approach is that we can build a large object from smaller versions of itself. For example, to build a staircase of n
steps, we can build a large step, then build a smaller staircase of n - 1
steps on top of that step. The smallest staircase is one that consists of only one step.
Here’s a picture of the result:
The code is below. See the comments for explanations. As a challenge, try to draw the above by translating the code into p5.js.
Also see Wikipedia: Recursion.
def setup():
size(440, 440)
noLoop()
background(249)
fill(0, 0, 0, 48)
def draw():
# Draw a staircase with 16 stairsteps composed of
# round building units with a diameter of 40.
diam = 40
dimension = 10
draw_staircase(diam, height - diam, diam, dimension)
# Three recursive functions follow.
# A recursive function is one that calls itself.
# Each recursion consists of ...
# a recursive case wherein the function calls itself.
# a base case wherein the function does not call itself.
# To avoid an infinite recursion, the recursive calls must ultimately resolve to the base case.
# Within the three recursions here ...
# The recursive cases build features from smaller versions of themselves.
# The base cases draw the smallest versions of the features.
def draw_building_unit(x, y, diam):
if diam > 5:
# Recursive case:
# First, draw a smaller round building unit.
draw_building_unit(x - diam // 16, y - diam // 16, diam * 3 // 4)
# Then enclose it in a full-size ellipse.
ellipse(x, y, diam, diam)
else:
# Base case: simply draw a small ellipse
ellipse(x, y, diam, diam)
def draw_step(x, y, diam, dimension):
# First, draw a round building unit.
draw_building_unit(x, y, diam)
# If <dimension> > 1, extend the step toward the right
# by a smaller step with <dimension - 1> round building units.
if (dimension > 1):
draw_step(x + diam, y, diam, dimension - 1)
def draw_staircase(x, y, diam, dimension):
# First, draw a step of <dimension> circles.
draw_step(x, y, diam, dimension)
# If <dimension> > 1, draw a smaller staircase
# of <dimension - 1> steps on top of it.
if dimension > 1:
draw_staircase(x, y - diam, diam, dimension - 1) # recursive case
else:
pass # Base case; do nothing