View Single Post
Old Feb 17th, 2006, 6:42 AM   #4
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
This is just what I knocked up in a text editor, so I haven't tested or run it yet, but it seems like it would work. I'll test it when I get home.
class Grid:
    def __init__(self, (width, height)):
        self.size = width, height
        self.grid = [[None for i in range(width)] for j in range(height)]

    def get(self, (x, y)):
        if not in_bounds((x, y)):
            raise ValueError, "coordinates are out of bounds"
        return self.grid[y][x]

    def put(self, (x, y), object):
        if not in_bounds((x, y)):
            raise ValueError, "coordinates are out of bounds"
        self.grid[y][x] = object

    def in_bounds(self, (x, y)):
        width, height = self.size
        return (x >= 0 and x < width) and (y >= 0 and y < height)

    def neighbours(self, (x, y)):
        neighbours = []
        for i in [x - 1, x, x + 1]:
            for j in [y - 1, y, y + 1]:
                if x == i and y == j:
                    continue
                try:
                    neighbours.append(self.get(i, j))
                except ValueError:
                    continue
        return neighbours

    def __iter__(self):
        for x, row in enumerate(self.grid):
            for y, square in enumerate(row):
                yield (x, y), square

class Cell:
    pass

cell = Cell()

class GameOfLife:
    def __init__(self, grid):
        self.grid = grid

    def turn():
        for position, square in self.grid:
            if square == None:
                if self.grid.neighbours(position).count(cell) == 3:
                    self.add_cell(position)
            else:
                if self.grid.neighbours(position).count(cell) <= 1:
                    self.remove_cell(position)
                if self.grid.neighbours(position).count(cell) >= 4:
                    self.remove_cell(position)

    def add_cell(self, position):
        self.grid.put(position, cell)

    def remove_cell(self, position):
        self.grid.put(position, None)
Arevos is offline   Reply With Quote