Forum: Ruby Console battleship game in Ruby

72267a9e615942649c57d2fa733bee92?d=identicon&s=25 Kirill Brown (Guest)
on 2014-08-03 09:45
Attachment: ___.jpg (1 MB)
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:
http://ideone.com/cM8g57)

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
4a65f01f7ece0b720bdb0de3c3db089e?d=identicon&s=25 Dansei Yuuki (blutorange)
on 2014-08-06 21:41
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)
72267a9e615942649c57d2fa733bee92?d=identicon&s=25 Kirill Brown (Guest)
on 2014-08-07 06:12
Tnx a lot, I will try it.
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.