18) To Your Battle Stations


#1




When I enter a coordinate that is outside the ocean (eg. row 2, col 7), the following error message appears and consequently the loop breaks:
"Traceback (most recent call last):
File "python", line 45, in
IndexError: list assignment index out of range"


I am not sure why this is happening. I expected it to simply say "Oops, that's not even in the ocean." and continue the loop.


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)

print "Let's play Battleship!"
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)
print ship_row
print ship_col

# Everything from here on should go in your for loop!
# Be sure to indent four spaces!
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!"
        if turn == 3:
                print "Game Over"
                break
    board[guess_row][guess_col] = "X"
    print "Turn", turn + 1
    # Print (turn + 1) here!
    print_board(board)


#2

If you find yourself doing something you should have guarded yourself against then check what order you did things


#3

Thanks for the feedback. I have in fact checked the order and unable to figure out myself why I am getting the error message. I posted this in the hopes that someone could explain exactly why and what is causing the error message. If it is the order, can you please help me better arrange the code so this issue does not come up?

Thanks


#4

@jaypsavla ,

When you run a program and it does not work correctly, use all the clues you find to locate the problem. In the console, you must have gotten ...

Guess Row: 2
Guess Col: 7
Oops, that's not even in the ocean.
Traceback (most recent call last):
  File "python", line 45, in <module>
IndexError: list assignment index out of range

This suggests that you should consider some questions.

  • What is on line 45?
  • Why, after you have entered coordinates that are outside the ocean, does a list index go outside of range?
  • Do you really want that statement to be at a location where it gets executed when the guessed coordinates are outside the ocean?
  • When should the statement execute, and when should it not?
  • What can you do about this; could the the statement be moved so that it only executes when intended?

There may be additional questions to ask. In fact, I am asking myself a question, namely ...

  • Why did Codecademy pass this submission despite its having raised an IndexError while it was executing?

(Edited on December 6, 2016 to ask additional questions in the list, above.)


#5

I have tried re arranging the statement on line 45 that seems to be causing the problem in every way I thought would make the needed differences. I tried using an if statement on it and then re arranging. I even tried using an if statement inside an existing if statement, but that also did not work.

I cannot seem to figure out what is causing this issue.


#6

You should only use the indexes to access the board if they're valid coordinates.

You'd write that as:

if coords are safe to use:
    do stuff with coords here
    anywhere outside this won't have considered whether they are safe to use
    so anything outside this code block should not use the coords to access the board

So identify where in your code you're testing the coords and where it's safe to use them. Then move everything using the coords to access the board into that.

The bug you have can be identified without reading the code at all by just observing how your code behaves (see my previous reply), read the code and consider what code corresponds to that behaviour. You also have a line number pointing out where crash itself happens, so without reading the code you can identify what line isn't in the part of your code that only runs if the coords are deemed valid

Writing code is very intentional, you're telling the computer what to do, what you tell it has to add up. You have to understand every bit of what you write. Spend more time with the code, in no particular order, here are things you can do:
- read it
- execute it manually (you're the machine carrying out what the code says)
- write it down in English instead and execute/debug that
- rewrite it, making sure that you can motivate why each thing you write needs to be there
- remove parts that aren't related to the current problem so that there's less code to deal with and experiment with that until you get it working and can argue for why it behaves the way it does and then add the rest back again


#7

This helped a lot. I tried implementing it as an "if" statement but I made a careless error by using "or" when I should have been using "and" and this is what made me believe that the "if" statement was not a valid solution.


#8

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