13/19. Why?


#1



This code is correct. It is also incorrect. When I input a row and a column that are in the board, I get an error message:
Traceback (most recent call last):
File "python", line 38, in
TypeError: 'function' object has no attribute 'getitem'

Whenever I type a row and a column that are outside of the board, I get it correct. Changing the "X" in:

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

to "O" also makes it correct, as every spot on the board is a "O", so it prints out: "You guessed that one already."
Does anyone understand this? Not even my teacher could. Thanks.


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!"
    #print_board[guess_row][guess_col] = "X" 
elif 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][guess_col]=="X":
    print "You guessed that one already."
else:


#2

Hi,

your code seems to be cut off before line 38, can you add the missing part?


#3

Hello, Can you please copy + paste the entire code? It seems to be missing from line 36 itself. :slight_smile:


#5
    print "You missed my battleship!"
    board[guess_row][guess_col] = "X"

My bad, here's the rest.


#6
    print "You missed my battleship!"
    board[guess_row][guess_col] = "X"

My bad, sorry.


#7

Odd, this runs without errors for me. I tried input on and off the board.


#8

First of all, there are a lot of things that you are missing the code.

  • for turn in range(4): # Every condition comes below this "for" loop
    This is the "for" loop which belongs before the guess_row and guess_col statements.

This basically lets the program know that the range is only until 4 and not beyond that. If wont let you take turns after your 4th.

Moreover, you haven't yet added any the turn function. So, the problem which you are talking about shouldn't exist. As of now, the code will only let you take one turn and nothing more than that. So, the error shouldn't read the way you described it.

Keep me updated and let me know you have any problem. :slight_smile:


#9

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