Experiments with ruby-processing (processing-2.2.1) and JRubyArt for processing-3.0

Monday 9 March 2015

Watch a Handy Sketch in ruby-processing

There is this other attempt at doing ruby-processing called processing.rb (by someone who appears to be allergic to objects) here is their signature sketch in ruby-processing, what is is wrong with 'rp5 watch'? Improvements made to their example (yes I know I cheated with boundary check):-
  • avoid unecessary use of instance eval (it is all over processing.rb examples)
  • use rand(range) this is ruby after all
  • use __persistent__ to warn ruby compiler of a singleton (advisable for jruby 9000)
  • use map to create an array
  • use Struct to create a simple Boundary class
load_library :handy
java_import org.gicentre.handy.HandyRenderer

BALL_NUM = 6
BALL_COLORS = [[255, 0, 0], [255, 255, 0], [64, 64, 255]]
attr_reader :balls, :handy

def setup
  size(400, 400)
  HandyRenderer.__persistent__ = true
  @handy = HandyRenderer.new(self)
  @balls = (0...BALL_NUM).map { |i| Ball.new(i, handy) }
end

def draw
  background(color(234, 215, 182))
  fill(color(0, 255, 0))
  handy.rect(20, 20, 360, 20)
  handy.rect(20, 360, 360, 20)
  handy.rect(20, 40, 20, 320)
  handy.rect(360, 40, 20, 320)
  balls.each(&:draw)
end

# Bouncing ball
class Ball
  include Processing::Proxy
  attr_reader :x, :y, :radius, :size, :renderer, :boundary
  def initialize(id, renderer)
    @renderer = renderer
    @x, @y = rand(100..300), rand(100..300)
    @vx, @vy = rand(-6..6), rand(-6..6)
    @size = rand(60..100)
    @radius = size / 2.0
    @color = color(*BALL_COLORS[id % BALL_COLORS.size])
    @boundary = Boundary.new(40 + radius, 360 - radius)
  end

  def draw
    @x += @vx
    @y += @vy
    @vy += 0.1
    @vx = -@vx unless boundary.include? x
    @vy *= -0.99 unless boundary.include? y
    fill(@color)
    renderer.ellipse(x, y, size, size)
  end
end

Boundary = Struct.new(:lower, :upper) do
  def include?(x)
    (lower...upper).cover? x
  end
end

No comments:

Post a Comment

Followers

About Me

My photo
I have developed JRubyArt and propane new versions of ruby-processing for JRuby-9.1.5.0 and processing-3.2.2