导入
介绍我们的基础网格
了解本课程中我们将如何创建网格的概览。
1# 创建一个 10x10 的网格 2grid = Grid.new(10, 10) 3# 获取第 1 行第 2 列的单元格 4cell = grid[1, 2] 5# 遍历网格中的所有单元格 6grid.each_cell do |cell| 7 # 对单元格进行操作 8end
...
网格结构
1class Cell 2 attr_reader :row, :column 3 attr_accessor :north, :south, :east, :west 4end
1def initialize(row, column) 2 @row, @column = row, column 3 @links = {} 4end
1def link(cell, bidi=true) 2 @links[cell] = true 3 cell.link(self, false) if bidi 4end 5 6def unlink(cell, bidi=true) 7 @links.delete(cell) 8 cell.unlink(self, false) if bidi 9 self 10end
1def links 2 @links.keys 3end 4 5def linked?(cell) 6 @links.key?(cell) 7end
1def neighbors 2 list = [] 3 list << north if north 4 list << south if south 5 list << east if east 6 list << west if west 7 list 8end
1class Cell 2 attr_reader :row, :column 3 attr_accessor :north, :south, :east, :west 4 def initialize(row, column) 5 @row, @column = row, column 6 @links = {} 7 end 8 def link(cell, bidi=true) 9 @links[cell] = true 10 cell.link(self, false) if bidi 11 end 12 13 def unlink(cell, bidi=true) 14 @links.delete(cell) 15 cell.unlink(self, false) if bidi 16 self 17 end 18 def neighbors 19 list = [] 20 list << north if north 21 list << south if south 22 list << east if east 23 list << west if west 24 list 25 end 26end