14. Test Run


#1



Hello, my code is not returning any errors, but when I enter the row and column guesses, they do not appear in the proper location- it appears in the index location. For example: if I guess row 4 and column 4, the "X" appears in the bottom right, what I would assume to be row 5, column 5. If I guess row 5, column 5, an error is returned. How can I edit my code to fix 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)
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!"
else:
    print "You missed my battleship!"
    board[guess_row][guess_col] = "X"
    print_board(board)
    if 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: "You missed my battleship!"


#2

Remember to take into account zero-indexing. Since you are the only user, you know to enter 0..4. If you want an anonymous user to be able to use 1..5 then tell them...

guess_row = int(raw_input("Guess Row (1..5): ")) - 1
guess_col = int(raw_input("Guess Col (1..5): ")) -1

The rest of the code will function as normal.

This condtional should follow immediately after the opening (win) condition so the range is tested before anything else.


#3

Right, but what if this was an actual game being played? The player probably wouldn't know about that.


#4

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