My version of battleship. Need some help


#1

Here is my version of battleship. But there always error occurs and everything is crushed when I try out of range position. As I see my code, it should print "Oops, that's not even in the ocean." and start new guess turn. Need help.

UPD: it says that it couldn't check while condition, that's ok, but how can I fix it? I want to check if user already chose the cell and in that case give user another try without increment of turns. But all possible guesses should be considered (e.g. the same cell [should ask guess again then], the right cell, out of range cell).

from random import randint

board = []

for x in range(5):
    board.append(["O"] * 5)

def print_board(board):
    for row in board:
        print " ".join(row)

print "Let's play Battleship!"
print_board(board)

def random_row(board):
    return randint(1, len(board))

def random_col(board):
    return randint(1, len(board))

ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col

for turn in range(4):
    print "Turn", turn+1
    guess_row = int(raw_input("Guess Row:"))
    guess_col = int(raw_input("Guess Col:"))

    if guess_row == ship_row and guess_col == ship_col:
        board[guess_row-1][guess_col-1]="Y"
        print_board(board)
        print "Congratulations! You sunk my battleship!"
        break
    else:
        while (board[guess_row-1][guess_col-1] == "X"):
            print "You guessed that one already."
            print "Turn", turn+1
            guess_row = int(raw_input("Guess Row:"))
            guess_col = int(raw_input("Guess Col:"))
        if guess_row == ship_row and guess_col == ship_col:
            board[guess_row-1][guess_col-1]="Y"
            print_board(board)
            print "Congratulations! You sunk my battleship!"
            break
        elif (guess_row in range(1,6)) and (guess_col in range(1,6)):
            print "You missed my battleship!"
            board[guess_row-1][guess_col-1] = "X"
        else:
            print "Oops, that's not even in the ocean."
    print_board(board)
    if turn>=3:
        print "Game Over"

#2

Move this out to a function of its own to avoid cluttering the game loop, and then just do the steps you already described:

function get_input(board)
    while true
        ask for input

        if invalid coordinates
            print valid options are 0..x inclusive
            continue

        if already guessd
            already fired there, try a new coordinate
            continue

        return user coords