Programming, Python

Day 3: Learning Python

Day 3 of my lessons, and I’m learning more about classes and inheritance. My Memory game has come quite a long way, here it is:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

''' Player Class '''
class Player:

    ''' Initialize Player '''
    def __init__(self):

        self.moves   = 0
        self.flipped = []


    ''' Turn over tile '''
    def flipTile(self, tile):

        tile.flip()
        self.moves += 1
        self.flipped.append(tile)

    ''' Check if one round is complete '''
    def roundComplete(self):

        return len(self.flipped) == 2

    ''' Retrieve flipped tiles '''
    def getPair(self):

        return (self.flipped.pop(), self.flipped.pop())

    ''' Cover unmatched pairs '''
    def coverPair(self, tile_pair):
        for tile in tile_pair:
            tile.flip()

''' Board Class '''
class Board(list):

    ''' Initialize Board '''
    def __init__(self, tiles):

        super().__init__(tiles)

    ''' Modify string output '''
    def __str__(self):
        return " ".join(str(t) for t in self) + 
                "n0 1 2 3 4 5 6 7 8 9"

    ''' Check if board is complete '''
    def isComplete(self):
        for tile in self:
            if tile.isCovered():
                ''' If even one Tile is uncovered, then  game is still going '''
                return False

        ''' if we got this far, board is complete '''
        return True


''' Tile Class '''
class Tile:

    ''' Initialize the Tiles '''
    def __init__(self, char):

        ''' uncovered value of character '''
        self.char = char

        ''' set default output as the covered state '''
        self.image = '_'

    ''' Change string evaluation '''
    def __str__(self):
        ''' return the image state '''
        return self.image

    ''' Evaluate equality '''
    def __eq__(self, other):
        return self.image == other.image

    ''' Evaluate inequality '''
    def __ne__(self, other):
        return not self.__eq__(other)

    ''' Flip tile '''
    def flip(self):
        if self.image == '_':
            self.image = self.char
        else:
            self.image = '_'

    ''' Check tile state '''
    def isCovered(self):
        return self.image == '_'

''' Only run the rest if called directly '''
if __name__ == "__main__":

    ''' Initialize Player '''
    player = Player()

    ''' Set up the board '''
    board = Board([Tile(t) for t in ['A', 'B', 'C', 'D', 'E'] * 2])

    ''' Randomize the tiles '''
    import random
    random.shuffle(board)

    ''' Evaluate input '''
    def validInput(user_input):

        ''' Check if input is a number '''
        if user_input.isdigit():

            ''' Convert user_input to a integer '''
            idx = int(user_input)

            ''' check if idx is in range '''
            if idx < len(board):

                ''' check if tile is flipped '''
                if not board[idx].isCovered():
                    print("Tile already flipped!")
                    return False

                ''' All tests passed '''
                return True

            else:
                print("User input out of range")
                return False

        else:
            ''' Input not a number, ignore '''
            return False



    ''' Start Game '''
    print('n+----------------+')
    print('|   M E M O R Y   |')
    print('+----------------+n')

    while not board.isComplete():

        ''' Print Game Board '''
        print(board)

        ''' Check if we completed a round '''
        if player.roundComplete():
            a,b = player.getPair()

            ''' If flipped tiles do not match, flip them back '''
            if a != b:
                player.coverPair((a,b))

        ''' Get user input '''
        user_input = input("nChoice: ")

        ''' Check for quit '''
        if user_input == "q" or user_input == "Q":
            break

        ''' Check if input is valid '''
        if validInput(user_input):

            ''' convert user_input to an integer '''
            idx = int(user_input)

            ''' Get Tile '''
            tile = board[idx]

            ''' flip tile '''
            player.flipTile(tile)

        else:
            print("Invalid Input!")

    ''' Game Over!!! '''
    if board.isComplete():

        ''' Print only if player completes game '''
        print('n+----------------+')
        print('|  W I N N E R ! |')
        print('+----------------+n')
        print(board)
        print("You won in {:d} moves!".format(player.moves))

    else:

        ''' Quitters never prosper! '''
        print('n+----------------+')
        print('| F A I L U R E  |')
        print('+----------------+n')
        print("Winners don't quit, LOSER!!!")

