《付録》organism.py

# -*- coding: utf-8 -*-
#===============================================================================
#    Copyright (C) 2000-2008, 小泉ひよ子とタマゴ倶楽部
#
# Change History: Games
#    1988/05, Smalltalk
#    2004/09, Java
#    2005/02, C#
#    2005/03, Jython
# Change History: WPF examples
#    2008/01/25, IronPython 1.1.1 (download)
#    2008/08/22, IronPython 1.1.2 (download)
#    2008/03/16, ver.2.0, WPF
#    2008/00/00, ver.2.1, IronPython 1.1.2 
#===============================================================================
from hexOthello import HexStone

## --------------------               
class Colony:                           # 生命体: life-form
    def __init__(self):
        self.lives = 

    def addCell(self, cell):
        life = Unicellular(cell)
        for e in self.lives:
            e.adjoin(life)
        self.lives.append(life)

    def detectLife(self, name):
        life = None
        for e in self.lives:            
            if e.cell.name == name:
                life = e; break
        return life

## --------------------               
class Organism:
    def merge(self, s1, i1, s2, i2):
        p = (i1+4)%len(s2)
        q = 6-i2; d = 5-q
        return s1[:i1+1] + self.circulate(s2, p, q) + s1[i1+d:]

    def circulate(self, s, p, q):
        size = len(s)
        start = p+1; stop = p+q+1
        if size < stop:
            s = s[start:] + s[:stop-size]
        else:
            s = s[start:stop]
        return s

## --------------------               
class Unicellular(Organism):            # 単細胞生物: unicellular organism
    def __init__(self, cell):
        self.cell = cell
        self.surroundings = 
        
    def __repr__(self):
        return str(self.cell)
        
    def adjoin(self, cell):
        self.surroundings.append(cell)
        cell.surroundings.append(self)

    def combine(self):
        target = self.surroundings[0]
        indexes = self.intersection(target)
        print "target::", target.name(), indexes
        points = self.merge(
            target.points(),
            indexes[0],
            self.points(),
            len(indexes),
            )
        return Multicellular([self, target], points)

    def intersection(self, target):
        return [i for i, e in enumerate(target.points()) if e in self.points()]

    def points(self):
        return self.cell.points()
    
    def name(self):
        return self.cell.name

## --------------------               
class Multicellular(Organism):          # 多細胞生物: multicellular organism
    def __init__(self, lives, points):
        self.lives = lives
        self.points = points

    def __repr__(self):
        s = []
        for e in self.points:
            s.append("(%d,%d) "%(e.X, e.Y))         
        return "%s %s"%(self.lives, "".join(s))

## --------------------