Guest User

Untitled

a guest
Apr 20th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.60 KB | None | 0 0
  1. def neighbors(cell)
  2.   neighbors = []
  3.   x = cell[0]
  4.   y = cell[1]
  5.   (x-1..x+1).each do |xx|
  6.     (y-1..y+1).each do |yy|
  7.      next if xx==x && yy==y
  8.      neighbors.push([xx,yy])
  9.     end
  10.   end
  11.   neighbors
  12. end
  13.  
  14. def step(this_gen)
  15.   next_gen        = []
  16.   dead_neighbors  = []
  17.  
  18.   # all live cells
  19.   this_gen.each do |cell|
  20.     live_neighbors  = []
  21.     these_neighbors = neighbors(cell)
  22.    
  23.     these_neighbors.each do |this_neighbor|
  24.       if (this_gen.include?(this_neighbor))
  25.         live_neighbors.push(this_neighbor)
  26.       elsif (!dead_neighbors.include?(this_neighbor))
  27.         dead_neighbors.push(this_neighbor)
  28.       end
  29.     end
  30.     next_gen.push(cell) if (live_neighbors.count >= 2 && live_neighbors.count <= 3)
  31.   end
  32.  
  33.   # all dead neighbors
  34.   dead_neighbors.each do |cell|
  35.     live_neighbors  = []
  36.     these_neighbors = neighbors(cell)
  37.    
  38.     these_neighbors.each do |this_neighbor|
  39.       live_neighbors.push(this_neighbor) if (this_gen.include?(this_neighbor))
  40.     end
  41.     next_gen.push(cell) if (live_neighbors.count == 3)
  42.   end
  43.  
  44.   next_gen
  45. end
  46.  
  47. def display(board,size=40)
  48.   (1..size).each do |row|
  49.     str = ""
  50.     (1..size).each do |col|
  51.       if (board.include?([row,col]))
  52.         str += "O"
  53.       else
  54.         str += " "
  55.       end
  56.     end
  57.     puts str
  58.   end
  59. end
  60.  
  61. def game_of_life(start_gen,generations)
  62.   this_gen = start_gen
  63.   while(generations>0)
  64.     display(this_gen)
  65.     next_gen = step(this_gen)
  66.     generations -= 1
  67.     this_gen = next_gen
  68.     sleep 0.1
  69.   end
  70. end
  71.  
  72. start_gen = [[2,1],[3,2],[1,3],[2,3],[3,3]]
  73. game_of_life(start_gen,150)
Add Comment
Please, Sign In to add comment