class Battleship::Grid

Constants

COORD_ERR
HIT
MISS
PLACE_ERR
SINK
SIZE

Attributes

bot_left[R]
ships[R]
top_right[R]

Public Class Methods

factory(coord_class=Coord) click to toggle source
# File lib/battleship/grid.rb, line 17
def self.factory(coord_class=Coord)
  new(coord_class.orig, coord_class.new(SIZE, SIZE))
end
new(bot_left, top_right) click to toggle source
# File lib/battleship/grid.rb, line 25
def initialize(bot_left, top_right)
  @bot_left = bot_left
  @top_right = top_right 
  @ships = []
end

Public Instance Methods

<<(ship) click to toggle source
# File lib/battleship/grid.rb, line 35
def <<(ship)
  fail PlacingError.new(PLACE_ERR) unless valid?(ship)
  ships << ship
end
footprint() click to toggle source
# File lib/battleship/grid.rb, line 49
def footprint
  ships.map(&:footprint).flatten
end
shot(coord) click to toggle source
# File lib/battleship/grid.rb, line 40
def shot(coord)
  fail PlacingError.new(COORD_ERR.call(self)) unless included?(coord)
  data = damages(coord)
  purge!
  return SINK if data.any? { |d| d < 0 }
  return HIT if data.any? { |d| d > 0 }
  MISS
end
to_s() click to toggle source
# File lib/battleship/grid.rb, line 31
def to_s
  "bot_left=#{bot_left} top_right=#{top_right} ships=#{ships.size}"
end

Private Instance Methods

damages(coord) click to toggle source
# File lib/battleship/grid.rb, line 53
        def damages(coord)
  ships.reduce([]) do |acc, ship|
    damage = ship.strike(coord)
    acc << damage
  end
end
included?(coord) click to toggle source
# File lib/battleship/grid.rb, line 72
        def included?(coord)
  coord >= bot_left && coord <= top_right
end
overlap?(ship) click to toggle source
# File lib/battleship/grid.rb, line 76
        def overlap?(ship)
  footprint.any? do |coord|
    ship.footprint.any? { |c| c == coord }
  end
end
purge!() click to toggle source
# File lib/battleship/grid.rb, line 60
        def purge!
  ships.reject!(&:empty?)
end
valid?(ship) click to toggle source
# File lib/battleship/grid.rb, line 64
        def valid?(ship)
  within?(ship) && !overlap?(ship)
end
within?(ship) click to toggle source
# File lib/battleship/grid.rb, line 68
        def within?(ship)
  ship.footprint.all? { |coord| included?(coord) }
end