class Battleships::CoordinateHandler

Constants

COORD_REGEX
HORIZONTAL_COORDS
VERTICAL_COORDS

Public Instance Methods

each() { |coordinate x, y| ... } click to toggle source
# File lib/battleships/coordinate_handler.rb, line 9
def each
  VERTICAL_COORDS.each do |y|
    HORIZONTAL_COORDS.each do |x|
      yield coordinate x, y
    end
  end
end
each_row() { |row, y| ... } click to toggle source
# File lib/battleships/coordinate_handler.rb, line 17
def each_row
  VERTICAL_COORDS.each do |y|
    row = HORIZONTAL_COORDS.map do |x|
      coordinate x, y
    end
    yield row, y
  end
end
from(start, size, orientation = :horizontally) click to toggle source
# File lib/battleships/coordinate_handler.rb, line 34
def from start, size, orientation = :horizontally
  match = COORD_REGEX.match start

  x = match.captures.first
  y = match.captures.last

  if orientation.to_sym == :horizontally
    horizontal_coords_for x, y, size
  else
    vertical_coords_for x, y, size
  end
end
valid?(coord) click to toggle source
# File lib/battleships/coordinate_handler.rb, line 30
def valid? coord
  COORD_REGEX.match coord.to_s
end
validate(coord) click to toggle source
# File lib/battleships/coordinate_handler.rb, line 26
def validate coord
  fail 'Invalid coordinate' unless valid? coord
end

Private Instance Methods

coordinate(x, y) click to toggle source
# File lib/battleships/coordinate_handler.rb, line 67
def coordinate x, y
  "#{x}#{y}".to_sym
end
horizontal_coords_for(x, y, size) click to toggle source
# File lib/battleships/coordinate_handler.rb, line 49
def horizontal_coords_for x, y, size
  x_coords(x, size).map { |x| coordinate x, y }
end
vertical_coords_for(x, y, size) click to toggle source
# File lib/battleships/coordinate_handler.rb, line 58
def vertical_coords_for x, y, size
  y_coords(y, size).map { |y| coordinate x, y }
end
x_coords(x, size) click to toggle source
# File lib/battleships/coordinate_handler.rb, line 53
def x_coords x, size
  start = HORIZONTAL_COORDS.index x
  HORIZONTAL_COORDS.slice start, size
end
y_coords(y, size) click to toggle source
# File lib/battleships/coordinate_handler.rb, line 62
def y_coords y, size
  start = VERTICAL_COORDS.index Integer(y)
  VERTICAL_COORDS.slice start, size
end