Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # ดัดแปลงจากตัวอย่างในภาษา fe (github.com/rxi/fe)/ มาเป็น ruby
- def print_grid(grid)
- grid.each do |row|
- print row.map {|cell| cell==0?" ":"#"}, "\n"
- end
- end
- def get_cell(grid, x, y)
- if x < 0 or y < 0 or y >= grid.length or x >= grid[y].length
- return 0
- end
- grid[y][x]
- end
- def next_cell(grid, cell, x, y)
- n = get_cell(grid, (x - 1), (y - 1)) +
- get_cell(grid, (x - 1), y) +
- get_cell(grid, (x - 1), (y + 1)) +
- get_cell(grid, x, (y - 1)) +
- get_cell(grid, x, (y + 1)) +
- get_cell(grid, (x + 1), (y - 1)) +
- get_cell(grid, (x + 1), y) +
- get_cell(grid, (x + 1), (y + 1))
- if cell == 1 and (n == 2 or n == 3)
- return 1
- end
- if cell == 0 and n == 3
- return 1
- end
- 0
- end
- def next_grid(grid)
- y = -1
- grid.map {|row|
- y += 1
- x = -1
- row.map {|cell|
- x += 1
- next_cell grid,cell,x,y
- }
- }
- # ngrid = []
- # for y in 0...grid.length
- # ngrid[y]=[]
- # for x in 0...grid[y].length
- # ngrid[y][x] = next_cell grid, grid[y][x], x, y
- # end
- # end
- # ngrid
- end
- def life(n, grid)
- i = 1
- puts grid.length
- while i <= n
- puts ">> iteration #{i}"
- print_grid grid
- puts
- grid = next_grid grid
- i += 1
- end
- end
- # blinker in a 3x3 universe
- life(2, [
- [0, 1, 0],
- [0, 1, 0],
- [0, 1, 0]
- ])
- # glider in an 8x8 universe
- life(22, [
- [0, 0, 1, 0, 0, 0, 0, 0],
- [0, 0, 0, 1, 0, 0, 0, 0],
- [0, 1, 1, 1, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0],
- [0, 0, 0, 0, 0, 0, 0, 0]
- ])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement