Creating a local library
Here is a little ruby-processing sketch by Thomas R. Koll, that has been refactored and updated for JRubyArt. Also demonstrated is how to create a local library that gets picked up by the JRubyArt library_loader
.
raining.rb
# raining after Rain1 by Thomas R. 'TomK32' Koll
#
# draws raindrops as bezier shapes and moves them downwards
#
# available key commands:
# + make raindrops heavier/bigger
# - make raindrops smaller
# a more raindrops
# s less raindrops
# <SPACE>
#
# License: Same as processing
#
load_library :rain_drops
attr_reader :drops, :weight, :drops_size, :paused
def settings
size 640, 480
end
def setup
sketch_title "It's Raining"
frame_rate 30
@drops_size = 20
@weight = 20
@drops = RainDrops.new width, height
@paused = false
font = create_font('Georgia', 15)
text_font(font)
end
def draw
return if paused
# we fill up with new drops randomly
drops.fill_up(weight) while rand(drops_size / 3) < (drops_size - drops.size)
# the less drops the darker it is
background 127 + 127 * (drops.size / drops_size.to_f)
drops.run
form = '%d of %d drops with a size of %d'
text(format(form, drops.size, drops_size, weight), 10, 20)
end
def key_pressed
case key
when '+'
@weight += 5
when '-'
@weight -= 5 if weight > 10
when 'a'
@drops_size += 5
when 's'
@drops_size -= 5 if drops_size > 5
when ' '
@paused = !paused
end
end
Here is the local library nest library/rain_drops
folder for library_loader
to work
rain_drops.rb
require 'forwardable'
# wrap the run method
module Runnable
def run
reject!(&:dead?)
each(&:display)
end
end
# Using forwardable to include enumerable methods we use
# Include runnable for a nice run abstraction
class RainDrops
include Enumerable, Runnable
extend Forwardable
def_delegators(:@drops, :<<, :each, :reject!, :size)
attr_reader :drops, :width, :height
def initialize(width, height)
@drops = []
@width = width
@height = height
end
def fill_up(weight)
drops << Drop.new(rand(width), rand(height / 2) - height / 2, weight)
end
end
# Encapsulates drop behaviour, and include Proxy to access PApplet methods
class Drop
include Processing::Proxy
attr_reader :weight, :x, :y
def initialize(x, y, weight = nil)
@weight = weight || 10
@x, @y = x, y
end
def render
fill(100, 100, 200)
no_stroke
bezier(
x,
y,
x - (weight / 2),
y + weight,
x + (weight / 2),
y + weight,
x,
y
)
end
def dead?
@y > height
end
def display
@y = y + weight
@x = x - rand(-5..5)
render
end
end