Last active
June 23, 2018 04:17
-
-
Save bastosmichael/983628ad7ff3c590f53c7cb649714533 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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