For my homework, I was told to extend the List class so that anything I put in the list would create a doubled up copy, here’s my working attempt:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

''' Dlist Class '''
class Dlist(list):

    ''' Initialize List '''
    def __init__(iterable=()):

        super().__init__(iterable)

    ''' Append to list * 2 '''
    def append(self, item):

        super().append(item * 2)

Programming, Python

Day 2: Learning Python

Today I got to play with objects. I had to make another memory game, only instead of procedural code, I had to demonstrate the use of class and method objects. This one was a bit more tricky, and I eventually ended up scrapping my code and starting it all over, but I got it figured out!

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

''' Tile Class '''
class Tile:

    ''' Initialize the Tiles '''
    def __init__(self, char):

        ''' uncovered value of character '''
        self.char = char

        ''' set default output as the covered state '''
        self.image = '_'

    ''' Change string evaluation '''
    def __str__(self):
        ''' return the image state '''
        return self.image

    ''' Evaluate equality '''
    def __eq__(self, other):
        return self.image == other.image

    ''' Evaluate inequality '''
    def __ne__(self, other):
        return not self.__eq__(other)

    ''' Flip tile '''
    def flip(self):
        if self.image == '_':
            self.image = self.char
        else:
            self.image = '_'

    ''' Check tile state '''
    def isCovered(self):
        return self.image == '_'

''' Set up the board '''
board      = [Tile(t) for t in ['A', 'B', 'C', 'D', 'E'] * 2]
flipped    = []
moves_made = 0

''' Randomize board '''
import random
random.shuffle(board)

''' Print Game Board '''
def printBoard(board):
    print(*board)
    print("0 1 2 3 4 5 6 7 8 9")

''' Evaluate input '''
def validInput(user_input):

    ''' Check if input is a number '''
    if user_input.isdigit():

        ''' Convert user_input to a integer '''
        idx = int(user_input)

        ''' check if idx is in range '''
        if idx < len(board):

            ''' check if tile is flipped '''
            if not board[idx].isCovered():
                print("Tile already flipped!")
                return False

            ''' All tests passed '''
            return True

        else:
            print("User input out of range")
            return False

    else:
        ''' Input not a number, ignore '''
        return False

''' Evaluate Game Progress '''
def gameComplete(board):

    ''' Iterate through all tiles in the board '''
    for tile in board:
        if tile.isCovered():
            return False

    ''' If we got this far, all tiles are flipped '''
    return True

def flipTile(idx):

    ''' Call moves_made into scope '''
    global moves_made

    ''' get tile instance '''
    tile = board[idx]

    ''' Check if we are uncovering a tile '''
    if tile.isCovered:
        moves_made += 1

    ''' Flip Tile '''
    tile.flip()

''' Start Game '''
while True:

    ''' Print Game Board '''
    printBoard(board)

    ''' Check if player has won '''
    if gameComplete(board):
        print("You won in {:d} moves!".format(moves_made))
        break

    ''' Check if we've completed a round '''
    if len(flipped) == 2:
        a,b = [board[i] for i in flipped]

        ''' If flipped tiles don't match, flip them back '''
        if a != b:
            for i in flipped:
                flipTile(i)

        ''' reset flipped array '''
        flipped = []

    ''' Get user input '''
    user_input = input()

    ''' Check for quit '''
    if user_input == "q" or user_input == "Q":
        break

    ''' Check if input is valid '''
    if validInput(user_input):

        ''' convert user_input to an integer '''
        idx = int(user_input)

        ''' attempt to flip tile '''
        flipTile(idx)

        ''' note which tile was flipped '''
        flipped.append(idx)
    else:
        print("Invalid Input!")

As homework for my Day 2, I was instructed to create a Dog object. Dogs can bark, dogs can die, but dead dogs can’t bark, nor die. This class shows that, requires python 3.3, will not work in python2 ( found out the hard way by accident ). This demonstrates that I learned how classes and objects work.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

