Advertisement
wwwRong

conway's game of life rb

Apr 30th, 2021
1,618
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.81 KB | None | 0 0
  1. # ดัดแปลงจากตัวอย่างในภาษา fe (github.com/rxi/fe)/ มาเป็น ruby
  2.  
  3. def print_grid(grid)
  4.     grid.each do |row|
  5.         print row.map {|cell| cell==0?" ":"#"}, "\n"
  6.     end
  7. end
  8.  
  9. def get_cell(grid, x, y)
  10.     if x < 0 or y < 0 or y >= grid.length or x >= grid[y].length
  11.         return 0
  12.     end
  13.     grid[y][x]
  14. end
  15.  
  16. def next_cell(grid, cell, x, y)
  17.     n = get_cell(grid, (x - 1), (y - 1)) +
  18.         get_cell(grid, (x - 1), y) +
  19.         get_cell(grid, (x - 1), (y + 1)) +
  20.         get_cell(grid, x, (y - 1)) +
  21.         get_cell(grid, x, (y + 1)) +
  22.         get_cell(grid, (x + 1), (y - 1)) +
  23.         get_cell(grid, (x + 1), y) +
  24.         get_cell(grid, (x + 1), (y + 1))
  25.     if cell == 1 and (n == 2 or n == 3)
  26.         return 1
  27.     end
  28.     if cell == 0 and n == 3
  29.         return 1
  30.     end
  31.     0
  32. end
  33.  
  34. def next_grid(grid)
  35.     y = -1
  36.     grid.map {|row|
  37.       y += 1
  38.       x = -1
  39.       row.map {|cell|
  40.         x += 1
  41.         next_cell grid,cell,x,y
  42.       }
  43.     }
  44. #    ngrid = []
  45. #    for y in 0...grid.length
  46. #        ngrid[y]=[]
  47. #        for x in 0...grid[y].length
  48. #            ngrid[y][x] = next_cell grid, grid[y][x], x, y
  49. #        end
  50. #    end
  51. #    ngrid
  52. end
  53.  
  54. def life(n, grid)
  55.     i = 1
  56.     puts grid.length
  57.     while i <= n
  58.         puts ">> iteration #{i}"
  59.         print_grid grid
  60.         puts
  61.         grid = next_grid grid
  62.         i += 1
  63.     end
  64. end
  65.  
  66. # blinker in a 3x3 universe
  67. life(2, [
  68.     [0, 1, 0],
  69.     [0, 1, 0],
  70.     [0, 1, 0]
  71. ])
  72.  
  73.  
  74. # glider in an 8x8 universe
  75. life(22, [
  76.     [0, 0, 1, 0, 0, 0, 0, 0],
  77.     [0, 0, 0, 1, 0, 0, 0, 0],
  78.     [0, 1, 1, 1, 0, 0, 0, 0],
  79.     [0, 0, 0, 0, 0, 0, 0, 0],
  80.     [0, 0, 0, 0, 0, 0, 0, 0],
  81.     [0, 0, 0, 0, 0, 0, 0, 0],
  82.     [0, 0, 0, 0, 0, 0, 0, 0],
  83.     [0, 0, 0, 0, 0, 0, 0, 0]
  84. ])
  85.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement