Need Explanation 14/19 (Test Run)


#1



Exercise 14/19 (Test Run)


There's no error messages. (Can anyone check if there is any flaws in my code?, thanks. :slight_smile:)


When l input 1 for Guess Row and 4 for Guess Col 'which way does guess row align and which way does guess col align?' That is my question.

Here is the code output:

O O O O O - (is this the row or column)
O O O O O
O O O O O
O O O O O
O O O O O
Guess Row: 1
Guess Col: 4
4
3
You missed my battleship!
O O O O O
O O O O X
O O O O O
O O O O O
O O O O O
None

This is the code input below:

from random import randint

board = []

for x in range(0, 5):
    board.append(["O"] * 5)

def print_board(board):
    for row in board:
        print " ".join(row)

print_board(board)

def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))

print ship_row
print ship_col

# Write your code below!
if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sank my battleship!"
else:
    if guess_row not in range(5) and guess_col not in range(5):
       print "Oops, that's not even in the ocean."
    elif board[guess_row] [guess_col] == "X":
        print "You guessed that one already."
    else:
       print "You missed my battleship!"
       board[guess_row] [guess_col] = "X"
       print_board(board)


#2

The marked part is the row. You have to remember that we start indexing lists from 0.

So the row 1 is the second row. And column 4 is the fifth column.


You can subtract 1 from the inputed values to make the game more natural for the non-programmers :slight_smile:

guess_row = int(raw_input("Guess Row:")) - 1
guess_col = int(raw_input("Guess Col:")) - 1

And now the output is:

O O O O O
O O O O O
O O O O O
O O O O O
O O O O O
Guess Row: 1
Guess Col: 4
3
4
You missed my battleship!
O O O X O
O O O O O
O O O O O
O O O O O
O O O O O

#3

Thank you very much. :slight_smile:(I was confused how columns and rows were arranged)


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.