Console battleship game in Ruby

Hello everyone!

I’m new to programming in Ruby and I have the task to write a console
battleship game (sea battle game). I addressed my question on various
forums in Russia, but unfortunately no one did not help me. I found many
examples on github, but could not understand them.

I wrote the code (see the attachment) which displays a board and in hash
I can set the location of ships. (code and result is also here:
cM8g57 - Online Ruby Interpreter & Debugging Tool - Ideone.com)

But how to set the coordinates for each type of ship (4 spaces (1 ship
of this type), 3 spaces (2 ships), 2 spaces (3 ships), 1 space (4
ships)) entering the coordinates (A1, A2, A3, A4 for 4 space ship, for
example)?

That is, the terminal asks:

“Where to place ship 4 cells? Enter the first coordinate.” - A1
"Enter the second coordinate - A2,
etc.

And on the board instead of “.” appears, for example “S”.

Many thanks for watching!

P.S. Excuse me for my English

Here’s a code snippet to get you started.

4.times do |i|
puts “Enter coordinate ##{i+1}.”
coord = gets.chomp.strip.downcase
row = coord[0]
col = coord[1].to_i
if board[row] && (1…10).include?(col)
board[row][col-1] = true
else
puts “Invalid coordinate.”
redo
end
end

Integrated with your code.

def display(board, indent=1)
len = board.length.to_s.length
head = Array.new(board.length){|i|(i+1).to_s.rjust(len,‘0’)}.join(’
')
$stdout << ’ ‘(indent+1) << head << “\n”
(indent/2).times {$stdout << “\n”}
board.each do |key, row|
$stdout << key << ’ '
(indent)
$stdout << row.map{|x| x ? ‘S’ : ‘.’}.join(’ '*len) << “\n”
end
end

def add_ship(board, n=4)
puts “Adding ship of size #{n}.”
n.times do |i|
puts “Enter coordinate ##{i+1}.”
coord = gets.chomp.strip.downcase
row = coord[0]
col = coord[1…-1].to_i
if board[row] && (1…board.length).include?(col)
board[row][col-1] = true
else
puts “Invalid coordinate.”
redo
end
end
end

def new_board(size=10)
board = {}
(‘a’…(96+size).chr).each {|row| board[row] = [false]*size}
return board
end

board = new_board(20)
display(board)

add_ship(board, 4)
display(board)

add_ship(board, 2)
display(board)

Tnx a lot, I will try it.