Class: GameOfLife
- Inherits:
-
Object
- Object
- GameOfLife
- Defined in:
- lib/GameOfLife.rb
Instance Attribute Summary collapse
-
#column ⇒ Object
Returns the value of attribute column.
-
#last_column ⇒ Object
Returns the value of attribute last_column.
-
#last_row ⇒ Object
Returns the value of attribute last_row.
-
#row ⇒ Object
Returns the value of attribute row.
Instance Method Summary collapse
- #display_board(board) ⇒ Object
- #get_neighbors(board, row, column) ⇒ Object
-
#initialize(row, column) ⇒ GameOfLife
constructor
A new instance of GameOfLife.
- #next_board(board) ⇒ Object
Constructor Details
#initialize(row, column) ⇒ GameOfLife
Returns a new instance of GameOfLife.
7 8 9 10 11 12 |
# File 'lib/GameOfLife.rb', line 7 def initialize(row,column) @row = row @column = column @last_row = row.to_i-1 @last_column = column.to_i-1 end |
Instance Attribute Details
#column ⇒ Object
Returns the value of attribute column.
3 4 5 |
# File 'lib/GameOfLife.rb', line 3 def column @column end |
#last_column ⇒ Object
Returns the value of attribute last_column.
5 6 7 |
# File 'lib/GameOfLife.rb', line 5 def last_column @last_column end |
#last_row ⇒ Object
Returns the value of attribute last_row.
4 5 6 |
# File 'lib/GameOfLife.rb', line 4 def last_row @last_row end |
#row ⇒ Object
Returns the value of attribute row.
2 3 4 |
# File 'lib/GameOfLife.rb', line 2 def row @row end |
Instance Method Details
#display_board(board) ⇒ Object
13 14 15 16 17 18 19 20 |
# File 'lib/GameOfLife.rb', line 13 def display_board(board) board.each.with_index do |row, i| row.each.with_index do |cell, j| print board[i][j] == 1 ? "0" : " " end puts end end |
#get_neighbors(board, row, column) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/GameOfLife.rb', line 21 def get_neighbors(board, row, column) row_max = [row - 1, 0].max row_min = [row + 1, @last_row.to_i].min column_max = [column - 1, 0].max column_min = [column + 1, @last_column].min array_neighbors = [] (row_max..row_min).each do |i| (column_max..column_min).each do |j| unless i == row and j == column array_neighbors << board[i][j] end end end return array_neighbors.inject(:+) end |
#next_board(board) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/GameOfLife.rb', line 36 def next_board(board) i = 1 while i <= 100 temp_board = Array.new(@row){Array.new(@column){ 0 } } system("clear") board.each.with_index do |row, i| row.each.with_index do |cell, j| neighbors = get_neighbors(board,i,j) if board[i][j] == 1 and neighbors < 2 temp_board[i][j] = 0 elsif board[i][j] == 1 and neighbors > 3 temp_board[i][j] = 0 elsif board[i][j] == 1 and neighbors == 3 || neighbors == 2 temp_board[i][j] = 1 elsif board[i][j] == 0 and neighbors == 3 temp_board[i][j] = 1 end end end board = temp_board display_board(board) puts "Iterations: #{i}" sleep(0.2) i+=1 end end |