class Boggler::Grid

Public Class Methods

new() click to toggle source
# File lib/boggler/grid.rb, line 3
def initialize
  @grid = []

  @dice = Dice.get
  @size = Math.sqrt(@dice.length).to_i

  build_grid
end

Public Instance Methods

to_s() click to toggle source
# File lib/boggler/grid.rb, line 12
def to_s
  row_strings = []

  @grid.each do |row|
    row_strings << row_string_for(row)
  end

  grid_string = separator
  row_strings.each do |row|
    grid_string += row
    grid_string += separator
  end

  grid_string
end
words() click to toggle source
# File lib/boggler/grid.rb, line 28
def words
  return @words if defined?(@words)

  @words = []

  @size.times do |i|
    @size.times do |j|
      words_starting_at(i + 1, j + 1)
    end
  end

  @words
end

Private Instance Methods

build_grid() click to toggle source
# File lib/boggler/grid.rb, line 67
def build_grid
  letters = []

  @dice.each_with_index do |die, i|
    if i % @size == 0
      @grid << letters unless letters.empty?
      letters = []
    end

    letters << die.roll
  end

  @grid << letters
end
next_possible_cell(cell) click to toggle source
# File lib/boggler/grid.rb, line 55
def next_possible_cell(cell)
  return unless cell
  candidate = cell && cell.next_cell
  while candidate && !candidate.possible_word?
    candidate = cell.next_cell
  end

  return candidate if candidate

  next_possible_cell cell.previous
end
row_string_for(row) click to toggle source
# File lib/boggler/grid.rb, line 82
def row_string_for(row)
  row_string = '|'
  row.each do |cell|
    row_string += " #{cell.upcase} |"
  end
  row_string + "\n"
end
separator() click to toggle source
# File lib/boggler/grid.rb, line 90
def separator
  @sep ||= '-' + ('-' * (4 * @size)) + "\n"
end
words_from_cell(cell) click to toggle source
# File lib/boggler/grid.rb, line 49
def words_from_cell(cell)
  @words << cell.word if cell.valid_word?
  next_cell = next_possible_cell(cell)
  words_from_cell(next_cell) if next_cell
end
words_starting_at(row, column) click to toggle source
# File lib/boggler/grid.rb, line 44
def words_starting_at(row, column)
  start_cell = Cell.new(@grid, row, column)
  words_from_cell start_cell
end