18/19 how do I make my battleships longer?


#1

from random import randint

board = []

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

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(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)

turn = 0
for turn in range(15):
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))

if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sunk my battleship!"
    break
else:
    if (guess_row < 0 or guess_row > 6) or (guess_col < 0 or guess_col > 6):
        print "Oops, that's not even in the ocean."
    elif(board[guess_row][guess_col] == "X"):
        print "You guessed that one already."
    else:
        print "You missed my battleship!"
    board[guess_row][guess_col] = "X"
turn += 1
print  "Turn", turn
if turn == 15:
    print "Game Over"
print_board(board)

This is my code. I changed the board to a 7 by 7 to make it a bit more challenging. I like the size of the board, but it is almost impossible to hit the battleship. Do you have any ideas on how to make the battleship longer?


#2

A longer ship will also introduce a second parameter, direction (E/W or N/S). We would need to construct the ship with one or the other orientation.

First, we could decide ahead what the orientation will be. For that, we could use randint to generate a 0 for N/S or a 1 for E/W.

Then we would generate one random location, as in the original code. This could end up being on an edge, so we would have to test for that.

Then we would arbitrarily set the appropriate row and col for the second square. If on bottom edge, and direction is 0, use cell above, else use cell below, else if on the right edge and direction is 1 use cell to the left, else use cell to the right.

Your board should still check out the way it does now. Happy coding! Let us know how you make out.