lindenmayer.py 2.4 KB

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