class Boggler::Cell

Constants

MOVES

Attributes

column[R]
letter[R]
previous[R]
row[R]
word[R]

Public Class Methods

new( grid, row, column, dictionary = nil, used = nil, previous = nil) click to toggle source
# File lib/boggler/cell.rb, line 16
def initialize(
    grid, row, column, dictionary = nil, used = nil, previous = nil)
  @row    = row
  @column = column
  @letter = grid[row - 1][column - 1]
  @grid   = grid
  @previous = previous
  @dictionary = dictionary || Dictionary.words

  set_used used
  @used[row][column] = true

  @word = ((previous && previous.word) || '') + @letter
  set_dictionary
end

Public Instance Methods

next_cell() click to toggle source
# File lib/boggler/cell.rb, line 32
def next_cell
  begin
    iterator.next
  rescue StopIteration
    nil
  end
end
possible_word?() click to toggle source
# File lib/boggler/cell.rb, line 44
def possible_word?
  !!@dictionary
end
valid_word?() click to toggle source
# File lib/boggler/cell.rb, line 40
def valid_word?
  !!@dictionary['']
end

Private Instance Methods

iterator() click to toggle source
# File lib/boggler/cell.rb, line 71
def iterator
  @iterator ||= neighbors.each
end
neighbors() click to toggle source
# File lib/boggler/cell.rb, line 75
def neighbors
  return @neighbors if @neighbors

  @neighbors = []

  MOVES.each do |move|
    next_row    = row + move.first
    next_column = column + move.last

    if next_row > 0 && next_row <= @grid.size &&
        next_column > 0 && next_column <= @grid.size &&
        !@used[next_row][next_column]
      @neighbors << Cell.new(
        @grid, next_row, next_column, @dictionary, @used, self)
    end
  end

  @neighbors
end
set_dictionary() click to toggle source
# File lib/boggler/cell.rb, line 50
def set_dictionary
  case word.length
  when 1, 2
    @dictionary = {}
  when 3
    @dictionary = Dictionary.words[@word]
  else
    @dictionary = @dictionary[@word[-1]]
  end
end
set_used(used) click to toggle source
# File lib/boggler/cell.rb, line 61
def set_used(used)
  @used = used && used.dup
  @used ||= {}

  @grid.size.times do |i|
    row = used && used[i + 1] && used[i + 1].dup
    @used[i + 1] = row || {}
  end
end