Bad aim


#1

Can anyone tell me why cant I use this code

if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sank my battleship!"
    board[guess_row][guess_col] = "X"
    print_board(board)
else:
    if guess_row in range(5) and guess_col in range(5):
         print "You missed my battleship!"
        board[guess_row][guess_col] = "X"
        print_board(board)
    else:
     print ("Oops, that's not even in the ocean.")

forget about the indents these are typing errors the error it shows if I input 2,9 is index list out of range


#2

this line:

board[guess_row][guess_col] = "X"

you try to access your list, so if the coordinates are too high (outside your list), you get an error. To check if the coordinates or on the board should come before you try to access your board.


#3

I am checking them in the condition
if guess_row in range(5) and guess_col in range(5):


#4

yes, but too late. this line:

board[guess_row][guess_col] = "X"

is still before you check if the coordinates are valid:

if guess_row in range(5) and guess_col in range(5):

so the user can still access the board with invalid coordinates (a program runs from top to bottom, so order is important)


#5

but in the below code only if the if condition is satisfied will the board[guess_row][guess_col] = "X" come right so so the user cannot access the board with invalid coordinates

 if guess_row in range(5) and guess_col in range(5):
         print "You missed my battleship!"
        board[guess_row][guess_col] = "X"
        print_board(board)

Am I making a mistake here?


#6

yes, you are right this time. But for the exercise you will need the following structure:

if ship_is_hit:
   print you sank my battle ship
else:
   if not in the ocean:
      print that is not even  in the ocean 
   else:
     print you missed my battle ship
     update board with the spot they missed
     print the board

the above is just the design, not the actual code.


#7

so we can write the code the way I written it but the structure is different and that's why its not working
right?


#8

yes, your code is correct, it just needs to be structured slightly different. I hope my textcode (or pseudo code as it is called) is understandable, if not post an updated version of your code.


#10

2 posts were split to a new topic: Bad aim


#14

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