Generative art: paintings that surprise you
What if you wrote the rules and the computer made the painting? That's generative art. You choose the shapes and colors. The computer chooses the rest, and it's new every time.
The big idea
Generative art comes from rules plus chance: a loop repeats, a random pick makes each trip different, and the result changes on every Run.
See it in code
Start with a loop and two random numbers. Every bubble gets its own spot, chosen fresh on each trip:
bubble_count = 30
paper("royal blue")
for count in range(bubble_count):
ring(x=random_number(20, 380), y=random_number(20, 380), size=18, color="white")
Press the 'Run Code' button again and every bubble moves. You wrote one line of paint. The loop and the random picks did the rest.
A recipe can decide what to paint. This one rolls a number from 1 to 3, then uses if, elif, and else to choose a shape:
palette = ["gold", "coral", "turquoise"]
def surprise(x, y, size=50):
choice = random_number(1, 3)
if choice == 1:
circle(x=x, y=y, size=size, color=pick(palette))
elif choice == 2:
diamond(x=x, y=y, width=size, height=size, color=pick(palette))
else:
heart(x=x, y=y, size=size, color=pick(palette))
paper("dark slate gray")
for count in range(5):
surprise(x=60 + count * 70, y=200)
The recipe makes two choices each time it's called: which shape, and which color. Five calls gave five small surprises.
Now fill a whole poster. A loop inside a loop calls the recipe for every square of a grid, then one big call adds a centerpiece:
palette = ["gold", "coral", "turquoise", "orchid"]
rows = 5
columns = 5
start = 60
step = 70
def surprise(x, y, size=44):
choice = random_number(1, 3)
if choice == 1:
circle(x=x, y=y, size=size, color=pick(palette))
elif choice == 2:
diamond(x=x, y=y, width=size, height=size, color=pick(palette))
else:
heart(x=x, y=y, size=size, color=pick(palette))
paper("midnight blue")
for row in range(rows):
for column in range(columns):
surprise(x=start + column * step, y=start + row * step)
surprise(x=200, y=200, size=130)
The centerpiece is the same recipe with a bigger size. It's painted last, so it sits in front of everything else.
Games use the same trick. A wave of rocks gets random sizes and speeds, so no two games look alike. The rules stay fixed, and chance fills in the details.
Try it yourself
Put your own four colors in palette. Then add a fourth shape to the recipe: change random_number(1, 3) to (1, 4) and add one more elif.
The common mistake
Expecting chance to be fair. With three shapes, you won't get the same number of each. One Run might have no hearts at all. That's randomness doing its job.
What it unlocks
The pieces of generative art are randomness, loops inside loops, and recipes with options. Combine them your own way.