Swiftでツリー曲線プログラム

概要

「Java人工知能プログラミング」
第1章 再帰処理と副問題への分割 – 1.2 フラクタルカーブ – ツリー曲線プログラム
をSwiftに変換。書籍はJavaです。
Playgroundで実行出来ます。
iPadのPlaygroundでも実行出来ます。

コード

import UIKit

class Curve {
    var lastX:Double = 0.0
    var lastY:Double = 0.0
    
    func move(x:Double, y:Double) {
        lastX = x
        lastY = y
    }
    
    func forward(len:Double, angle:Double) {
        let x = lastX + len * cos(angle)
        let y = lastY + len * sin(angle)
        let uiBezierPath = UIBezierPath()
        uiBezierPath.move(to: CGPoint(x: lastX, y: lastY))
        uiBezierPath.addLine(to : CGPoint(x: x, y: y))
        uiBezierPath.stroke()
        move(x: x, y: y)
    }
    
    func draw(len:Double, angle:Double) {
        forward(len: len, angle: angle)
    }
    
    func strokeline(x1:Double, y1:Double, x2:Double, y2:Double) {
        let uiBezierPath = UIBezierPath()
        uiBezierPath.move(to: CGPoint(x: x1, y: y1))
        uiBezierPath.addLine(to : CGPoint(x: x2, y: y2))
        uiBezierPath.stroke()
    }
}

class Tree : Curve {
    func draw(n:Int, len:Double, angle:Double, sw:Int) {
        let x = lastX
        let y = lastY
        if  n == 1 {
            forward(len: len, angle: angle)
        }
        else {
            let l = len / (2 / sqrt(2))
            let a = .pi * 0.15 * Double(sw)
            forward(len: l * 0.33, angle: angle)
            draw(n: n - 1, len: l * 0.8, angle: angle - a, sw: 1)
            forward(len: l * 0.33, angle: angle)
            draw(n: n - 1, len: l * 0.7, angle: angle + a * 1.5, sw: -1)
            forward(len: l * 0.33, angle: angle)
            draw(n: n - 1, len: l * 0.6, angle: angle, sw: 1)
        }
        lastX = x
        lastY = y
    }
}

let size = CGSize(width: 600, height: 600)
let point = CGPoint(x: 0, y: 0)
CGRect(origin: point, size: size)
let view = UIView(frame: CGRect(origin: point, size: size))
UIGraphicsBeginImageContextWithOptions(size, false, 0)

UIColor.yellow.setStroke()

var tree = Tree()
tree.move(x: 300, y: 600)
tree.draw(n: 7, len: 450, angle: .pi * -0.5, sw: 1)

view.layer.contents = UIGraphicsGetImageFromCurrentImageContext()?.cgImage
UIGraphicsEndImageContext()

let preview = view

結果

Mac Playground

Swift

Posted by shi-n