Skip to content

Instantly share code, notes, and snippets.

@zunda
Last active June 3, 2018 02:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zunda/58f41c1d6325c53107f1c90129ac1fb1 to your computer and use it in GitHub Desktop.
Save zunda/58f41c1d6325c53107f1c90129ac1fb1 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
class Board
Alive = 'πŸ₯“'
Dead = 'πŸ₯š'
Neighbors = [[-1,-1], [0,-1], [1,-1], [-1,0], [1,0], [-1,1], [0,1], [1,1]]
Glider = <<_END
πŸ₯šπŸ₯“πŸ₯š
πŸ₯šπŸ₯šπŸ₯“
πŸ₯“πŸ₯“πŸ₯“
_END
LightweightSpaceship = <<_END
πŸ₯“πŸ₯šπŸ₯šπŸ₯“πŸ₯š
πŸ₯šπŸ₯šπŸ₯šπŸ₯šπŸ₯“
πŸ₯“πŸ₯šπŸ₯šπŸ₯šπŸ₯“
πŸ₯šπŸ₯“πŸ₯“πŸ₯“πŸ₯“
_END
def initialize(w = 20, h = 20, seed = nil)
@w = w
@h = h
@board = Array.new(h){Array.new(w){Dead}}
@count = Array.new(h){Array.new(w)}
if seed
seed.split(/\n/).each_with_index do |line, r|
line.scan(/./).each_with_index do |char, c|
@board[r][c] = char
end
end
else
(@w * @h / 5).times do
@board[Random.rand(@h)][Random.rand(@w)] = Alive
end
end
end
def neighbors(r, c)
n = 0
Neighbors.each do |dr, dc|
n += 1 if @board[(r + dr) % @h][(c + dc) % @w] == Alive
end
return n
end
def step
@h.times do |r|
@w.times do |c|
@count[r][c] = neighbors(r, c)
end
end
changed = false
@h.times do |r|
@w.times do |c|
if @board[r][c] == Alive
if @count[r][c] < 2 or @count[r][c] > 3
@board[r][c] = Dead
changed = true
end
else # Dead
if @count[r][c] == 3
@board[r][c] = Alive
changed = true
end
end
end
end
return changed
end
def to_s
@board.map{|line| line.join("")}.join("\n")
end
end
b = Board.new(39, 24, Board::Glider + "\n"*10 + Board::LightweightSpaceship)
ClearScreen = "\u001b[2J"
MoveToHome = "\u001b[1;1H"
print ClearScreen
print MoveToHome
puts b
while b.step
sleep 0.1
print MoveToHome
puts b
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment