1

I am implementing Conway's game of life in Python and would like to produce a small GUI to see the model evolving.

My code:

def __init__(self,grid):
        self.top = Tkinter.Tk()

        self.multiplier = 50

        self.gridSize = grid.getSize()
        self.gridArray = grid.getGrid()



        self.C = Tkinter.Canvas(self.top, bg="black", height = self.gridSize[1]*self.multiplier,
                           width=self.gridSize[0]*self.multiplier)
        self.C.pack()


    def renderGrid(self, grid):



        for x in range(0,self.gridSize[1]-1):
            for y in range(0,self.gridSize[0]-1):

                agent = grid.getAtPos(Coordinates2D(x,y))
                agent = agent[0]

                mx = x*self.multiplier
                my = y*self.multiplier

                if(agent.state == 0):
                    p = self.C.create_rectangle(mx,my,mx+self.multiplier,my+self.multiplier,
            fill="white", width=3)

        self.C.update()

I essentially want to be able to pass a grid object to this class and have it update the canvas drawing white squares wherever an agent has status 0.

While this works in principle (Ie: It produces the initial display) it doesn't seem to update. The code from which I am calling it:

grid = ObjectGrid2D(10,10, "golgrid")
g = GameOfLifeRenderer(grid)


for i in range(10):
    print i
    for x in range(10):
        for y in range(10):

            h = GOLCell(1)
            h.state == 0
            grid.moveAgent(Coordinates2D(x,y), h)
    g.renderGrid(grid)
    sleep(5)

Any advice on how I might improve my code?

Thanks!

MrD
  • 4,986
  • 11
  • 48
  • 90
  • There are better ways to do animation than a custom loop that includes `sleep`. See http://stackoverflow.com/a/25431690/7432 – Bryan Oakley Apr 08 '16 at 16:49

1 Answers1

2

It doesn't look like you're updating the canvas in your forloop. Try adding the following line after grid.moveAgent(...)

 g.C.update()
Pythonista
  • 11,377
  • 2
  • 31
  • 50
  • I am calling renderGrid each time my model is stepped and renderGrid ends with self.C.update() so that should od it? – MrD Apr 08 '16 at 15:15
  • 1
    Yes, it's updating the grid (canvas) after everything has been moved, but not activey updating on each iteration. Hence, why you don't see the grid being moved around – Pythonista Apr 08 '16 at 15:16