Not again


#1



Hi there

I get through the excercise but my code puts the X at the wrong col/row. I typed in 3/3 and the X is at 4/4. Any idea why?

console :
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: 3
Guess Col: 3
3
4
You missed my battleship!
O O O O O
O O O O O
O O O O O
O O O X O
O O O O O
None


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


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


#2

Hey @especialara the problem is in your range() both in your for loop and the check in your if statement.
Think about it if you have only 5 circles and you type in 3 and the console brings back 4. Is your range to big or too small?


#3

thanks for your answer bandit!
but... I dont get it.. How can my range be too big or too small? I set the board range to (0, 5)- meaning 5 colons and then put 5 O on each of it- meaning I will have 5 rows.
And in my if statement I tell it to not accept anything above 5... why wouldnt that work?


#4

or are (0, 5) 6 col? :sweat:


#5

Well your code and mine are similar and so are a bunch of other answers to this question so maybe its the way the console interprets what we're trying to achieve that's a bit off.

But feel free to do some research on the subject don't just take my word for it. :slight_smile:


#7

right... totally didnt think of that. thanks!


#8

Haha great answer didn't even look at it that way!


#9

list's index starts from 0.


#10

edit your code at board[guess_row][guess_col] = "X"
to board[guess_row-1][guess_col-1] = "X"


13- Not again!