LSystem.sf 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/usr/bin/ruby
  2. include('Turtle.sf')
  3. class LSystem(
  4. angle = 90,
  5. scale = 1,
  6. xoff = 0,
  7. yoff = 0,
  8. len = 5,
  9. color = 'black',
  10. width = 500,
  11. height = 500,
  12. turn = 0,
  13. ) {
  14. method execute(string, repetitions, filename, rules) {
  15. var theta = angle.deg2rad
  16. var turtle = Turtle(
  17. x: width,
  18. y: height,
  19. angle: turn,
  20. scale: scale,
  21. color: color,
  22. xoff: xoff,
  23. yoff: yoff,
  24. )
  25. var stack = []
  26. var table = Hash(
  27. '+' => { turtle.turn(theta) },
  28. '-' => { turtle.turn(-theta) },
  29. ':' => { turtle.mirror },
  30. '[' => { stack.push(turtle.state) },
  31. ']' => { turtle.setstate(stack.pop) },
  32. )
  33. repetitions.times {
  34. string.gsub!(/(.)/, {|c| rules{c} \\ c })
  35. }
  36. string.each_char { |c|
  37. if (table.contains(c)) {
  38. table{c}.run
  39. }
  40. elsif (c.is_uppercase) {
  41. turtle.forward(len)
  42. }
  43. }
  44. turtle.save_as(filename)
  45. }
  46. }