Test Run

#1

This code is correct, but it shows "You guessed that one already." unnecessarily. Is there anyway to fix this? Thanks.

``````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:
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."``````

#2

The design flow needs to be fixed a bit.
Like this..

1.If co-ordinate matches then Congratulate the user.
2.If The co-ordinate is already guessed it must have `"X"` then show the message to the user that it's guessed already.
3.If the Enemy is not at that co-ordinate then show message , You missed it and mark that co-ordinate by replacing `'O'` with `'X'`.
4.If it is not in the range ,show user that It's outside of ocean.

As you can see we can introduce an elif that will check if co-ordinates value is equal to `'X'` or not and show the message.

also show (print) the board at the last. (when all testing (`if/elif/else`) has done)

#3

Now I got the problem, I just don't understand it works like this in a specific order. Could you please explain why it is?

#4

As we can see that if user misses the enemy,it sets the co-ord value to `'X'` ,as just after first `if/else` statement, there is another block of `if/elif` starts, so it checks the user co-ordinates on same input and finds that it has '`'X'` so it simply prints (`You guessed that one already.`) it even you have not input-ed second time.

#5

Thanks for the help!

#6

That helped clear me up!

#7

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