Ruby/SDL を使ってみる
これまで Ruby で画面に線を引いたり円を描いたりするのに、自作の Gem 'oekaki' を使ってきましたが、その中では Gem 'gtk2' を使っていて、たかがお絵かきに GTK+ を使うのは大袈裟すぎるようにも思われたので、Ruby/SDL を使ってみることにしました。Linux MInt 18.3, Ruby 2.5.1 で確認しています。(SDL と SGE が入れば、Windows や Mac でも動く筈です。)
まずは SDL のインストールが必要です。Linux では apt-get で入ります。libsdl2-2.0 は既に入っているかもしれません。
sudo apt-get install libsdl2-2.0 libsdl-sge-dev
お絵かきをするには特に SGE(SDL Graphics Extension)が必要です。SDL 2.0 の日本語リファレンスはここにあります。
Ruby/SDL をインストール。gem install rubysdl でよいです。もちろん Bundler で入れてもかまいません。Ruby/SDL のリファレンス・マニュアルはここにあります。簡単なサンプルはこちらもどうぞ。
サンプルとして、Gem 'oekaki' で描いた(参照)のと同様のデモを載せておきます。複数の円が拡大縮小しながら落下していきます。
コード。簡単なライブラリのようなもの。
sdl_draw.rb
require 'sdl' def draw(width, height, &blk) SDL.init(SDL::INIT_VIDEO) screen = SDL::Screen.open(width, height, 16, SDL::SWSURFACE) SDL::WM::set_caption("SDL", "") class << screen def color(r, g, b) format.map_rgb(r, g, b) end end Thread.new {screen.instance_eval(&blk)} loop do while (event = SDL::Event.poll) case event when SDL::Event::Quit exit end end sleep 0.2 end end
サンプル。
sdl_sample3.rb
require_relative 'sdl_draw' Width, Height = (ARGV.size == 2) ? ARGV.map(&:to_i) : [1000, 700] Max_r, Min_r = 40, 10 ColorMax = 256 MaxNum = 60 class Circle def initialize(ob) @slot = ob renewal @y = rand(Height) end def renewal @max_r = rand(Min_r..Max_r) @x = rand(Width) @y = -rand(@max_r) @color = @slot.color(rand(ColorMax), rand(ColorMax), rand(ColorMax)) @fall_step = rand(1..4) @r = 1 @r_step = rand(0.2..1.0) end def paint @slot.draw_circle(@x, @y, @r, @color, true, true) @y += @fall_step @r += @r_step @r_step *= -1 if @r > @max_r or @r < 1 renewal if @y > Height + Max_r end end draw(Width, Height) do circles = Array.new(MaxNum) { Circle.new(self) } black = color(0, 0, 0) loop do fill_rect(0, 0, Width, Height, black) circles.each(&:paint) flip sleep(0.08) end end
Ruby/SDL、シンプルでよいですね。これからも使ってみたいです。
Gem 'oekaki' 版の動画です。こんな感じ。
追記(10/22)
実行時に
uninitialized constant SDL::Mixer (NameError)
のエラーが出る場合は、
$ sudo apt-get install libsdl-mixer1.2 libsdl-mixer1.2-dev
でライブラリを入れてから、Gem を再インストールしてみて下さい。