To Your Battle Stations! not in ocean problem

#1

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

the game should keep on playing

``````for turn in range(4):
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))

if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
break
else:
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
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"
if turn == 3:
print "Game Over"

# Print (turn + 1) here!
print turn + 1
print_board(board)``````

#2

Take a look at this part of your code:

``````if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
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"``````

Let us assume that `guess_row = 6` and `guess_col = 11`. That's not even in the ocean right?

And after the whole `if ... elif ... else` construction your script will try to affect the `board[guess_row][guess_col]` value. `board[6][11]` doesn't exists, right?

To fix this problem you have to mark position as `X` only if it is in the ocean:

``````if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
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"``````

#3

Thanks so much for all your help!
I think the problem was just indenting the board[guess_row][guess_col], it works now

#4

Awesome! You're very welcome

I am happy that it was the only problem, but please remember to post the whole code in the future. It just really helps others to help you

#5

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