For information on L-Systems see Lindenmayer Systems, Fractals, and Plants or The Algorithmic Beauty of Plants
-
Turtle - A class that holds a location, direction and a renderer object
-
TurtleAction - A struct that wraps a closure of the form
(_ : Turtle) -> Void
. Actions are simple instructions like move or turn and complex sequences of other actions. -
TurtleRenderer - A protocol for renderers. There are two implementations. One is an extentsion to CGContext. The other is a bounding box finder.
-
TurtleView - A NS/UIView that holds a TurtleAction object and draws it scaled to the views bounds.
let flowsnake : TurtleAction = {
let F = TurtleAction.move(by: 4)
let x = [ "+" : TurtleAction.turn(by: +60),
"-" : TurtleAction.turn(by: -60),
"X" : F,
"Y" : F ]
let p = [ "X" : "X-Y--Y+X++XX+Y-",
"Y" : "+X-YY--Y-X++X+Y" ]
let a = "X"
return .lindenmayer(axiom: a, rules: p, actions: x, depth: 4)
}()
let view = TurtleView(action: flowsnake)
let triangles = (1 ... 3).map({ (i : Int) -> TurtleAction in
if (i % 2 == 1) {
return .polygon(sideLength: 150, sideCount: 3, ccw: (i == 1), twist: 3, repeat: 50)
} else {
return .turn(by: 60)
}
})
let view = TurtleView(action: .sequence(triangles, repeat: 6))
Swift 4
Xcode 9 or Swift Playgrounds iPad app