← RU Pythoncursus

Uitwerking: L-systemen

#! /usr/bin/env python

import turtle
import os

directory = './l_systemen'
posstack = list()
anglestack = list()

#angle = 85
#length = 40
#depth = 4
#rules = {'F' : 'F+F--F+F'}

# 85
# 40
# 4
# F:F+F--F+F

#for dirname, dirnames, filenames in os.walk('.'):
#    print('filenames:',filenames)

def rules_from_file(fname):
    rules = {}
    with open(fname, 'r') as f:
        angle = int(f.readline())
        length = int(f.readline())
        depth = int(f.readline())
        axiom = f.readline()
        for rule in f:
            left = rule[0]
            right = rule[2:]
            rules[left] = right
    return angle, length, depth, axiom, rules

def parameterised_replace(s, rules):
    result = ''
    for c in s:
        if c in rules:
            result += rules[c]
        else:
            result += c
    return result

def replace(s):
    result = ''
    for c in s:
        if c == 'F':
            result += 'F+F-F-F+F'
        else:
            result += c
    return result

def draw(s, length, angle):
    for c in s:
        if c == 'F':
            turtle.forward(length)
        elif c == '-':
            turtle.left(angle)
        elif c == '+':
            turtle.right(angle)
        elif c == '[':
            posstack.append(turtle.position())
            anglestack.append(turtle.heading())
        elif c == ']':
            turtle.penup()
            turtle.setposition(posstack.pop())
            turtle.setheading(anglestack.pop())
            turtle.pendown()


def readAndDraw(filename):
    angle, length, depth, axiom, rules = rules_from_file(filename)
    s = axiom
    for i in range(depth):
        s = parameterised_replace(s, rules)
    turtle.speed(0)
    turtle.penup()
    turtle.setposition(-100, -200)
    turtle.left(90)
    turtle.pendown()
    turtle.color('black', 'red')
    #turtle.begin_fill()
    turtle.delay(0)
    draw(s, length, angle)
    print('done')
    #turtle.end_fill()
    turtle.done()

for dirname, dirnames, filenames in os.walk(directory):
    print (filenames)
    for filename in filenames:
        if len(filename) > 3 and filename[len(filename)-4:] == '.lst':
            print('drawing ' + filename)
            readAndDraw(directory + '/' + filename)
        else:
            print('skipping ' + filename)
print('finished!')