1#!/usr/bin/env python
2"""       turtle-example-suite:
3
4        xtx_lindenmayer_indian.py
5
6Each morning women in Tamil Nadu, in southern
7India, place designs, created by using rice
8flour and known as kolam on the thresholds of
9their homes.
10
11These can be described by Lindenmayer systems,
12which can easily be implemented with turtle
13graphics and Python.
14
15Two examples are shown here:
16(1) the snake kolam
17(2) anklets of Krishna
18
19Taken from Marcia Ascher: Mathematics
20Elsewhere, An Exploration of Ideas Across
21Cultures
22
23"""
24################################
25# Mini Lindenmayer tool
26###############################
27
28from turtle import *
29
30def replace( seq, replacementRules, n ):
31    for i in range(n):
32        newseq = ""
33        for element in seq:
34            newseq = newseq + replacementRules.get(element,element)
35        seq = newseq
36    return seq
37
38def draw( commands, rules ):
39    for b in commands:
40        try:
41            rules[b]()
42        except TypeError:
43            try:
44                draw(rules[b], rules)
45            except:
46                pass
47
48
49def main():
50    ################################
51    # Example 1: Snake kolam
52    ################################
53
54
55    def r():
56        right(45)
57
58    def l():
59        left(45)
60
61    def f():
62        forward(7.5)
63
64    snake_rules = {"-":r, "+":l, "f":f, "b":"f+f+f--f--f+f+f"}
65    snake_replacementRules = {"b": "b+f+b--f--b+f+b"}
66    snake_start = "b--f--b--f"
67
68    drawing = replace(snake_start, snake_replacementRules, 3)
69
70    reset()
71    speed(3)
72    tracer(1,0)
73    ht()
74    up()
75    backward(195)
76    down()
77    draw(drawing, snake_rules)
78
79    from time import sleep
80    sleep(3)
81
82    ################################
83    # Example 2: Anklets of Krishna
84    ################################
85
86    def A():
87        color("red")
88        circle(10,90)
89
90    def B():
91        from math import sqrt
92        color("black")
93        l = 5/sqrt(2)
94        forward(l)
95        circle(l, 270)
96        forward(l)
97
98    def F():
99        color("green")
100        forward(10)
101
102    krishna_rules = {"a":A, "b":B, "f":F}
103    krishna_replacementRules = {"a" : "afbfa", "b" : "afbfbfbfa" }
104    krishna_start = "fbfbfbfb"
105
106    reset()
107    speed(0)
108    tracer(3,0)
109    ht()
110    left(45)
111    drawing = replace(krishna_start, krishna_replacementRules, 3)
112    draw(drawing, krishna_rules)
113    tracer(1)
114    return "Done!"
115
116if __name__=='__main__':
117    msg = main()
118    print msg
119    mainloop()
120