Monday, January 9, 2012

[Level 2] Flyweight in Python.

#!/usr/bin/env python
import random

class Black(object):
    __instance = None
    def __new__(cls):
        if not cls.__instance:
            cls.__instance = super(Black, cls).__new__(cls)
        return cls.__instance

    def __str__(self):
        return 'black'

class White(object):
    __instance = None
    def __new__(cls):
        if not cls.__instance:
            cls.__instance = super(White, cls).__new__(cls)
        return cls.__instance

    def __str__(self):
        return 'white'

class BlackAndWhite(object):
    __black = Black()
    __white = White()
    def __new__(cls, index):
        if index == 0:
            return cls.__black
        else:
            return cls.__white

    def __init__(self, index):
        pass

class Board(object):
    def __init__(self, size):
        self.__size = size
        self.__planet = [ [ None for i in range(self.__size) ] for j in range(self.__size) ]

    def setPlanet(self):
        while True:
            x = int(random.random() * self.__size)
            y = int(random.random() * self.__size)
            if self.__planet[x][y] != None:
                continue
            else:
                z = int(random.random() * 2)
                self.__planet[x][y] = BlackAndWhite(z)

            if self.isCompleted():
                break

    def isCompleted(self):
        for x in range(0, self.__size):
            for y in range(0, self.__size):
                if self.__planet[x][y] == None:
                    return False
        return True

    def getPlanet(self):
        self.setPlanet()
        return self.__planet

    def displayPlanet(self):
        print [ [str(j) for j in i ] for i in self.getPlanet() ]

if __name__ == '__main__':
    b = Board(4)
    b.displayPlanet()
    pass
$ ./testFlyweight.py
[['black', 'white', 'black', 'black'], ['white', 'black', 'white', 'black'], ['black', 'black', 'black', 'black'], ['white', 'black', 'white', 'white']]
$
Wish this helps. regards, Stanley Huang