Life in WPF |
Written by Mike James | ||||||||
Monday, 28 June 2010 | ||||||||
Page 4 of 4
A call to setupTimer has to be added to the end of the Window_Loaded event handler: setupTimer(); Finally we need to write the button click handler to start and stop the timer: private void button1_Click( This simply toggles the text on the button from Run to Stop and back and starts and stops the timer. Computing LifeThe counter routine is easy enough once you have worked out where the eight neighbours of the cell cells(i,j) are. The big problem is that to count the number of live cells we are going to want to use expressions such as: cells[i - 1, j].state + cells[i + 1, j].state but the system does not automatically cast a boolean value to an integer value and so such an expression gives an error message. There are many ways of dealing with this problem but the most interesting is to add a custom implicit cast to the Cell class that automatically converts its Type, i.e. Cell to Int. Notice we are going one step further than casting a boolean to an int - by casting Cell to int and arranging for its value to be based on its state property we are making state a default property for the Cell class. To define the implicit cast we have to add the following method to the Cell class: public static With this addition we can simply add Cell objects together and writer counter in a straightforward way: private void counter()We also need to remember to declare the array n: private int[,] n = At the end of the routine n(i,j) contains the number of live neighbours that the cell cells(i,j) has. This information is used by nextgen to update the life array according to the rules of Life. private void nextgen() This looks complicated but you should be able to understand it if you break it down into its component parts. First there is a pair of outer loops that scan through the entire array. For each of the elements the number of neighbours n(i,j) is tested to see if there are 3, 4 or more or 1 or less. In each case the state of cells(i,j) is updated accordingly. That’s all there is to the logic of Life and at this point you can enter a pattern and see how it develops.
A pattern developing From this point there is a lot that can be added to the basic project. Add a style to the Ellipses so that they look better, display each ellipse in a color that depends on the number of neighbours they have, add a save and load option etc. To access the code for this project, once you have registered, click on CodeBin.
<ASIN:0470477229> <ASIN:1430272058> <ASIN:1430272406> <ASIN:1430225394> |
||||||||
Last Updated ( Monday, 28 June 2010 ) |