Category Archives: Python

Python Programs and Projects.

Battleship.py

Like classic Battleship? Well then this simplified version might, possibly, maybe  grab your attention!
On a serious note though,  I’ve done a simple version of Battleship in Python, the code is easy to follow and the idea’s in the code can be used for other things such as a word search!
Below is the source code and I will talk you through the important snippets of code!

# Possibly change this to be more user friendly e.g. 1-5
from random import randint

board = []

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

def print_board(board):
    for row in board:
        print " ".join(row)
        """ .join() combimes the items in the list taking each individual item at a time,
        in this case printing it with a space after it."""

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)

for turn in range(4):
    print "Let's play Battleship!"
    print "Rows & Colummns are numbered 0-4"

    if(turn+1 == 4):
        print "Last Turn!"
    else:
        print "Turn: %s" %(turn +1)

    print_board(board)

    # print ship_row
    # print ship_col
    """Above prints the position of the ship on the screen for debugging purposes"""

    # Everything from here on should go in your for loop!
    # Be sure to indent four spaces!
    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 > 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"
        if(turn+1 == 3):
            print"Ok, here's a clue, my battleship is at row %s" %(ship_row)

        print_board(board)
        print ""
    if(turn == 3):
        print "Game Over"
        print "My battleship was at row %s & column %s" %(ship_row, ship_col)

  • We import randint from the random module so we can use the function randint.
    from random import randint
    
  • We then create an empty list called board. First we fill it with [“O”,”O”,”O”,”O”,”O”] five times with our for loop. Then we join the individual parts of the list to form a grid full of “O”s.
    for x in range(5):
        board.append(["O"] * 5)
    
    def print_board(board):
        for row in board:
            print " ".join(row)
    
  • In the method “print_board”, the join() function combines the individual parts of each list in the “master_list” (i.e. board) together to form a grid. (See fig.1). If the programmer was to use a “-” before the join instead of ” ” it would result in a grid displayed in fig.2.
  • fig.1
    fig.1
    fig.2
    fig.2
  • After the creation of the grid the rest of the program is if and else statements in a for loop. The for loop allows the “player”/ “end user” to guess 4 times on the location of the battleship, taking input from the user each time.
    for turn in range(4):
        #more code here
        #Below we take input from end user
        guess_row = int(raw_input("Guess Row:"))
        guess_col = int(raw_input("Guess Col:"))
    

    Below are images of game play:

    Regular game play.
    Regular game play.

     

    Already guessed error.
    Already guessed error.

     

    Out of bounds error and failed ending.
    Out of bounds error and failed ending.

     

    Winner
    Winner

Learning Python – Factorial.py

Recently I have begun learning Python at Codecademy.
I plan on uploading some more complicated code in the coming weeks, but for now here’s a quick piece of code I did today. It a method that calculates factorial

def factorial(x):
    fact =1
    if(x == 1):
        return 1
    else:
        for i in range(x):
            fact = fact * (i+1)
        return fact
		
f = int(raw_input("Enter a positive number: "))
z = factorial(f)
print z
  • “def” defines a method with the name of the method following it and the parameters. if any, inside the parenthesis.
  • Python automatically assigns variables with types.
  • “raw_input” allows the programmer to take input from the user.
  • Indentation is very important in Python as it is how the compiler can tell where code starts and ends (such as a method, for loop, if statement), these are followed by colons “:”.