Source

the_game_of_life / src / map.py

Full commit
'''
Created on May 23, 2011

@author: strelok
'''

class Torus(list):
    def __getitem__(self, index):
        try:
            return super(Torus, self).__getitem__(index)
        except IndexError:
            index = index % super(Torus, self).__len__()
            return super(Torus, self).__getitem__(index)
        
    def __setitem__(self, index, value):
        try:
            super(Torus, self).__setitem__(index, value)
        except IndexError:
            index = index % super(Torus, self).__len__()
            super(Torus, self).__setitem__(index, value)
            
class Figure(object):
    def __init__(self, points):
        self.figure = points
        self._width = None
        self._height = None
        
    @property
    def width(self):
        if not self._width:
            self._width = max([x[1] for x in self.figure]) + 1
        return self._width
        
    @property
    def height(self):
        if not self._height:
            self._height = max([x[0] for x in self.figure]) + 1
        return self._height
    
    def draw(self):
        prev_x = 0
        prev_y = 0
        out = []
        line = ''
        for x, y in self.figure:
            if x != prev_x:
                line = line.ljust(self.width)
                out.append(line)
                line = ''
                if y != 0:
                    line = line.rjust(y)
            elif y - prev_y > 1:
                line += ' ' * (y - prev_y - 1)
            elif y - prev_y == 1 and not line:
                line += ' '
            line += 'X'

            prev_x = x
            prev_y = y
        line = line.ljust(self.width)
        out.append(line)
        return '\n'.join(out)


class Map(object):
    '''
    classdocs
    '''

    def __init__(self, width, height, **kwargs):
        '''
        Constructor
        '''
        self.width = width
        self.height = height
        
    def create_map(self):
        self.map = Torus(Torus(range(self.width)) for x in range(self.height))
        
    def tick(self):
        for x, row in enumerate(self.map):
            for y, cell in enumerate(row):
                neighbours = self.get_neighbours_count(x, y)
                if neighbours == 3 and not cell:
                    self.map[x][y] = 1
                elif (neighbours > 3 or neighbours < 1) and cell:
                    self.map[x][y] = 0
            
    def get_neighbours_count(self, x, y):
        cells = ([(x-1, i) for i in range(y-1,y+2)] 
                 + [(x+1, i) for i in range(y-1,y+2)] 
                 + [(x, i) for i in range(y-1, y+2,2)])
        total = sum([self.map[x][y] for x, y in cells])
        return total
    
    def place_figure(self, figure):
        pass
    
    def draw(self):
        for row in self.map:
            print '| %s |' % ' | '.join(['X' if x else ' ' for x in row])