-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame_of_life.rb
More file actions
83 lines (70 loc) · 2.09 KB
/
game_of_life.rb
File metadata and controls
83 lines (70 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
class GameOfLife
def get_next_grid(current_grid)
new_grid = current_grid
new_grid.each_with_index do |row, row_index|
row.each_with_index do |cell, column_index|
living_neighbours_count = number_of_living_neighbours(row_index, column_index, new_grid)
new_state_of_cell(cell, living_neighbours_count)
end
end
end
def new_state_of_cell(cell, living_neighbours_count)
if cell == :live && living_neighbours_count < 2
cell = :dead
elsif cell == :live && living_neighbours_count > 3
cell = :dead
elsif cell == :live && living_neighbours_count == 2
cell = :live
elsif cell == :live && living_neighbours_count == 3
cell == :live
elsif cell == :dead && living_neighbours_count == 3
cell = :live
else
cell = :dead
end
end
def number_of_living_neighbours(cell_row, cell_column, grid)
living_neighbours = 0
if grid[cell_row+1] != nil
if grid[cell_row+1][cell_column] == :live
living_neighbours += 1
end
end
if grid[cell_row-1] != nil
if grid[cell_row-1][cell_column] == :live
living_neighbours += 1
end
end
if grid[0][cell_column+1] != nil
if grid[cell_row][cell_column+1] == :live
living_neighbours += 1
end
end
if grid[0][cell_column-1] != nil
if grid[cell_row][cell_column-1] == :live
living_neighbours += 1
end
end
if grid[cell_row-1] != nil && grid[0][cell_column+1] != nil
if grid[cell_row-1][cell_column+1] == :live
living_neighbours += 1
end
end
if grid[cell_row+1] != nil && grid[0][cell_column-1] != nil
if grid[cell_row+1][cell_column-1] == :live
living_neighbours += 1
end
end
if grid[cell_row-1] != nil && grid[0][cell_column-1] != nil
if grid[cell_row-1][cell_column-1] == :live
living_neighbours += 1
end
end
if grid[cell_row+1] != nil && grid[0][cell_column+1] != nil
if grid[cell_row+1][cell_column+1] == :live
living_neighbours += 1
end
end
return living_neighbours
end
end