-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworld.rb
More file actions
83 lines (65 loc) · 1.81 KB
/
world.rb
File metadata and controls
83 lines (65 loc) · 1.81 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
82
class World
attr_accessor :rows, :cols, :cell_board, :cells
def initialize(rows, cols)
@rows = rows
@cols = cols
@cells = []
@cell_board = Array.new(rows) do |row|
Array.new(cols) do |col|
Cell.new(col, row)
end
end
@cell_board.each do |row|
row.each do |element|
@cells << element
end
end
end
def live_neighbours(cell)
alive_neighbours = []
#up
if cell.y > 0
candidate = self.cell_board[cell.y - 1][cell.x]
alive_neighbours << candidate if candidate.alive?
end
#right
if cell.x < (cols - 1)
candidate = self.cell_board[cell.y][cell.x + 1]
alive_neighbours << candidate if candidate.alive?
end
#down
if cell.y < (rows - 1)
candidate = self.cell_board[cell.y + 1][cell.x]
alive_neighbours << candidate if candidate.alive?
end
#left
if cell.x > 0
candidate = self.cell_board[cell.y][cell.x - 1]
alive_neighbours << candidate if candidate.alive?
end
#up-right
if cell.y > 0 and cell.x < (cols - 1)
candidate = self.cell_board[cell.y - 1][cell.x + 1]
alive_neighbours << candidate if candidate.alive?
end
#down-right
if cell.y < (rows - 1) and cell.x < (cols - 1)
candidate = self.cell_board[cell.y + 1][cell.x + 1]
alive_neighbours << candidate if candidate.alive?
end
#down-left
if cell.y < (rows - 1) and cell.x > 0
candidate = self.cell_board[cell.y + 1][cell.x - 1]
alive_neighbours << candidate if candidate.alive?
end
#up-left
if cell.y > 0 and cell.x > 0
candidate = self.cell_board[cell.y - 1][cell.x - 1]
alive_neighbours << candidate if candidate.alive?
end
alive_neighbours
end
def live_cells
cells.select { |cell| cell.alive }
end
end