12. Bad Aim


The problem with Code Academy is they sometimes give awful and ambiguous directions. In this particular lesson they tell you to nest a new if statement under the existing else, which is WTF. Really they should have told you to do an elif in between.

If you're stuck, read the code I have below and try it out. I recommend for anyone doing code academy to have a text editor and run your code in Terminal/Command Prompt. The code I have below will pass. For some reason the "preformatted text" option that you have to use to put your code in sucks, it only formats the first line you paste and the rest you have to spacebar into place, so don't weigh heavily on the white space I have below. Copy and past it outside and use proper spacing.

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)


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

# Write your code below!
if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sank my battleship!"
elif guess_row not in range(1,5) and guess_col is not range(1,5):
	print "Oops, that's not even in the ocean."
	print "You missed my battleship!"
	board[guess_row][guess_col] = "X"


This was very helpful, however, this code, as written, doesn't allow a player to select the 5th row or column. When I guess, say, 1 and 5, I am told that 5 is not "in the ocean." Is this game just set up to allow a buffer between the ship and the abyss, or is there another way to allow users to select every point in the grid?

Nevermind! I forgot about counting from 0. Sigh.


Additionally, I didn't like using a fixed range to define the out of bounds testing in this lesson. That issue can be improved upon by using the length of 'board' instead of the hard-coded range:

elif guess_row not in range(0,len(board)) or \
    guess_col not in range(0,len(board[0])):
        print "Oops, that's not even in the ocean."

This has the benefit of not needing to be recoded every time the board changes size. Since the columns should be uniform I'm grabbing the length of one nested list to calculate the valid column sizes.

This isn't needed for this lesson, but it's a fun addition if you want to extend the project. You could have the user pick the board length and width at the start and this code would still work.