Extra Credit: double-deck ship!


#1



Hey guys! I have modified the battleship game so that it generates a ship with two decks! I am quite happy with the result. But I think that this code could be made more compact and clean than this mess. Can any good coders give me tips?


from random import randint
from random import choice
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(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)
#These are two inputs for two functions that generate a second row or column
row_two = [ship_row - 1, ship_row + 1]
col_two = [ship_col - 1, ship_col +1]
#This function picks a row that is adjacent to the first one:
def second_row(row_two):
    return choice(row_two)
#This function picks a column that is adjacent to the first one:
def second_col(col_two):
    return choice(col_two)

sec_row = ship_row
sec_col = ship_col
vertical_pos = [second_row(row_two), sec_col]
horizontal_pos = [sec_row, second_col(col_two)]
lst = [vertical_pos, horizontal_pos]
#Now this function picks whether the ship's position is vertical or horizontal:
def ship_pos(lst):
    return choice(lst)

print ship_row
print ship_col
print ship_pos(lst)
# Ending variable and ship location generation! Moving onto the action!
#P.s. I have excluded the for loop to make debugging easier.
# For loop:

The console gives out a good result: The decks are ajacent to each other!

Let's play Battleship!
O O O O O
O O O O O
O O O O O
O O O O O
O O O O O
3
3
[2, 3]
None


#2

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.