Battleship 14: Test Run
Hi, so I'm trying to get my code to loop back to the beginning if an invalid input is entered.
Unfortunately, the way I've written it, it does seem to loop during input, but doesn't appear to be saving the variable for use later.
I think there are some other bugs too with how it checks for the "X" in the grid, but I can't debug that right now with the input error, so if anyone happens to catch what I'm doing wrong there, I would really appreciate it.
Here's the error:
Traceback (most recent call last): File "python", line 55, in <module> NameError: name 'guess_row' is not defined
Here's my code:
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) def guess(): invalid_row = True invalid_col = True while invalid_row == True: raw_guess_row = raw_input("Guess a row:") if raw_guess_row.isdigit(): guess_row = int(raw_guess_row) if 1<= guess_row <= 5: invalid_row = False return guess_row else: print "Invalid input. Try a value between 1 and 5." else: print "Invalid input. Try a value between 1 and 5." while invalid_col == True: raw_guess_col = raw_input("Guess a column:") if raw_guess_col.isdigit(): guess_col = int(raw_guess_col) if 1<= guess_col <=5: invalid_col = False return guess_col else: print "Invalid input. Try a value between 1 and 5." else: print "Invalid input. Try a value between 1 and 5." return guess_row return guess_col guess() 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!" elif board[guess_row][guess_col] != "O": print "You guessed that one already." print_board(board) print "Try again." guess() else: print "You missed my battleship!" board[guess_row][guess_col] = "X" print_board(board) print "Try again." guess()