Encapsulates a Life board Attributes: X,Y : horizontal and vertical size of the board state : dictionary mapping (x,y) to 0 or 1 Methods: display(update_board) -- If update_board is true, compute the next generation. Then display the state
| 20 | |
| 21 | |
| 22 | class LifeBoard: |
| 23 | """Encapsulates a Life board |
| 24 | |
| 25 | Attributes: |
| 26 | X,Y : horizontal and vertical size of the board |
| 27 | state : dictionary mapping (x,y) to 0 or 1 |
| 28 | |
| 29 | Methods: |
| 30 | display(update_board) -- If update_board is true, compute the |
| 31 | next generation. Then display the state |
| 32 | of the board and refresh the screen. |
| 33 | erase() -- clear the entire board |
| 34 | make_random() -- fill the board randomly |
| 35 | set(y,x) -- set the given cell to Live; doesn't refresh the screen |
| 36 | toggle(y,x) -- change the given cell from live to dead, or vice |
| 37 | versa, and refresh the screen display |
| 38 | |
| 39 | """ |
| 40 | def __init__(self, scr, char=ord('*')): |
| 41 | """Create a new LifeBoard instance. |
| 42 | |
| 43 | scr -- curses screen object to use for display |
| 44 | char -- character used to render live cells (default: '*') |
| 45 | """ |
| 46 | self.state = {} |
| 47 | self.scr = scr |
| 48 | Y, X = self.scr.getmaxyx() |
| 49 | self.X, self.Y = X - 2, Y - 2 - 1 |
| 50 | self.char = char |
| 51 | self.scr.clear() |
| 52 | |
| 53 | # Draw a border around the board |
| 54 | border_line = '+' + (self.X * '-') + '+' |
| 55 | self.scr.addstr(0, 0, border_line) |
| 56 | self.scr.addstr(self.Y + 1, 0, border_line) |
| 57 | for y in range(0, self.Y): |
| 58 | self.scr.addstr(1 + y, 0, '|') |
| 59 | self.scr.addstr(1 + y, self.X + 1, '|') |
| 60 | self.scr.refresh() |
| 61 | |
| 62 | def set(self, y, x): |
| 63 | """Set a cell to the live state""" |
| 64 | if x < 0 or self.X <= x or y < 0 or self.Y <= y: |
| 65 | raise ValueError("Coordinates out of range %i,%i" % (y, x)) |
| 66 | self.state[x, y] = 1 |
| 67 | |
| 68 | def toggle(self, y, x): |
| 69 | """Toggle a cell's state between live and dead""" |
| 70 | if x < 0 or self.X <= x or y < 0 or self.Y <= y: |
| 71 | raise ValueError("Coordinates out of range %i,%i" % (y, x)) |
| 72 | if (x, y) in self.state: |
| 73 | del self.state[x, y] |
| 74 | self.scr.addch(y + 1, x + 1, ' ') |
| 75 | else: |
| 76 | self.state[x, y] = 1 |
| 77 | if curses.has_colors(): |
| 78 | # Let's pick a random color! |
| 79 | self.scr.attrset(curses.color_pair(random.randrange(1, 7))) |