Minesweeper 1 dimension version. English Posting

In last post, I used 2 dimension array. Below is 1 dimension version.

class Board
  def initialize(rows, cols)
    @rows, @cols = rows, cols
    @blocks = []
  end
 
  def add(block)
    @blocks[index(block.x, block.y)] = block
    block.board = self
    block
  end
 
  def get_block(x,y)
    @blocks[index(x,y)] if inside_board?(x,y)
  end
 
  def to_s
    str = ""
    @blocks.each_with_index do |block, index|
      str += "\n" if (index > 0 and (index+1) % @cols == 0)
      str += block.to_s    
    end
    str
  end
 
  def friends_of(block)
    candidates = []
    (block.x-1).upto(block.x+1) do |target_x|
      (block.y-1).upto(block.y) do |target_y|
        candidates << get_block(target_x, target_y)
      end
    end
    candidates.compact
  end
 
  #sometimes, minus index of Ruby array leads extra work. :-<
  def inside_board?(x,y)
    (x >= 0 and x < @cols and y >= 0 and y < @rows)
  end
 
  def index(x, y)
    @cols * y + x
  end
end

덧글

댓글 입력 영역