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)

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.