-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworld.rb
89 lines (69 loc) · 1.95 KB
/
world.rb
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
82
83
84
85
86
87
require_relative 'game.rb'
require_relative 'cell.rb'
class World
attr_accessor :rows, :cols, :cell_grid, :cells
def initialize(rows = 10, cols = 10)
@rows = rows
@cols = cols
@cells = []
@cell_grid = Array.new(rows) do |row|
Array.new(cols) do |col|
Cell.new(col, row)
end
end
cell_grid.each do |row|
row.each do |element|
if element.is_a?(Cell)
cells << element
end
end
end
end
def cell_live_neighbours(cell)
live_neighbours = []
if cell.y < (rows - 1)
# Top
candidate = self.cell_grid[cell.y + 1][cell.x]
live_neighbours << candidate if candidate.alive?
end
if cell.y < (rows - 1) && cell.x < (cols - 1)
# Top right
candidate = self.cell_grid[cell.y + 1][cell.x + 1]
live_neighbours << candidate if candidate.alive?
end
if cell.x < (cols - 1)
# Right
candidate = self.cell_grid[cell.y][cell.x + 1]
live_neighbours << candidate if candidate.alive?
end
if cell.y > 0 && cell.x < (cols - 1)
# Bottom right
candidate = self.cell_grid[cell.y - 1][cell.x + 1]
live_neighbours << candidate if candidate.alive?
end
if cell.y > 0
# bottom
candidate = self.cell_grid[cell.y - 1][cell.x]
live_neighbours << candidate if candidate.alive?
end
if cell.y > 0 && cell.x > 0
# Bottom left
candidate = self.cell_grid[cell.y - 1][cell.x - 1]
live_neighbours << candidate if candidate.alive?
end
if cell.x > 0
# Left
candidate = self.cell_grid[cell.y][cell.x - 1]
live_neighbours << candidate if candidate.alive?
end
if cell.y < (rows - 1) && cell.x > 0
# Top left
candidate = self.cell_grid[cell.y + 1][cell.x - 1]
live_neighbours << candidate if candidate.alive?
end
live_neighbours
end
def randomly_update
cells.each { |cell| cell.alive = [true, false].sample }
end
end