Battleship passes but doesn't work right


#1


Once I hit bad AIm I can pass the exercises as long as I pick valid co-ordinates. if I pick out side the grid I get:

Traceback (most recent call last):
File "python", line 35, in
IndexError: list index out of range

It should tell me I am not even in the ocean. I can't even get to a second guess to try out the "You guess that all ready. I am pretty sure it is because I messed up the nested IF/ELSE. I am currently trying to debug at test run


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!"
elif guess_row == "X" or guess_col == "X":
    print "You guessed that one already."
else:
    print "You missed my battleship!"
    board[guess_row][guess_col] = "X"
    if guess_row not in range(5) or guess_col not in range(5):
            print "Oops, that's not even in the ocean."
    else:
        print "You missed my battleship!"
print_board(board)


#2

this line:

board[guess_row][guess_col] = "X"

should be after you check if the user shot is at the board, otherwise you might enter wrong coordinates, causing a error


#3

Thanks, it does solve my problem but i changed it anyway. i just noticed that I get two "you missed my battleship" messages. I am sure I have the nested IF wrong but I'll be damned if I can figure out what i did wrong.


#4

take a moment to think of what the order of if/elif and else conditions should be


#5

Correct me if I am wrong but it goes : if-elif-else. The directions were to nest another function in the else function.

Edit: I solved the problem. it looks like it was a combo of the placement of the Board[][] variable and an indentation error. The relevent portion of the fixed code is below. Thanls

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

#6

sounds like you solved it?


#7

I did thank you. The indent error was tough to spot. At least I am getting lots of practice debugging.