Skip to content

Instantly share code, notes, and snippets.

@SunnyIzr
Created September 1, 2013 06:28
Show Gist options
  • Save SunnyIzr/6402691 to your computer and use it in GitHub Desktop.
Save SunnyIzr/6402691 to your computer and use it in GitHub Desktop.
class Battleship
attr_reader :board
def initialize
@ships = [%w[AC AC AC AC AC], %w[BS BS BS BS], %w[CR CR CR], %w[DS DS], %w[SB SB]]
@board = Array.new(10) {Array.new(10,'/')}
@mvmt = [ [-1, 0], #top
[0, 1], #right
[1, 0], #bttm
[0, -1]] #left
end
def create_board
@board.clone
end
def check_all_adj_empty?(coord)
row=coord[0]
col=coord[1]
@mvmt.each do |mvmt_coord|
if (row+mvmt_coord[0])> -1 && (col+mvmt_coord[1]) > -1 && (row+mvmt_coord[0]) < 10 && (col+mvmt_coord[1]) < 4
test_coord_value = @computer_ship_board[row+mvmt_coord[0]][col+mvmt_coord[1]]
if test_coord_value == '/'
return true
else
false
end
end
end
false
end
def check_dir_adj_empty?(orig_coord,next_coord)
end
def random_empty_space
p "finding random space..."
row = rand(10)
col = rand(10)
p "Checking to see if coord (#{row},#{col} is empty and adj is empty"
if @computer_ship_board[row][col] == '/' && check_all_adj_empty?([row,col])
p "random_space found coords are #{row},#{col}"
return [row,col]
else
random_empty_space
end
end
def populate_computer_board
@computer_ship_board = create_board
@ships.each_with_index do |ship, ship_num|
unless var == true
start_pt = random_empty_space
ship.length.times {|x|
@computer_ship_board[start_pt[0]+x,start_pt[1]] == '/'
}
end
p "STARTNG PT is #{start_pt}"
ship.each_with_index do |ship_pt,index|
if index == 0
p "printing #{ship_pt}[#{index}] to #{start_pt}"
@computer_ship_board[start_pt[0]][start_pt[1]] = ship_pt
else
p "printing #{ship_pt}[#{index}] to #{start_pt[0]+index},#{start_pt[1]}"
@computer_ship_board[start_pt[0]+index][start_pt[1]] = ship_pt
end #closes if
end #closes e_w_i ship_pt
end # closes e_w_i ship
@computer_ship_board
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment