11 Danger Will Robinson Not showing correct ship location


#1



***Edit: Sorry, I just now realized it's Xing the places that I guess and not the location of the hidden battleship...**

When I execute my code, it works through and gives me a pass. However, the X is not where it says the ship should be. For example:

O O O O O
O O O O O
O O O O O
O O O O O
O O O O O
Guess Row: 2
Guess Col: 4
4
0
You missed my battleship!
O O O O O
O O O O O
O O O O X
O O O O O
O O O O O
None

What am I missing? What do I need to fix? Thanks so much for any help!


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)


#2

This is a result of indexes starting from 0, so the row we think of as the first row, or row 1, is actually row 0. We can fix this problem by subtracting 1 from the guess, so if they guess 1 we would store it as 0. It would look something like this:

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

One note, if you implement that solution, you will have to rework other parts of the program as you proceed with the course.


#3

Thanks for the response!
I think I was confused as to whether the program was supposed to be Xing the guesses or the hidden battleship. It is asking us to X the guesses, correct?


#4

Correct, that way we can see what spots we have guessed.


#5

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