Battleship 13/19: Problem solved, but seeking insight


#1

I was having trouble with the coding for the "You guessed that one already." else if statement.

I found a solution but as I go back to add comments, I'm not certain WHY it worked.

Problem one - thinking too much.

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

This returned the error: list indices must be integers, not str

After a number of permutations such as:

guess_row == board["X"]
board[guess_row] == ["X"]
board[guess_row] == int(board["X"])

I settled on:

     elif board[guess_row] == "X" or board[guess_col] == "X":
            print "You guessed that one already."

The guess variables were integers already:

guess_row = int(raw_input(" "))
guess_col= int(raw_input(" "))

Which suggests that "X" was the offending string and that it was now being read as an integer, but I have no idea why.

Is it that I referenced "X" in brackets ["X"] or as part of board(["X"]) that it kept returning a string?
Did removing the brackets have the loop return an integer (the index number instead of the string?)

Thank you in advance for any help offered.
M


#2

My apologies!
I thought I had formatted the code correctly!
Problem code (line 34)

Solution

I hope these pics post!

Thanks again.

M


#3

Hey @dr.kung-fucocopops

The reason for the issue the first time is, you can't convert the letter X, a string value, into an integer. It simply doesn't work. For example, if we take the word "cow" and try to make it into numbers, we'd have to make a whole letter-number translation system, like A=26, B=25, C=24, etc. This would result in 24,12,4. Python doesn't have that ability on its own without us writing a program to teach it how, so it wouldn't be able to do it.

I can see why you thought you needed an int there. However, you are going through list positions, which are not considered integer variables. That would convert a variable to an int.

Good try, but that's the explanation, if that made any sense.

(If you think this helps, please click the check box to show it answered your question.)


#4

Thanks 825orion. The explanation helps a lot.


#5

No problem. Happy to help.