''' Dog Class '''
class Dog:

    ''' Initialize dog '''
    def __init__(self, name):
        self.name  = name
        self.alive = True

    ''' Modify string output '''
    def __str__(self):

        ''' Check if our dog is alive '''
        if self.alive:
            return "A dog named " + self.name

        ''' Our dog is dead '''
        return "A dead dog named " + self.name

    ''' Make dog bark '''
    def bark(self):
        if self.alive:
            print(self.name + ": Bark! Bark! Bark!")
            return
        print("Dead dogs don't bark!")


    ''' KILL THE DOG '''
    def die(self):
        if self.alive:
            self.alive = False
            print(self.name + " died.")
            return
        print(self.name + " is already dead.")
Programming, Python

Day 1: Learning Python

This is a progress report of my Python learning. This is not to teach you how to code Python, this is merely the results of my Python homework. For my first lesson, I had to come up with a way to program a memory game in Python, here are my results.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Board Definitions
board         = ['A', 'B', 'C', 'D', 'E'] * 2
board_visible = list("__________")
board_flipped = []
board_steps   = 0

# Shuffle the board
import random
random.shuffle(board)

def printBoard(board):
    ''' Print the board '''
    print(" ".join(board))
    print("0 1 2 3 4 5 6 7 8 9")

def boardComplete(board):
    ''' Check if board is completed '''
    return not '_' in board

def inRange(value):
    ''' Check if value is digit '''
    if value.isdigit():
        test = int(value)
        ''' Ensure value is in range '''
        if test  9:
            ''' Out of range error '''
            print("Input out of range!")
            return False

        ''' Valid input, return true '''
        return True

    ''' Not an integer, ignore input '''
    return False

def quitApp(value):
    ''' Check if quit has been requested '''

    if value.isdigit():
        ''' Input is an integer, ignore it '''
        return False

    ''' Check if character is our quit character '''
    if value == 'q' or value == 'Q':
        return True

    ''' Illegal character '''
    print("Invalid option!")
    return False

def flipTile(idx):
    if board_visible[idx] == '_':
        board_visible[idx] = board[idx]
        board_flipped.append(idx)
        return True
    return False


''' Start Application '''
while True:
    # Show board and board key
    printBoard(board_visible)

    # check if we have one
    if boardComplete(board_visible):
        print("You win in {:d} moves!" . format(board_steps))
        break

    if len(board_flipped) == 2:
        a, b = [board[i] for i in board_flipped]
        if a == b:
            # don't flip if they match
            board_flipped = []
        else:
            for i in board_flipped:
                # flip cards back if they don't match
                board_visible[i] = '_'
                board_flipped    = []


    # get user input
    user_input = input("Input: ")

    if quitApp(user_input):
        break

    # check input type
    if inRange(user_input):
        idx = int(user_input)

        if flipTile(idx):
            board_steps = board_steps + 1
        else:
            print("Tile already flipped!")

Nothing too special, but it gets the job done. Just a simple 10 card memory game. I had to show that I’ve learned and understood the basic concepts taught by the course, so I may have done some things that might not be optimum. I could have done this whole game in less than 65 lines of code and gotten the same results, but it would not have demonstrated all that I had learned as part of the course.

Programming, Python

Learning Python 3

I’ve been an avid PHP programmer for quite a while, but now the time has come to move on. I’m taking the time to study Python, and I’m starting with Python 3.3.5. I considered doing Python 2, but, as I see it, even though Python 2 is still very common, by the time I get to a level where my skills are useful everyone should be on Python 3. At least the vast majority should be. I don’t want to waste my time on a deprecated version, and learn bad habits as they are not compatible with each other.

I figure there’s going to be a lot of tedious and boring work involved just to get to a point where I can code something useful. My first project will be something fun and entertaining. I’ll make a multi-threaded IRC bot from scratch. I don’t want to use other peoples libraries, not because I want to re-invent the wheel, but because I want to learn how it works at a low level so that I can apply those skills to other things. I will probably use libraries for some things, but I’d prefer to do as much as I can do on my own first.

I think this should be a very entertaining project for myself, and I hope that I can get a lot out of it in order to make myself more marketable for jobs in the future.