Green Shoes を使ってみる

Ruby の簡便な GUI ライブラリである Green Shoes を使ってみました。
The Green Shoes Manual // Hello!

とても手軽に使えます。例えばこんな感じ。マウスでクリックしたところに円を書きます。

#! /usr/bin/env ruby
require 'bundler/setup'
require 'green_shoes'

Shoes.app do 
  click do |button, left ,top|
    cl = rgb(rand(256), rand(256), rand(256))
    stroke(cl); fill(cl)
    oval(left - 30, top - 30, 30)
  end
end


オリジナル版の Shoes はこちら。Green Shoes は Linux の場合、普通に Gem としてインストールできるので(Bundler を使っていとも簡単にできます)、こちらを選びました。GTK2 を使って Ruby だけで書かれているようです。オリジナル版に比べ、多少機能が限定されています。

ヒルベルト曲線

以前 Ruby/Tk でヒルベルト曲線を描いてみましたが(参照)、それの Green Shoes 版です。殆ど変わりはありません。

#! /usr/bin/env ruby
require 'bundler/setup'
require 'green_shoes'

class Draw
  def initialize(n, slot)
    @lgth = Width / 2 ** n
    @y = (Width - @lgth * (2 ** n - 1)) / 2  #見栄えを整えているだけで、特に意味のない計算
    @x = Width - @y
    @oldx = @x; @oldy = @y
    @slot = slot
  end
  
  def ldr(n)
    return if n == 0
    dlu(n-1); @x -= @lgth; dline
    ldr(n-1); @y += @lgth; dline
    ldr(n-1); @x += @lgth; dline
    urd(n-1)
  end
  
  def urd(n)
    return if n == 0
    rul(n-1); @y -= @lgth; dline
    urd(n-1); @x += @lgth; dline
    urd(n-1); @y += @lgth; dline
    ldr(n-1)
  end
  
  def rul(n)
    return if n == 0
    urd(n-1); @x += @lgth; dline
    rul(n-1); @y -= @lgth; dline
    rul(n-1); @x -= @lgth; dline
    dlu(n-1)
  end
  
  def dlu(n)
    return if n == 0
    ldr(n-1); @y += @lgth; dline
    dlu(n-1); @x -= @lgth; dline
    dlu(n-1); @y -= @lgth; dline
    rul(n-1)
  end
  
  def dline
    x1 = @oldx; y1 = @oldy; x2 = @x; y2 = @y 
    @slot.app {line(x1, y1, x2, y2)}
    @oldx = @x; @oldy = @y
  end
end

Width = 400
Shoes.app title:"Hilbert curve", width: Width, height: Width do
  background(ghostwhite)
  stroke(firebrick)
  n = (ARGV[0] || 5).to_i  #次数を引数に。デフォルトは5次
  exit if n < 1
  Draw.new(n, stack).ldr(n) 
end