Skip to content

Instantly share code, notes, and snippets.

@EdmundLeex
Created August 13, 2015 15:11
Show Gist options
  • Save EdmundLeex/39b8596dfffad8453175 to your computer and use it in GitHub Desktop.
Save EdmundLeex/39b8596dfffad8453175 to your computer and use it in GitHub Desktop.
class Board
attr_reader :grid
def initialize(grid = nil)
@grid = grid || self.class.default_grid
end
def self.default_grid
Array.new(10) { Array.new(10) }
end
def count
@grid.inject(0) { |sum, row| sum += row.count(:s) }
end
def empty?(*pos)
if pos.empty?
@grid.flatten.all? { |el| el.nil? }
else
x, y = pos.flatten
@grid[y][x].nil?
end
end
def display
col_idx = " |"
@grid.each_index { |i| col_idx += " #{i} |" }
col_idx += "\n" + "-" * 44 + "\n"
board_without_col_idx = ""
@grid.each_with_index do |row, i|
board_without_col_idx += " #{i} |"
row.each { |el| board_without_col_idx += " #{el || ' '} |" }
board_without_col_idx += "\n"
board_without_col_idx += "-" * 44 + "\n"
end
puts col_idx + board_without_col_idx
end
def full?
@grid.flatten.all? { |el| !el.nil? }
end
def place_random_ship
raise "Board is full" if self.full?
taken_pos = []
x = rand(0...@grid.size)
y = rand(0...@grid.size)
if !taken_pos.include?([x, y])
@grid[y][x] = :s
taken_pos << [x, y]
end
end
def won?
empty?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment