class Battleship::Ship

Constants

LARGE_LEN
SMALL_LEN
WIDTH

Attributes

footprint[RW]
len[RW]
name[RW]
wid[RW]

Public Class Methods

large() click to toggle source
# File lib/battleship/ship.rb, line 17
def self.large
  new(LARGE_LEN, WIDTH, "large (#{LARGE_LEN}x#{WIDTH})")
end
new(len, wid, name=nil) click to toggle source
# File lib/battleship/ship.rb, line 23
def initialize(len, wid, name=nil)
  @len = len.to_i
  @wid = wid.to_i
  @name = name.to_s
  @footprint = []
end
small() click to toggle source
# File lib/battleship/ship.rb, line 13
def self.small
  new(SMALL_LEN, WIDTH, "small (#{SMALL_LEN}x#{WIDTH})")
end

Public Instance Methods

place(position) click to toggle source
# File lib/battleship/ship.rb, line 34
def place(position)
  coord = position.coord
  @footprint = case position.cardinal
  when 'N'
    len.times.map { |i| coord.class.new(coord.x, coord.y + i) }
  when 'E'
    len.times.map { |i| coord.class.new(coord.x + i, coord.y) }
  when 'S'
    len.times.map { |i| coord.class.new(coord.x, coord.y - i) }
  when 'W'
    len.times.map { |i| coord.class.new(coord.x - i, coord.y) }
  when 'NE'
    len.times.map { |i| coord.class.new(coord.x + i, coord.y + i) }
  when 'NW'
    len.times.map { |i| coord.class.new(coord.x - i, coord.y + i) }
  when 'SE'
    len.times.map { |i| coord.class.new(coord.x + i, coord.y - i) }
  when 'SW'
    len.times.map { |i| coord.class.new(coord.x - i, coord.y - i) }
  end
end
strike(coord) click to toggle source
# File lib/battleship/ship.rb, line 56
def strike(coord)
  hit = @footprint.delete(coord)
  return -1 if empty?
  return 1 if hit
  0
end
to_s() click to toggle source
# File lib/battleship/ship.rb, line 30
def to_s
  "len=#{len} wid=#{wid} footprint=(#{footprint.map(&:to_s).join(', ')})"
end