class Battleships::Board
Constants
- SIZE
Attributes
coord_handler[R]
grid[R]
width[RW]
Public Class Methods
new()
click to toggle source
# File lib/battleships/board.rb, line 10 def initialize @grid = {} @coord_handler = CoordinateHandler.new @ships = [] initialize_grid end
Public Instance Methods
[](coordinate)
click to toggle source
# File lib/battleships/board.rb, line 54 def [] coordinate coord_handler.validate coordinate grid[coordinate] end
all_ships_sunk?()
click to toggle source
# File lib/battleships/board.rb, line 59 def all_ships_sunk? return false if ships.empty? ships.all?(&:sunk?) end
height()
click to toggle source
# File lib/battleships/board.rb, line 28 def height SIZE end
inspect()
click to toggle source
# File lib/battleships/board.rb, line 64 def inspect to_s end
place_ship(ship, coordinate, orientation = :horizontally)
click to toggle source
# File lib/battleships/board.rb, line 17 def place_ship ship, coordinate, orientation = :horizontally coords = all_ship_coords ship, coordinate, orientation coords.each { |coord| grid[coord].content = ship } @ships << ship end
receive_shot(coordinate)
click to toggle source
# File lib/battleships/board.rb, line 39 def receive_shot coordinate coord_handler.validate coordinate validate_coord_not_shot coordinate cell = grid[coordinate] cell.receive_shot if cell.content cell.content.sunk? ? :sunk : :hit else :miss end end
ships()
click to toggle source
# File lib/battleships/board.rb, line 32 def ships # note we do not pass the source array here as it would enable # callers to modify the board's ships, which would break encapsulation. # Instead we return a duplicate. @ships.dup end
Private Instance Methods
all_ship_coords(ship, coord, orientation)
click to toggle source
# File lib/battleships/board.rb, line 78 def all_ship_coords ship, coord, orientation coord_handler.validate coord all_coords = coord_handler.from coord, ship.size, orientation validate_all_ship_coords all_coords, ship.size end
initialize_grid()
click to toggle source
# File lib/battleships/board.rb, line 72 def initialize_grid coord_handler.each do |coord| grid[coord] = Cell.new end end
validate_all_coords_available(coords)
click to toggle source
# File lib/battleships/board.rb, line 93 def validate_all_coords_available coords coords.each do |coord| fail 'Coordinate already occupied' unless grid[coord].empty? end end
validate_all_ship_coords(coords, size)
click to toggle source
# File lib/battleships/board.rb, line 86 def validate_all_ship_coords coords, size #ship is out of bounds if the ship is larger than the available coords fail 'Out of bounds' if size > coords.length validate_all_coords_available coords end
validate_coord_not_shot(coord)
click to toggle source
# File lib/battleships/board.rb, line 99 def validate_coord_not_shot coord fail 'Coordinate has been shot already' if grid[coord].shot? end