コッホ曲線を描く(Python, Ruby)
自己相似図形であるコッホ曲線を Python と Ruby で描いてみました。
Python では手軽にタートル・グラフィックスが使えるので、これを利用するのが簡単です。
3次のコッホ曲線を描きます。
from turtle import * def draw(length, depth): if depth == 0: forward(length) else: draw(length / 3, depth - 1) left(60) draw(length / 3, depth - 1) right(120) draw(length / 3, depth - 1) left(60) draw(length / 3, depth - 1) color('firebrick') up() setx(-250) down() draw(500, 3) input()
Ruby では簡単なタートル・グラフィックスを実装して描くことにします(Turtle クラス)。描画は自作の Gem 'oekaki' で行っています。
4次のコッホ曲線を描きます。
require 'oekaki' Width, Height = 600, 300 class Turtle def initialize(x, y, ob) @pen_po = Vector[x, y] @pen = ob @dir = Vector[1, 0] end def left(deg) θ = PI * deg / 180 @dir = Matrix[[cos(θ), -sin(θ)], [sin(θ), cos(θ)]] * @dir end def right(deg) left(-deg) end def forward(length) next_po = @pen_po + @dir * length @pen.line(Width / 2 + next_po[0], Height / 2 - next_po[1], Width / 2 + @pen_po[0], Height / 2 - @pen_po[1]) @pen_po = next_po end end Oekaki.app width: Width, height: Height, title: "Koch curve" do draw do color(0, 0, 0) rectangle(true, 0, 0, Width, Height) t = Turtle.new(-250, -50, self) drawing = proc do |length, depth| if depth.zero? t.forward(length) else drawing[length / 3, depth - 1] t.left(60) drawing[length / 3, depth - 1] t.right(120) drawing[length / 3, depth - 1] t.left(60) drawing[length / 3, depth - 1] end end color(0, 65535, 0) drawing[500.0, 4] end end
Python でも Ruby でもやっていることはほぼ同じです。
Gem 'oekaki' については以下。
oekaki | RubyGems.org | your community gem host
GTK+でお絵かきしてみた(Ruby) - Camera Obscura
誰かえらい人、Ruby でタートル・グラフィックスを実装しないですかね。初心者が遊ぶのに手頃だと思うのだけれど。自分でやれるといいのだけれど、Python みたいにインタラクティブに描画させるようにすると自分のスキルではむずかしそう。
→自分で実装してみた。
※参考
GTK+でヒルベルト曲線(Ruby) - Camera Obscura
Python の Turtle でヒルベルト曲線 - Camera Obscura