Code Sketch


Dragon Fractal
By: Andrew White
Category: Programming

object Config {
    val dragonSize      = 16 // WARN: 20 is huge, dragon grows exponentially

    val backgroundColor = darkGray
    val penColor        = cyan

    val lineLength      = 10
    val turtleSpeed     = 16
}

Dragon.draw(Config.dragonSize)

object Dragon {

    def draw(scaleFactor: Int) = {
        clear()
        toggleFullScreenCanvas()
        setAnimationDelay(Config.turtleSpeed)
        setBackground(Config.backgroundColor)
        setPenColor(Config.penColor)

        edges(scaleFactor) foreach (_.draw)
    }

    def edges(iterations: Int, start: List[Move] = List(Left)): List[Move] = {
        def edgesWithAcc(i: Int, acc: List[Move]): List[Move] =
            if (i <= 0) acc
            else edgesWithAcc(i - 1, acc ++ start ++ acc.reverse.map(_.opposite))

        edgesWithAcc(iterations, start)
    }

}

sealed trait Move {
    val lineLength = Config.lineLength

    def draw = { turn; forward(lineLength) }
    def opposite: Move
    def turn: Unit
}

case object Right extends Move {
    def turn = right()
    def opposite = Left
}

case object Left extends Move {
    def turn = left()
    def opposite = Right
}