# LCCRMY: a recursive random walker v2021_04_30 - Alexandre B A Villares
# Drag the mouse to rotate. Press SPACE to generate a new one.

from random import choice
elements = []
r = 0

def setup():
    size(800, 800, P3D)
    generate()

def generate(n=500):
    pegs = (-20, -10, 0, 0, 10, 20)
    elements[:] = [(choice('LCCRMY'),
                   (choice(pegs), choice(pegs)),
                   choice((1, 3)),)
                   for _ in range(n)]

def draw():
    background(240, 240, 220)
    # for Processing Python mode, use this:
    # translate(width / 2, height / 2, -400)  
    translate(0, 0, -400)  # this for pyp5js
    rotateY(r)
    draw_e(elements)


def draw_e(els):
    for i, e in enumerate(els):
        stroke(0)
        t, v, w = e
        strokeWeight(w)
        if t == 'Y':
            if i % 2:
                rotateX(QUARTER_PI)
            else:
                rotateY(QUARTER_PI)
        if t == 'L':
            line_e(v)
        if t == 'C':
            line_e(v, c=w)
        if t == 'M' and i > 1:
            for _ in range(3):
                line_e(v)
                pushMatrix()
                scale(.5)
                draw_e(els[i - 5:i])
                popMatrix()
        if t == 'R' and i > 1:
            for _ in range(3):
                line_e(v)
                line_e((v[1] / 2, -v[0] / 2))
                draw_e([els[i - 1]])


def line_e(v, c=None):
    x, y = v
    line(0, 0, x, y)
    if c is not None:
        d = sqrt(x * x + y * y)
        if c != 1:
            fill(0)
            square(0, 0, d / 9)
        else:
            fill(255, 0, 0)
            circle(0, 0, d)
    translate(x, y)

def mouseDragged():
    global r
    r += (mouseX - pmouseX) / 200.0

def keyReleased():
    if key == ' ':
        generate()