Battleship!


#1



https://www.codecademy.com/en/courses/python-beginner-en-4XuFm/2/4?curriculum_id=4f89dab3d788890003000096


I get an "IndexError: list index out of range." on my elif board[guess_row][guess_col] == "X"


I expected that the program would print "X" at the guessed spot where the battle ship was not


from random import randint

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

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

#line = ["-","-","-","-","-"]

#print "".join(line)
print "Lets Play Battleship!!"
#print "".join(line)

print_board(board)

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

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

ship_row = random_row(board)
ship_col = random_col(board)

print ship_row
print ship_col

for turn in range(4):

    guess_row = int(raw_input("Guess Row: "))
    guess_col = int(raw_input("Guess Column: "))

    if guess_row == ship_row and guess_col == ship_col:
        print "CONGRATS! 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 have guessed that already."

        else:
            print "You missed my battleship!"
            board[guess_row][guess_col] = 'X'

        print turn + 1

        print_board(board)

        if turn == 3:
            print "Game Over!"


#2

Indices are from 0 to 4. Any value larger than 4 will raise this error.


#3

when I pick my row and columns, they are, they get checked before it even goes into that else if statement.. thats why I can not figure out what is going on.


#4

Yes, I''m scratching my head, too. You test the range beforehand, so it doesn't make sense that the error is coming up.


#5

So frustrating... there has to be something, I had it running before


#6

It works as expected in the lab. Copy your code and refresh the lesson page. Then paste it back in and submit again.

Spoke too soon. Just ran into the same error with input of 2 and 4. Something isn't right.

I should have seen it sooner. The list is not two dimensional.

Should be,

board.append(['O'] * 5)

#7

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