Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1of 4

class Player

def get_move
puts "enter a position with coordinates separated with a space like `4 7` "
position = gets.chomp
position_array = []
position_array << position[0].to_i
position_array << position[2].to_i
position_array
end
end

class Board
attr_reader :size

def initialize(n)
@grid = Array.new(n) { Array.new(n, :N) }
@size = n * n
end

def [](array)
@grid[array[0]][array[1]]
end

def []=(position, value)


@grid[position[0]][position[1]] = value
end

def num_ships
@grid.flatten.count { |ele| ele == :S}
end

def attack(position)
if self[position] == :S
self[position] = :H
puts 'you sunk my battleship!'
return true
else
self[position] = :X
return false
end
end

def place_random_ships
total_ships = 0.25 * @size
while self.num_ships < total_ships
rand_row = rand(0...@grid.length)
rand_col = rand(0...@grid.length)
position = [rand_row, rand_col]
self[position] = :S
end
end

def hidden_ships_grid
@grid.map do |row|
row.map do |ele|
if ele == :S
:N
else
ele
end
end
end
end

def self.print_grid(grid)
grid.each do |row|
puts row.join(" ")
end
end

def cheat
Board.print_grid(@grid)
end

def print
Board.print_grid(self.hidden_ships_grid)
end
end

class Battleship
attr_reader :board, :player
def initialize(n)
@player = Player.new
@board = Board.new(n)
@remaining_misses = n * n / 2
end

def start_game
@board.place_random_ships
puts @board.num_ships
@board.print
end

def lose?
if @remaining_misses <= 0
puts 'you lose'
return true
else
return false
end
end

def win?
if @board.num_ships == 0
print 'you win'
return true
else
return false
end
end

def game_over?
return win? || lose?
end

def turn
new_position = @player.get_move
if @board.attack(new_position) == false
@remaining_misses -= 1
end
@board.print
puts "Remaining misses: #{@remaining_misses}"
end
end

You might also like