Need some help with my code at the 14/19 stage


#1

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_col == ship_col and guess_row == ship_row:
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."
    board[guess_row][guess_col] = "X"
    print_board(board)

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


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

Whenever i run the code it always prints the following after the first guess

O O O O O
O O O O O
O O O O O
O O O O O
O O O O O
Guess Row: 3
Guess Col: 4
0
2
You guessed that one already.
O O O O O
O O O O O
O O O O O
O O O O X
O O O O O
None

The problem is, I haven't guessed before this, anyone know why it is saying i have guessed that one?


#2

Hi,

when the player enters a guess that's not in the ocean you can't set the guessed field to "X" because it's not on the board.

In the elif branch you are checking if guess_row or guess_col == "X". There's two problems with that, first you would have to use guess_row == "X" or guess_col == "X" and second that guess_row and guess_col are numbers and not strings so this is always False. You should use
board[guess_row][guess_col] == "X".


#3

I put the first bit in and that works perfectly thank you! However when i changed the "Guessed already" section to what you suggested it came up with the following error

elif board[guess_row][guess_col] == "X"
                                      ^

@eveat


#4

Nevermind, i see my stupid mistake, just a lack of colon, thanks for your help! @eveat