Last active
March 22, 2020 08:31
-
-
Save thara/86ddd4832d7e383ffedcb031ac8a5845 to your computer and use it in GitHub Desktop.
Conway's Game of Life written in Ruby, except classes; ported from https://gist.github.com/thara/ded6dd880ba95580088ef8875abb05e5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'set' | |
def neighbors(point) | |
return to_enum(:neighbors, point).to_a unless block_given? | |
x, y = point | |
yield [x + 1, y] | |
yield [x - 1, y] | |
yield [x, y + 1] | |
yield [x, y - 1] | |
yield [x + 1, y + 1] | |
yield [x + 1, y - 1] | |
yield [x - 1, y + 1] | |
yield [x - 1, y - 1] | |
end | |
def living?(point, board) | |
count = neighbors(point).count(&->(n) { board.include? n }) | |
count == 3 || (count == 2 && board.include?(point)) | |
end | |
def advance(board) | |
recalc = board | board.flat_map(&->(x) { neighbors(x) }).to_set | |
recalc.filter(&->(p) { living?(p, board) }).to_set | |
end | |
def print_board(state) | |
10.times.each do |x| | |
10.times.each do |y| | |
mark = state.include?([x, y]) ? '*' : '-' | |
print mark | |
end | |
print "\n" | |
end | |
end | |
state = Set.new([[0, 1], [1, 2], [2, 0], [2, 1], [2, 2]]) | |
print_board(state) | |
100.times.each do |_| | |
gets | |
print "\033[11A\r" | |
state = advance(state) | |
print_board(state) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment