I'm making a Battleship game using python 2.7. However, how to make it is not currently my issue. The main aspect that I'm asking about is the style and method of making the code. Am I following best (or even good) practice? Are the comments too much, too little, unclear? If someone could give me some pointers based on my code on how to make it more readable and standard, it would be highly appreciated.
from random import randint
# Adds the board to use as a list later
board = []
# Numbering my rows and columns
row_num = ["0", "1", "2", "3", "4"]
# "0" string begins a space as the row numbering pushed in the output text. Could the space be better implemented in print board?
columns = [" 0", "1", "2", "3", "4"]
for x in range(5):
board.append(["-"] * 5)
# Function for making the board. Added tabs to make it more in the middle and clearer.
def print_board(board):
row_num = 0
print "\t\t", " ".join(columns)
for row in board:
print "\t\t", row_num, " ".join(row)
row_num += 1
print "Let's play Battleship!"
print_board(board)
# Functions for playing agasint the computer
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
print "Would you like to play agasint the computer or against a friend?"
# Choosing the location of the battleship and data validation of raw_input
def game_type(game_input):
global ship_row
global ship_col
if game_input == 1:
ship_row = random_row(board)
ship_col = random_col(board)
elif game_input == 2:
ship_row = int(raw_input("Choose a Row to place your battleship:"))
ship_col = int(raw_input("Choose a Column to place your battleship:"))
else:
print "That is not a valid input. Please try again"
game_type(int(raw_input("To play against the computer press 1, to play against a friend press 2: \n")))
game_type(int(raw_input("To play against the computer press 1, to play against a friend press 2: \n")))
# Printing the sollution for easy testing
print ship_row
print ship_col
# Starts the actual game
for turn in range(4):
turn
print "Turn", turn + 1
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Column:"))
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
board[guess_row][guess_col] = "X"
print_board(board)
break
# Data Validation for the inputs. Maybe this shouldn't make a player miss but rather allow to retry
else:
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] == "O"):
print "You guessed that one already."
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "O"
if turn == 10:
print "Game Over"
break
print_board(board)