Last active
June 11, 2018 12:21
-
-
Save tzmfreedom/5e4f13300769df4437eb28caf80a877d to your computer and use it in GitHub Desktop.
This file contains 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
#!/usr/bin/env ruby | |
class LifeGame | |
attr_accessor :height, :width, :sleep_time | |
def initialize(height:, width:, sleep_time: 0.25) | |
@height = height | |
@width = width | |
@sleep_time = sleep_time | |
@field = Array.new(height) { Array.new(width) { rand(2) == 0 } } | |
end | |
def run | |
loop do | |
render | |
sleep sleep_time | |
set_new_field | |
clear_screen | |
end | |
end | |
private | |
def set_new_field | |
new_field = Array.new(height) { Array.new(width) } | |
height.times { |i| width.times { |j| new_field[i][j] = calc(i, j) } } | |
@field = new_field | |
end | |
def calc(i, j) | |
number = 0 | |
(i-1..i+1).each do |di| | |
(j-1..j+1).each do |dj| | |
next if di == i && dj == j | |
number += 1 if @field[di == height ? 0 : di][dj == width ? 0 : dj] | |
end | |
end | |
current = @field[i][j] | |
(!current && number == 3) || (current && (2..3) === number) | |
end | |
def render | |
puts @field.map { |cols| cols.map { |col| col ? '*' : ' ' }.join }.join("\n") | |
end | |
def clear_screen | |
puts "\033[2J" | |
end | |
end | |
LifeGame.new(height: ARGV[0] ? ARGV[0].to_i : 20, width: ARGV[1] ? ARGV[1].to_i : 50).run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment