Battleship

I get an error after guessing can someone tell me what causes this

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)
print ship_row
print ship_col

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 sank my battleship!"
else:
  print "You missed my battleship!"
  board[guess_row,guess_col] = "X"
  print_board(board)

If an incorrect guess is made, then the following line causes an error.

board[guess_row,guess_col] = "X"
# TypeError: list indices must be integers or slices, not tuple

As the error suggests, you can either select an element from a list (using integer index) or you can select a slice from the list e.g.

x = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]

# Integer Index
print(x[1]) 
# Output: [4, 5, 6]

# Slicing
print(x[0:2])
# Output: [[1, 2, 3], [4, 5, 6]]

print(x[0,2])
# TypeError: list indices must be integers or slices, not tuple

With the above in mind,

# You wrote:
board[guess_row,guess_col] = "X"

# Change it to:
board[guess_row][guess_col] = "X"

board is a list of lists, so the [][] notation will allow you to target the nested element.

1 Like