Battleship complete script by Umair


#1

from random import randint #Importing randint function from random module.
board = [] #Created board list for game board

for x in range(5): #repeating this code 5 times
board.append(["O"] * 5) #modify board list 5 times

def print_board(board): #created function to display board in
for row in board: # nice way.
print " ".join(row)

print "Let's play Battleship!" #printing msg to console
print_board(board) #calling function to print board

def random_row(board):#created function to select random row
return randint(0, len(board) - 1)#between 0 to 5

def random_col(board):#created function to select random colum
return randint(0, len(board[0]) - 1)

ship_row = random_row(board) #set value of random row
ship_col = random_col(board) #set value of random colum

for turn in range(4): #It will run this code 4 times
guess_row = int(raw_input("Guess Row:"))#asking input
guess_col = int(raw_input("Guess Col:"))#asking input

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 > 4) or (guess_col < 0 or guess_col > 4):
        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"
    print 'Turn', turn + 1
    print_board(board)
    if turn == 3:
        print "Game Over"

#2

Hi @umair_pk,

Here's a little trick:

Whenever you would like to paste code, since this forum supports Markdown Syntax you can use three backticks before and after your code block like so:

```
def my_func(x):
my_var = 0
if x > my_var:
sum = my_var + x
else:
print "Odelay!"
return sum
```

and it will retain proper indentation and even have nifty syntax highlighting:

def my_func(x):
    my_var = 0
    if x > my_var:
      sum = my_var + x
    else:
      print "Odelay!"
    return sum