Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def neighbors(cell)
- neighbors = []
- x = cell[0]
- y = cell[1]
- (x-1..x+1).each do |xx|
- (y-1..y+1).each do |yy|
- next if xx==x && yy==y
- neighbors.push([xx,yy])
- end
- end
- neighbors
- end
- def step(this_gen)
- next_gen = []
- dead_neighbors = []
- # all live cells
- this_gen.each do |cell|
- live_neighbors = []
- these_neighbors = neighbors(cell)
- these_neighbors.each do |this_neighbor|
- if (this_gen.include?(this_neighbor))
- live_neighbors.push(this_neighbor)
- elsif (!dead_neighbors.include?(this_neighbor))
- dead_neighbors.push(this_neighbor)
- end
- end
- next_gen.push(cell) if (live_neighbors.count >= 2 && live_neighbors.count <= 3)
- end
- # all dead neighbors
- dead_neighbors.each do |cell|
- live_neighbors = []
- these_neighbors = neighbors(cell)
- these_neighbors.each do |this_neighbor|
- live_neighbors.push(this_neighbor) if (this_gen.include?(this_neighbor))
- end
- next_gen.push(cell) if (live_neighbors.count == 3)
- end
- next_gen
- end
- def display(board,size=40)
- (1..size).each do |row|
- str = ""
- (1..size).each do |col|
- if (board.include?([row,col]))
- str += "O"
- else
- str += " "
- end
- end
- puts str
- end
- end
- def game_of_life(start_gen,generations)
- this_gen = start_gen
- while(generations>0)
- display(this_gen)
- next_gen = step(this_gen)
- generations -= 1
- this_gen = next_gen
- sleep 0.1
- end
- end
- start_gen = [[2,1],[3,2],[1,3],[2,3],[3,3]]
- game_of_life(start_gen,150)
Add Comment
Please, Sign In to add comment