-
Notifications
You must be signed in to change notification settings - Fork 0
/
game_of_life.rb
111 lines (96 loc) · 2.22 KB
/
game_of_life.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
107
108
109
110
111
# coding: utf-8
def generate_world
row_limit = WORLD_SIZE[0]
column_limit = WORLD_SIZE[1]
world = []
loop do
break if world.size == row_limit
column = []
loop do
break if column.size == column_limit
column << rand(2)
end
world << column
end
world
end
def next_generation world
new_gen = world.map.with_index do |rval, row|
rval.map.with_index do |val, col|
next_generation_state row, col, world
end
end
new_gen
end
def next_generation_state row, col, world
states = get_neighbour_cell_states row, col, world
population = states.select{ |state| state >= 0 }.inject(:+).to_i
if is_a_live_cell? row, col, world
return 0 if under_populated? population
return 0 if over_populated? population
return 1 if normally_populated? population
else
return 1 if will_come_to_life? population
return 0
end
end
def get_neighbour_cell_states row, col, world
row_limit = WORLD_SIZE[0] - 1
column_limit = WORLD_SIZE[1] - 1
neighbours = get_neighbour_cells row, col
cells = neighbours.map do |cell|
row = cell[0]
column = cell[1]
if (row > row_limit) || (row < 0) || (column > column_limit) || (column < 0)
-1
else
world[row][column]
end
end
cells
end
def get_neighbour_cells row, col
cells = [[row, col+1], [row, col-1], [row+1, col], [row-1, col], [row-1, col-1], [row+1, col+1], [row-1, col+1], [row+1, col-1]]
cells
end
def is_a_live_cell? row, col, world
world[row][col] == 1
end
def under_populated? population
population < 2
end
def over_populated? population
population > 3
end
def normally_populated? population
(population == 2) || (population == 3)
end
def will_come_to_life? population
population == 3
end
if !ARGV[0].nil? && !ARGV[1].nil?
WORLD_SIZE = [ARGV[0].to_i, ARGV[1].to_i]
else
WORLD_SIZE = [20, 30]
end
system('clear')
world = generate_world
# world = [[0,0,0,0,0],
# [0,0,1,1,1],
# [0,1,1,1,0],
# [0,0,0,0,0]]
loop do
system('clear')
world = next_generation(world)
printable = world.map do |cell|
cell.map do |c|
if c == 1
"\e[32m👹\e[0m"
else
"◽"
end
end.join(" ")
end.join("\n\n")
puts printable
sleep 0.5
end