from graphics import * from random import * ROWS = 50 COLS = 50 CELLSIZE = 10 OFFSET = 3 #Draw lines to an active window, based on constants #defined above: ROWS, COLS, CELLSIZE, and OFFSET def drawLines(win): for i in range(0, ROWS+1): l = Line(Point(OFFSET,OFFSET + i*CELLSIZE), Point(COLS*CELLSIZE+OFFSET, OFFSET + i*CELLSIZE)) l.setFill("grey") l.draw(win) for i in range(0, COLS+1): l = Line(Point(OFFSET + i*CELLSIZE, OFFSET), Point( OFFSET+i*CELLSIZE, ROWS*CELLSIZE+OFFSET)) l.setOutline("grey") l.draw(win) #Given a particular row and column, create a #square for that cell def getSquare(row, col): p1 = Point(OFFSET+1 + row*CELLSIZE, OFFSET+1 + col * CELLSIZE) p2 = Point(OFFSET-1 + (row+1)*CELLSIZE, OFFSET-1 + (col+1)*CELLSIZE) sq = Rectangle(p1, p2) sq.setFill("black") return sq #Create a list of squares, corresponding to cells #that have a 1 in them, draw the squares, and #return the list of squares def drawBoard(win, board): squares=[] for i in range(ROWS): for j in range(COLS): if board[i][j] == 1: squares.append(getSquare(i,j)) for sq in squares: sq.draw(win) return squares def main(): #initialize the 2d list board = [] for i in range(ROWS): board.append([0]*COLS) #draw the lines win = GraphWin("Life Demo", ROWS*CELLSIZE+2, COLS*CELLSIZE+2) win.autoflush = False drawLines(win) for times in range(5): #With some probability, set a cell to have life for i in range(ROWS): for j in range(COLS): if random() < 0.1: board[i][j] = 1 #Draw the squares corresponding to spots where #the board has a 1. Return the list of squares #so that they can be removed later squares = drawBoard(win, board) #pause win.getMouse() #get rid of the squares from the window and #return the board to having to squares alive for i in range(ROWS): for j in range(COLS): board[i][j]=0 for sq in squares: sq.undraw() win.close() main()