p5rb 練習
p5rb例
code: example.rb
noLoop
noStroke
fill('#ffffff')
beginShape
################### example ########################
def tri(x:, y:)
fill('#aabbcc') # 塗りつぶし色
noStroke # 枠線を消す
size = 100
# 正三角形の頂点を計算
half_size = size / 2
height = (Math.sqrt(3) / 2) * size # 正三角形の高さ
beginShape
vertex(x, y) # 上の頂点
vertex(x - half_size, y + height) # 左下の頂点
vertex(x + half_size, y + height) # 右下の頂点
endShape(CLOSE)
end
def setup
createCanvas(800, 800)
background '#aabbaa'
end
def draw
noLoop
0.step 800,100 do |x|
0.step 800,100 do |y|
tri(x:x,y:y) ## 引数を指定
end
end
end
rubyでよく使う表現例*
step
code: ruby_exapmle.rb
# step
step(limit, step = 1) -> Enumerator
step(limit, step = 1) -> Enumerator::ArithmeticSequence
step(by: 1, to: Float::INFINITY) {|n| ... } -> self
step(by: 1, to: Float::INFINITY) -> Enumerator
step(by: 1, to: Float::INFINITY) -> Enumerator::ArithmeticSequence
step(by:, to: -Float::INFINITY) {|n| ... } -> self
step(by:, to: -Float::INFINITY) -> Enumerator
step(by:, to: -Float::INFINITY) -> Enumerator::ArithmeticSequence
self からはじめ step を足しながら limit を越える前までブロックを繰り返します。step は負の数も指定できます。また、limit や step には Float なども指定できます。
ループの上限あるいは下限を数値で指定します。step に負の数が指定された場合は、下限として解釈されます。
各ステップの大きさを数値で指定します。負の数を指定することもできます。
引数limitと同じですが、省略した場合はキーワード引数byが正の数であれば Float::INFINITY、負の数であれば -Float::INFINITYを指定したとみなされます。
2.step(5){|n| p n}
2
3
4
5
1.1.step(1.5, 0.1) {|n| p n}
1.1
1.2
1.3
1.4
1.5
10.step(6, -1){|n| p n}
10
9
8
7
6
3.step(by:2, to:10){|n| p n}
3
5
7
## 例
code:face.rb
class Face
attr_reader :width, :height, :color, :x, :y
def initialize(width, height, color, x, y)
@width = width
@height = height
@color = color
@x = x
@y = y
end
def eye(x, y)
angle = atan2(mouse_y - y, mouse_x - x)
no_stroke
push
translate(x, y)
# Draw white part of the eye
fill(255)
ellipse(0, 0, 0.25 * @width, 0.25 * @width)
# Draw black part of the eye
rotate(angle)
fill(@color)
ellipse(0.0625 * @width, 0, 0.125 * @width, 0.125 * @width)
pop
end
def mouth
distance = dist(mouse_x, mouse_y, @x + @width / 2, @y + @height / 2)
ratio = 1 - clamped_distance / 200.0
push
no_stroke
translate(@x + @width / 2, @y + 0.75 * @height)
fill(255)
start_angle = 0
end_angle = PI
arc(0, 0, 0.5 * @width, 0.25 * @height * ratio, start_angle, end_angle)
pop
end
def draw
fill(@color)
rect(@x, @y, @width, @height)
# Draw eyes
eye(@x + 0.375 * @width, @y + 0.5 * @height)
eye(@x + 0.625 * @width, @y + 0.5 * @height)
# Draw mouth
mouth
end
end
class FaceGrid
attr_reader :faces
def initialize(canvas_size, cell_size)
@faces = []
(0...canvas_size).step(cell_size) do |x|
(0...canvas_size).step(cell_size) do |y|
color = color(rand(360), 100, 100)
@faces << Face.new(cell_size, cell_size, color, x, y)
end
end
end
def draw
@faces.each(&:draw)
end
end
@face_grid = nil
def setup
canvas_size = 300
cell_size = 100
createCanvas(canvas_size, canvas_size)
color_mode(HSB)
@face_grid = FaceGrid.new(canvas_size, cell_size)
end
def draw
@face_grid.draw
end