Skip to content

Instantly share code, notes, and snippets.

@bastosmichael
Last active June 23, 2018 04:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bastosmichael/983628ad7ff3c590f53c7cb649714533 to your computer and use it in GitHub Desktop.
Save bastosmichael/983628ad7ff3c590f53c7cb649714533 to your computer and use it in GitHub Desktop.
module BattleShip
class Board
SHIPS = {C: 5, B: 4, S: 3, D: 3, T: 2}
def initialize
@grid = (1...10).map {(1...10).map {'.' }}
end
def randomly_load_ships
SHIPS.each do |ship,cells|
loaded = false
while loaded == false
x = rand(10 - cells)
y = rand(10 - cells)
orientation = ['horizontal','vertical'].sample
empty_cells = true
(0...cells).each do |number|
if orientation == 'vertical'
empty_cells = false unless @grid[x+number][y] == "."
else
empty_cells = false unless @grid[x][y+number] == "."
end
end
if empty_cells == true
(0...cells).each do |number|
if orientation == 'vertical'
@grid[x+number][y] = ship
else
@grid[x][y+number] = ship
end
end
loaded = true
end
end
end
self
end
def print_board
@grid.each do |x|
puts x.join(' ')
end
end
end
end
BattleShip::Board.new.randomly_load_ships.print_board
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment