Hello everyone. I don't think that this problem has been seen before.
When submitted for approval, I am given the green go-ahead to the next lesson. But I know that my code has something wrong with the logic.
- If I enter in the coordinates (2,4) I see:
- The board with an X marking my selection -- but it is not always correlated to what I typed in!
- "You guessed that one already" -- Not sure why it sometimes gives me that on my first try.
- Another board with the X marking a selection--not always my selection.
*If I enter in coordinates such as (5, 5) I get an error like "Index out of range". With no green go ahead button.
*If I enter in (2,5) I get the error "Not in the ocean".
*If I enter (5, 5), I get the "You missed my battleship" text along with the correct coordinates, but with no X mark, and with the red error text ("Traceback (most recent call last):
File "python", line 38, in
IndexError: list index out of range").
So I know that my problem is related to my ranges. It seems like the board does not actually have 5s as an option for the rows or columns. And that is probably also why my X marks are not accurate. When I enter in other coordinates that do not have 5s, I seem to get the correct responses "You missed my Battleship", but only occasionally do I get a reading of my X mark.
I hope that this wasn't too confusing. I can attempt to clear it up if there are any more questions.
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) - 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! # Check to see if guesses coords are = to actual ship coords! # Add if guess_row = ship_row and guess_col = ship_col # Add an else statement to handle if player guesses wrong if guess_row == ship_row and guess_col == ship_col: print "Congratulations! You sank my battleship!" else: print "You missed my battleship!" # Mark ship location with "X" board[guess_row][guess_col] = "X" print print_board(board) # Add new if: statement that is under else. \ <-- continues statement # Check if guess_row isn't in range(5) or guess_col isnt' in range(5) if guess_row not in range(5) or \ guess_col not in range(5): print "Oops, that's not even in the ocean." # Add elif statement elif(board[guess_row][guess_col] == "X"): print "You guessed that one already." # Add else that reuses handler for incorrect guess else: print "You missed my battleship!" board[guess_row][guess_col] = "X" print print_board(board)