L-System > Albero binario

La grammatica ha 2 variabili, 2 costanti, un assioma, 2 regole di produzione

  • variabili: 0, 1
  • costanti: [, ]
  • assioma: 0
  • regole di produzione:
    • 0 → 1[0]0
    • 1 → 11

Ecco i 6 alberi successivi per ANGOLO=45°

LivelloStringaLung.Risultato
101
21[0]05
311[1[0]0]1[0]014
41111[11[1[0]0]1[0]0]11[1[
0]0]1[0]0
34
511111111[1111[11[1[0]0]1[
0]0]11[1[0]0]1[0]0]1111[1
1[1[0]0]1[0]0]11[1[0]0]1[
0]0
78

Al livello 6 la stringa è lunga 174 caratteri

1111111111111111[11111111[1111[11[1[0]0]1[0]0]11[1[0]0]1[0]0]1111[11[1[0]0]1[0]0]11[1[0]0]1[0]0]11111111[1111[11[1[0]0][0]0]11[1[0]0]1[0]0]1111[11[1[0]0]1[0]0]11[1[0]0]1[0]0

Ecco le 6 immagini insieme!

import time
import turtle
#-----------------------------------------------
WIDTH  =800       # Dimensione finestra
HEIGHT =800       # ...
LIVELLI=6         # Numero livelli
#-----------------------------------------------
W      =0              # Posizione iniziale
H      =-HEIGHT*0.45   # ...
DIR    =90             # Direzione iniziale
ANGOLO =45             # Angolo a sinistra
#----------------------------------------------- Passo della tartaruga
SIZE   = HEIGHT*0.9/(2**(LIVELLI-1))
#-----------------------------------------------
R     =['0']
REGOLE={'0':'1[0]0', '1':'11', '[':'[', ']':']'}
#-----------------------------------------------
def trasforma(R):
    R2=[]
    for x in R:
        R2 += REGOLE[x]
    return R2
#-----------------------------------------------
def disegna(R):
    turtle.setup(width=WIDTH, height=HEIGHT)
    turtle.bgcolor('pink')
    turtle.pencolor("red")
    turtle.pensize(3)
    turtle.penup()
    turtle.shape('turtle')
    turtle.speed(0)
    turtle.setposition(W,H)
    turtle.setheading(DIR)
    STACK=[]
    for x in R:
        if(x == '0'):
            turtle.pendown()
            turtle.forward(SIZE)
            turtle.dot(10, 'black')
        elif(x == '1'):
            turtle.pendown()
            turtle.forward(SIZE)
        elif(x == '['):
            p=turtle.position()
            h=turtle.heading()
            STACK.append(p)
            STACK.append(h)
            turtle.left(ANGOLO)
        elif(x == ']'):
            h=STACK.pop()
            p=STACK.pop()
            turtle.penup()
            turtle.setposition(p)
            turtle.setheading(h)
            turtle.right(ANGOLO)    
    turtle.penup()
    turtle.setposition(W,H)
    turtle.setheading(DIR)    
#-----------------------------------------------
for j in range(LIVELLI):
    print(len(R), '\t', str().join(R), '\n')
    disegna(R)
    R=trasforma(R)

Al variare dell’angolo si ottengono le figure seguenti

ANGOLO=18°

ANGOLO=36°

ANGOLO=45°

ANGOLO=60°

ANGOLO=90°

Lascia un commento