Created
June 12, 2018 19:41
-
-
Save etrex/9999836faa433046d44ab5af9e7c01fe to your computer and use it in GitHub Desktop.
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 GOL | |
| attr_accessor :size | |
| attr_accessor :board | |
| def initialize(size) | |
| @size = size | |
| reset_board | |
| end | |
| def reset_board | |
| @numbers = (0...size).to_a | |
| @board = Array.new(size*size, 0) | |
| randomize(size*size/2) | |
| end | |
| def randomize(n) | |
| (1..n).each do |i| | |
| x = @numbers.sample | |
| y = @numbers.sample | |
| board[x*size + y] = 1 | |
| end | |
| end | |
| def printboard | |
| system('clear') | |
| char_map = [' ', '@'] | |
| board.each.with_index do |cell, index| | |
| print char_map[cell] | |
| print "\n" if index % size == size - 1 | |
| end | |
| end | |
| def neighbor_by_index(index) | |
| x = index / size | |
| y = index % size | |
| xs = ((x-1)..(x+1)).to_a.map{|x| (x + size) % size } | |
| ys = ((y-1)..(y+1)).to_a.map{|y| (y + size) % size } | |
| neighbor = [] | |
| xs.each do |x| | |
| ys.each do |y| | |
| neighbor << board[x*size + y] | |
| end | |
| end | |
| neighbor | |
| end | |
| def step | |
| @board = @board.map.with_index do |cell, index| | |
| neighbor = neighbor_by_index(index) | |
| rule(neighbor) | |
| end | |
| end | |
| def rule(neighbor) | |
| count = neighbor.sum - neighbor[4] | |
| return 0 if count < 2 || count > 3 | |
| return 1 if neighbor[4] == 0 && count == 3 | |
| neighbor[4] | |
| end | |
| # def rule(neighbor) | |
| # neighbor[1] | |
| # end | |
| # def rule(neighbor) | |
| # neighbor[3] | |
| # end | |
| def run | |
| while true do | |
| printboard | |
| sleep(1.0 / 4) | |
| step | |
| end | |
| end | |
| end | |
| gol = GOL.new(20) | |
| gol.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment