Troubleshooting


#1

Hey there! Im trying to debug my battleship code:

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

When i guess regular values within range it works, but when i guess in a range of > 5 it replies:

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

Also when i try to guess no values it replies:

Traceback (most recent call last):
  File "python", line 22, in <module>
ValueError: invalid literal for int() with base 10: ''

I cant seem to find my mistake with these two elements. Any help would be appreciated


#2

"IndexError: list index out of range" Do you know what this error message means? If so do a quick hand trace of what happens when you you run the program with too large user inputs. The issue becomes pretty clear then..

I think you can ignore the second case if you want. The user leaving the input blank kind of is an user error anyways.


#3

Hey, thanks for the quick reply!
To answer your question: Yeah i know the "range" error. I have tried playing around with a few different values for the range, but when i enter "6" into the command i still get the error...


#4

It seems to be the:

board[guess_row][guess_col] = "X"

that there is something wrong with


#5

Take a moment to think about what you really have going on,

Do the following.

board = ['O' * 5 for i in range(5)]
board[5][5] # This should produce an error.
for i in range(5):
    for j in range(5):
        print("X: %s, Y: %s" % (i, j))

Now that you have an understanding of what you are doing, let's move on to what needs to be done when you take human input into consideration.

board = ['O' * 5 for i in range(5)]
guess_row = int(raw_input("Enter a number 1-5:\n")) - 1
guess_col = int(raw_input("Enter a number 1-5:\n")) - 1
print(board[guess_row][guess_col])

As you can see quickly we have to adjust by an offset of negative one in order to match the what the computer wants and what the user is imputing.

Once you do that everything should work correctly.