Created
February 10, 2012 04:38
-
-
Save thirtysixthspan/1786647 to your computer and use it in GitHub Desktop.
Sparse Sim Frost
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Particle | |
attr :x | |
attr :y | |
attr :state | |
def initialize(field, values = {}) | |
@field = field | |
@state = values[:state] || '.' | |
@next_state = @state | |
@x = values[:x] || rand(@field.size) | |
@y = values[:y] || rand(@field.size) | |
end | |
def at(x,y) | |
return true if @x == x && @y == y | |
false | |
end | |
def ==(p) | |
return true if self.at(p.x,p.y) | |
false | |
end | |
def <=>(p) | |
return false if self == p | |
return true if (@x - p.x).abs <= 1 && (@y - p.y).abs <= 1 | |
false | |
end | |
def display | |
"#{@state} #{@x} #{@y}" | |
end | |
def ice? | |
@state == '*' | |
end | |
def vapor? | |
@state == '.' | |
end | |
def freeze? | |
@field.neighbors(self).each { |p| return true if p.ice? } | |
false | |
end | |
def move | |
v = (rand(2)*2)-1 | |
if rand(2)==1 | |
@x+=v | |
else | |
@y+=v | |
end | |
end | |
def transform | |
if freeze? | |
@next_state = '*' | |
else | |
move | |
end | |
end | |
def evolve | |
@state=@next_state | |
end | |
end | |
class Field | |
attr :particles | |
attr :size | |
def initialize(n) | |
@size = 25 | |
@particles = [] | |
n.times { @particles << Particle.new(self) } | |
@particles << Particle.new(self, {:x=>@size/2, :y=>@size/2, :state=>'*'}) | |
end | |
def neighbors(p) | |
@particles.select { |x| x<=>p } | |
end | |
def at(x,y) | |
@particles.each { |p| return p if p.at(x,y) } | |
false | |
end | |
def display | |
@size.times do |y| | |
@size.times do |x| | |
p = self.at(x,y) | |
if p | |
print p.state | |
else | |
print ' ' | |
end | |
end | |
puts | |
end | |
end | |
def evolve | |
@particles.each { |p| p.transform } | |
@particles.each { |p| p.evolve } | |
end | |
end | |
f = Field.new(250) | |
loop do | |
puts `clear` | |
f.display | |
sleep 1 | |
f.evolve | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment