-
Notifications
You must be signed in to change notification settings - Fork 0
/
life.rb
executable file
·82 lines (66 loc) · 1.86 KB
/
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
#!/usr/local/bin/ruby
# little game of life -- tested on ruby-1.9.3
# © 7-9-2015 ~devoidfury -- furycodes.com
# I'm only meh at ruby, so we'll see how this goes.
# board is auto-generated, 50/50
require "curses"
include Curses
# ensure clean exit -----------------------
#def clean_exit(sig)
# close_screen # clean up tty
# exit sig # clean exit
#end
#(1..15).each do |i|
# if trap(i, "SIG_IGN") != 0 then
# trap(15) {|sig| clean_exit(sig) }
# end
#end
# fire it up -------------------------------
init_screen
nl
noecho # dont print user input
srand # seed random
height = cols
width = lines
life = Array.new(width+1) { Array.new(height+1) {rand(0..1)} }
while 1
now_state = Array.new(width+1) {Array.new(height+1, 0)}
for x in 0 .. width
for y in 0 .. height
# count neighbors
count = 0;
for i in ([x-1, 0].max) .. ([x+1, width-1].min)
for j in ([y-1, 0].max) .. ([y+1, height-1].min)
count += life[i][j] unless i == x and j == y
end
end
now_state[x][y] = count
end
end
for x in 0 .. width
for y in 0 .. height
# 1) Any live cell with fewer than two live neighbours dies,
# as if caused by under-population.
# 2) Any live cell with two or three live neighbours lives on
# to the next generation.
# 3) Any live cell with more than three live neighbours dies, as
# if by overcrowding.
# 4) Any dead cell with exactly three live neighbours becomes a
# live cell, as if by reproduction.
if life[x][y] == 0
if now_state[x][y] == 3
life[x][y] = 1 # (rule 4)
end
elsif now_state[x][y] > 3 or now_state[x][y] < 2
life[x][y] = 0 # (rule 1 and 3)
end
# (rule 2 implicit)
# draw the game
setpos(x, y)
addstr(life[x][y] == 1 ? "#" : " ")
end
end
# flush buffer to screen and pause
refresh
sleep(0.02)
end