Somewhat more concise code in ruby-processing cf the vanilla-processing original (replaced 0, 1 DEAD-ALIVE with a boolean for which they were only place-holder and hence much scope to dry code).
CELL_SIZE = 5
ALIVE = true
DEAD = false
ALIVE_START = 150
INTERVAL = 100
attr_reader :pause, :cells, :row, :column, :last_time, :alive, :cells_buffer
def setup
size(960, 640)
@pause = false
@row = width / CELL_SIZE
@column = height / CELL_SIZE
@cells = Array.new(row) {Array.new(column) {(rand(1000) > ALIVE_START)? DEAD : ALIVE}}
@last_time = 0
@alive = color(100, 255, 100)
stroke(48, 100)
noSmooth
end
def draw
background(0)
row.times do |x|
column.times do |y|
if (cells[x][y])
fill(alive)
rect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE)
end
end
end
if (millis - last_time > INTERVAL)
if (!pause)
tick!
@last_time = millis
end
end
if (pause && mouse_pressed?)
xCellOver = (map(mouseX, 0, width, 0, row)).to_i
xCellOver = constrain(xCellOver, 0, row - 1)
yCellOver = (map(mouseY, 0, height, 0, column)).to_i
yCellOver = constrain(yCellOver, 0, column - 1)
if (cells_buffer[xCellOver][yCellOver])
cells[xCellOver][yCellOver] = DEAD
fill(0)
else
cells[xCellOver][yCellOver] = ALIVE
fill(alive)
end
elsif (pause && !mouse_pressed?)
@cells_buffer = clone2d(cells)
end
end
def tick!
@cells_buffer = clone2d(cells)
row.times do |x|
column.times do |y|
neighbours = 0
(x - 1 .. x + 1).each do |xx|
(y - 1 .. y + 1).each do |yy|
if [(xx>=0), (xx<row), (yy>=0), (yy<column)].all? {|in_bounds| in_bounds == true}
if ![(xx == x), (yy == y)].all? {|is_self| is_self == true}
if (cells_buffer[xx][yy])
neighbours += 1
end
end
end
end
end
cells[x][y] = (cells_buffer[x][y])? ((2 .. 3) === neighbours) : (neighbours == 3)
end
end
end
def key_pressed
case key
when 'r', 'R'
@cells = Array.new(row) {Array.new(column) {(rand(1000) > ALIVE_START)? DEAD : ALIVE}}
when ' '
@pause = !pause
when 'c', 'C'
@cells = Array.new(row) {Array.new(column) {DEAD}}
end
end
def clone2d array
result = []
array.each do |val|
result << val.clone
end
return result
end
No comments:
Post a Comment