Using Python mode in Processing

  • 14
  • 0

Hi @all! :wave:

Here is Luiz. I'm a back-end engineer at SQUEEZE.
This is the 9th post for the Python Advent Calendar. I hope you guys don't mind a bit of English. :sweat_smile:

I have been working with Python only for 5 months, so there isn't much I can bring yet.

Last year I wrote a post about Creative Code with Processing. If you don't know Processing or what is creative coding, I recommend you to check my previous post before proceeding on this one.

Processing is a language based on Java, but with a simple add-on, it's possible to write sketches in Python. Today, let's see how it works.

How to start

  1. Download Processing if you still don't have it.
  2. Install the Python mode, as described here.

Example: Cellular Automation

Cellular automation is a discrete mathematical model, often used in Generative Art.

Just as a demonstration, I adapted the example from this book, from the original Processing syntax to Python.

This is the result:

def setup():
    size(300, 300)

    global generation
    generation = 0

    global memory
    memory = [[0 for x in range(width)] for y in range(height)] 

    for x in range(0, width):
        for y in range(0, height):
            if random(1) > 0.5:
                set(x, y, color(0, 0, 0))
                set(x, y, color(255, 255, 255))

def draw():
    global generation

    for x in range(1, width):
        for y in range(1, height):

            k = 0
            for i in range(-1, 2):
                for j in range(-1, 2):
                    if i == 0 and j == 0:

                    c = get(x + i, y + j)

                    if red(c) == 0:
                        k += 1

            if k == 3:
                memory[x][y] = 0

            elif k >= 5:
                memory[x][y] = 255

    for x in range(0, width):
        for y in range(0, height):
            set(x, y, color(memory[x][y]))

    generation += 1
    print generation         

You are probably thinking that it doesn't really look like "real Python code" (what is that global?).
Indeed, some workarounds are necessary to make it work. However, in general, it's the same Python you use every day. For more complex projects, it's possible to create classes, Python libraries and everything else.

This is how a basic cellular automata looks like:


Change the values in the code and observe how they affect the result!
Also, instead of only black and white, try to add some colors! :)

Check the Processing Language Reference for more information about functions you can use.


If you like Python and would like to play with creative coding or generative art, the Python Mode for Processing is definitely your best choice.

By the way, SQUEEZE IS HIRING!. Join us and make part of a international team in a fast growing Japanese startup! :muscle_tone3: