Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from random import randint
- class Cell:
- def __init__(self):
- self._alive = False
- def set_alive(self, is_alive):
- self._alive = is_alive
- def is_alive(self):
- return self._alive
- def __str__(self):
- return "O" if self.is_alive() else "."
- # end Cell
- class Board:
- def __init__(self, rows, columns):
- self._rows = rows
- self._cols = columns
- self._field = [None]*rows
- for i in xrange(self._rows):
- this_row = [None]*cols
- for j in xrange(self._cols):
- this_row[j] = Cell()
- self._field[i] = this_row
- # end __init__
- def __str__(self):
- join_row = lambda r: "".join(str(cell) for cell in r)
- return "\n".join(join_row(r) for r in self._field)
- # end __str__
- def set_random_board(self):
- for r in xrange(self._rows):
- for c in xrange(self._cols):
- self._field[r][c] = randint(0, 3) == 3
- # end set_random_board
- def set_board(self, input):
- """Overwrites the board with the content of s.
- @input has 3 valid characters only -- . O \n
- - . means the cell is dead
- - O means the cell is alive
- - \n means end-of-row
- """
- if not input.strip():
- self._rows = self._cols = 0
- self._board = []
- return
- assert all(c in ('.', 'O', '\n') for c in input)
- rows = [r.strip() for r in input.split("\n") if r.strip()]
- num_columns = len(rows[0])
- assert all(len(r) == num_columns for r in rows)
- self._rows = len(rows)
- self._cols = num_columns
- self._field = [None]*len(rows)
- for index, r in enumerate(rows):
- this_row = [None]*num_columns
- for c in xrange(num_columns):
- this_row[c] = Cell()
- this_row[c].set_alive(r[c] == 'O')
- self._field[index] = this_row
- # end set_board
- def neighbours(self, row, col):
- valid_index = lambda x, y: (0 <= x < self._rows) and (0 <= y < self._cols)
- result = list()
- for r in (-1, 0, 1):
- for c in (-1, 0, 1):
- i, j = row+r, col+c
- if (i, j) == (row, col):
- continue
- if valid_index(i, j):
- result.append(self._field[i][j])
- return result
- # end neighbours
- def live_neighbours(self, row, col):
- return len([x for x in self.neighbours(row, col)
- if x.is_alive()])
- # end live_neighbours
- def next_generation(self):
- next_gen_alive = list()
- next_gen_dead = list()
- for r in xrange(self._rows):
- for c in xrange(self._cols):
- cell = self._field[r][c]
- alive_neighbours = self.live_neighbours(r, c)
- if ((cell.is_alive() and (alive_neighbours in (2, 3))) or
- (not cell.is_alive() and (alive_neighbours == 3))):
- next_gen_alive.append(cell)
- else:
- next_gen_dead.append(cell)
- for cell in next_gen_alive:
- cell.set_alive(True)
- for cell in next_gen_dead:
- cell.set_alive(False)
- # end next_generation
- def main():
- s = """
- .OO.
- .O..
- ....
- """
- b = Board(0, 0)
- b.set_board(s)
- print("Board is:\n%s" % str(b))
- b.next_generation()
- print("Board is:\n%s" % str(b))
- # end main
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement