Confusing Indexing for Battleship


#1



https://www.codecademy.com/courses/python-beginner-en-4XuFm/1/2?curriculum_id=4f89dab3d788890003000096#

So using [guess_row - 1] as an index is necessary to return the correct board for already guessed spaces. However the error message says I need to use [guess_row] as an index.

There are a few topics on this already but none are very clear about what is going on. The console says I have it right when I use [guess_row][guess_col] as the indices, but the board it returns is completely incorrect. Am I doing something wrong here?


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


#2

The issue is there. If the users guess of row and column is same as computer's, it prints "Congratulations! You sank my battleship!". However, if not so, you are meant to tell the computer to show where the user should have guessed right on the board to have won the game. But what you did was to tell the computer that the guessed row and column position which was not guessed right should go back in one position. So, really you should be doing this:

board[guess_row][guess_col] = "X"


#3

Setting guess_row = guess_row -1 and guess_col = guess_col -1 immediately after taking those inputs will probably work. I haven't tried it, but will after posting this comment. I was just wondering if anyone has asked about the index issue in the Battleship problem.