Array2D实现好之后就是要来做一个程序了.
简单测程序 `生命游戏`,当然以前发过的,不过是使用SDL+C++写的.
现在直接使用Python写,代码如下.
这个主要是棋盘的设定.
class LifeGrid: DEAD_CELL = 0 LIVE_CELL = 1 def __init__(self,numRows,numCols): self._grid = Array2D(numRows,numCols) self.configure(list()) def numRows(self): return self._grid.numRows() def numCols(self): return self._grid.numCols() def configure(self,coordList): for i in range(self.numRows()): for j in range(self.numCols()): self.clearCell(i,j) for coord in coordList: self.setCell(coord[0],coord[1]) def isLiveCell(self,row,col): return self._grid[row,col] == LifeGrid.LIVE_CELL def clearCell(self,row,col): self._grid[row,col] = LifeGrid.DEAD_CELL def setCell(self,row,col): self._grid[row,col] = LifeGrid.LIVE_CELL def numLiveNeighbors(self,r,c): A00,A01,A02 = 0,0,0 A10,A11,A12 = 0,0,0 A20,A21,A22 = 0,0,0 rows = self.numRows() cols = self.numCols() grid = self._grid if r-1 >= 0 and c-1 >= 0: A00 = grid[r-1,c-1] if r-1 >= 0: A01 = grid[r-1,c] if r-1 >= 0 and c+1 <= cols-1: A02 = grid[r-1,c+1] if c-1 >= 0: A10 = grid[r,c-1] if c+1 <= cols - 1: A12 = grid[r,c+1] if r+1<= rows-1 and c-1>=0: A20 = grid[r+1,c-1] if r+1<= rows-1: A21 = grid[r+1,c] if r+1<= rows-1 and c+1 <= cols-1: A22 = grid[r+1,c+1] return A00 + A01 + A02 + \ A10 + A11 + A12 +\ A20 + A21 + A22
这个是主函数.
INIT_CONFIG = [(1,1),(1,2),(2,2),(3,2)] GRID_WIDTH = 5 GRID_HEIGHT = 5 NUM_GENS = 8 #from IPython.display import clear_output import time,sys def main(): grid = LifeGrid(GRID_WIDTH,GRID_HEIGHT) grid.configure(INIT_CONFIG) draw(grid) sys.stdout.flush() #clear_output() time.sleep(0.5) for i in range(NUM_GENS): print "Frame:",i evolve(grid) draw(grid) sys.stdout.flush() #clear_output() time.sleep(0.5) def evolve(grid): liveCells = list() for i in range(grid.numRows()): for j in range(grid.numCols()): neighbors = grid.numLiveNeighbors(i,j) #print (i,j),"=",neighbors if (neighbors == 2 and grid.isLiveCell(i,j)) or \ (neighbors == 3): liveCells.append((i,j)) grid.configure(liveCells) def draw(grid): for r in range(grid.numRows()): for c in range(grid.numCols()): if grid.isLiveCell(r,c): print "@ ", else: print ". ", print print main()
结果如下.
当然了我这里是在IPython notebook中运行的.如果把clear_output()函数打开的话可以得到一个动画效果.
耶.