12. Battleship 'Bad Aim'


#1

Yo,

It keeps saying that the list index for board[guess_col][guess_row] is out of range. Not sure how to fix.

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: "))

# Write your code below!
if guess_row == ship_row and guess_col == ship_col:
	print "Congratulations! You sank my ship!"
else:
  board[guess_row][guess_col] = "X"
  print "You missed my ship!"
  print print_board(board)
  if guess_row not in range(5) or guess_col not in range(5):
    print "Oops, thats not even in the ocean"
    print print_board(board)






#2

you updated the board:

board[guess_row][guess_col] = "X"

marking the miss with an X before you validate the shot is actually in the ocean, so the index error can still occur

to prevent this, we should only update the board/mark the miss with an X after we verified the shot is on the board


#3

Sorry this is completely going over my head. I don’t understand where else I am meant to put it? It wouldn’t be under the next if statement because if it wasnt on the board we shouldn’t mark it an X.

I feel like the whole section of it is just wrong?

if guess_row == ship_row and guess_col == ship_col:
	print "Congratulations! You sank my ship!"
else:
  board[guess_row][guess_col] = "X"
  print "You missed my ship!"
  print print_board(board)
  if guess_row not in range(5) or guess_col not in range(5):
    print "Oops, thats not even in the ocean"
    print print_board(board)


#4

from the instructions:

After your new if statement, add an else that contains your existing handler for an incorrect guess. Don’t forget to indent the code!

this is the existing handler:

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

this needs to be placed in an else clause you need to add


#5

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