-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame_field.rb
106 lines (96 loc) · 2.41 KB
/
game_field.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
class GameField
require './cell'
def initialize(sort_variant, width, height)
@cells = []
@width = width
@height = height
case sort_variant
when 1
fill_random
when 2
fill_stable
when 3
fill_glider
end
end
def fill_random
@height.times do
line = []
@width.times do
line.push Cell.new(rand > 0.5)
end
@cells.push line
end
end
def fill_stable
cells = [
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[0, 1, 0, 1, 0, 1, 0, 1],
[0, 0, 1, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0]
]
fill_like cells
end
def fill_glider
glider = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
]
fill_like glider
end
def fill_like(figure)
@height = figure.length
@width = figure[0].length
figure.each do |row|
line = []
row.each do |val|
if val == 1
line.push Cell.new(true)
else
line.push Cell.new(false)
end
end
@cells.push line
end
end
def show_field
system 'clear'
@height.times do |i|
@width.times do |j|
print @cells[i][j].show + ' '
end
puts
end
end
def life_round
to_kill = []
to_born = []
@height.times do |i|
@width.times do |j|
neighbors = 0
neighbors += 1 if @cells[i - 1][j - 1].alive?
neighbors += 1 if @cells[i - 1][j].alive?
neighbors += 1 if @cells[i - 1][(j + 1) % @width].alive?
neighbors += 1 if @cells[i][j - 1].alive?
neighbors += 1 if @cells[i][(j + 1) % @width].alive?
neighbors += 1 if @cells[(i + 1) % @height][j - 1].alive?
neighbors += 1 if @cells[(i + 1) % @height][j].alive?
neighbors += 1 if @cells[(i + 1) % @height][(j + 1) % @width].alive?
to_kill.push [i, j] if neighbors != 2 && neighbors != 3
to_born.push [i, j] if neighbors == 3
end
end
to_kill.each { |point| @cells[point[0]][point[1]].kill}
to_born.each { |point| @cells[point[0]][point[1]].born }
end
end