Lecture 33 Log into Windows/ACENET. Download and extract GameOfLife.zip. Double-click into the project folders to the solution file. Double-click on the solution file to start MS VS. One last issue with the Graph Function project. In the panel Resize handler, the RedrawPanel method should be called only if the data exists so there should be a test: if (data != null) { RedrawPanel(); } Questions? Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 1 Outline Cellular automata Conway's Game of Life GUI interface Two-dimensional arrays Game of Life project grid_Click handler CountNeighbors method Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 2 Cellular Automata Cellular automata are used in discrete modeling. The model consists of a regular grid of cells, each of which can be in one of a finite number of states. Time is discrete, so the state of a cell at time t+1 is a function of the state of a finite number of neighboring cells at time t. A rule (or function) is applied to every cell at each time step and all updates happen at once creating a new generation. Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 3 Conway's Game of Life Conway's Game of Life is one well-known example of a two-state, two-dimensional cellular automaton. The cells are square, and the neighborhood is the 8 cells immediately adjacent (i.e., including diagonally) to a cell. At each generation, a cell may be live (represented by a '*' in the cell) or dead (represented a blank cell). Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 4 Conway's Game of Life The original rules posed by Conway are: If a live cell has fewer than 2 live neighbors, the cell dies of loneliness If a live cell has more than 3 live neighbors, the cell dies of overcrowding If a dead cell has exactly 3 live neighbors, the cell becomes alive by birth Otherwise, the cell state is unchanged Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 5 Conway's Game of Life Here is an example of how the rules work. An initial condition is shown below. The neighbors of the center cell are shaded. * * * Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 6 Conway's Game of Life For this example, the left figure shows the number of live neighbors each cell has at this time. The right figure shows the grid state at the next time step after applying the rules. 0 1 1 1 0 Monday, April 4 0 2 1 2 0 0 3 2 3 0 0 2 1 2 0 0 1 1 1 0 * * * CS 205 Programming for the Sciences - Lecture 33 7 Conway's Game of Life The rules were applied as follows: The end live cells have only one live neighbor, so they die The dead cells above and below the center live cell each have 3 live neighbors, so they become alive by birth The center live cell has two live neighbors, so it continues to live All other cells continue with their present state. Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 8 Conway's Game of Life When we apply the rules again, we see that the grid returns to the initial condition. This particular configuration oscillates between the two states and is often called a blinker. 0 0 0 0 0 Monday, April 4 1 2 3 2 1 1 1 2 1 1 1 2 3 2 1 0 0 0 0 0 * * * CS 205 Programming for the Sciences - Lecture 33 9 Cellular Automata Research using cellular automata covers several areas looking at different definitions of neighbor or different death/birth rules as applied to different application areas looking at different grid arrangements, e.g. a grid of hexagons with 6 neighbors finding interesting configurations that live perpetually with many steps in their cycles and understanding the characteristics of those configurations Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 10 References "Cellular Automaton" from Wikipedia, URL: http://en.wikipedia.org/wiki/Cellular_automaton "Cellular Automaton" from Wolfram Mathworld, URL: http://mathworld.wolfram.com/CellularAutomaton.html "Conway's Game of Life" from Wikipedia, URL: http://en.wikipedia.org/wiki/Conway's_Game_of_Life "Life" from Wolfram Mathworld, URL: http://mathworld.wolfram.com/Life.html Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 11 GUI Interface For this exercise, you are given the following GUI interface: Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 12 GUI Interface The GUI interface shown consists of Two textboxes, one for the number of generations to be computed when the Next button is clicked (txtGenerationsPerClick) and one for the time between generation updates (txtUpdateTime). Two buttons, one to start the next generation updates (btnNext) and one to reset the simulation state back to the way it is when the program first starts (btnClear). Two buttons that will allow game configurations to be loaded from (btnLoad) and saved to (btnSave) text files. Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 13 GUI Interface The grid showing each cell automaton state is a two-dimensional array of Labels. In order to allow this project to be easily modified for different sizes of grids, this array of labels is dynamically created when the application loads. (Besides, it would be tedious to "draw" each cell separately.) Thus these Labels do not appear in C# GUI designer. They only appear when the program is run. Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 14 Two-Dimensional Arrays A two-dimensional (2D) array is a data structure that is collection of elements of the same type that are accessed by giving an index for each of two dimensions. Conceptually, they may be thought of as similar to matrices. The C# syntax for declaring a 2D array variable is: <element type> [ , ] <name>; indicator of 2 dimensions Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 15 Two-Dimensional Arrays For our Game of Life project, we need two 2Darrays. One of Labels that is the current generation displayed by the GUI Label [ , ] grid; One of strings that is the computed next generation string [ , ] nextGrid; Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 16 Two-Dimensional Arrays As with one-dimensional arrays, the actual array object must be created using the new operator. <2D­array var> = new <element type>[#rows,#cols]; For example, if we wanted our grids to be 10x20 we could write: grid = new Label [10,20]; newGrid = new string [10,20]; Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 17 Two-Dimensional Arrays Elements of an array are accessed by giving an index for each dimension of the array. For example, in our project, a grid Label's Text property might be accessed using index variables i and j: // Set Text property of grid[i,j] grid[i,j].Text = "*"; // Get Text property of grid[i,j] if (grid[i,j].Text == " ") // dead cell Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 18 Two-Dimensional Arrays The easiest way to think about 2D arrays is that the first dimension index is a row index and the second dimension index is a column index. As with screen coordinates the [0,0] element is in the upper left corner: [ ,0] [ ,1] [ ,2] [ ,3] ... [ ,#cols-1] [0, ] [1, ] : [#rows-1, ] Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 19 Two-Dimensional Arrays Often we want to access each element of the 2D array. This can be done using nested forloops with the outer loop variable counting the row indexes and the inner loop variable counting the column indexes. The array method GetUpperBound(dim#) returns the maximum index value in the dim# dimension. Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 20 Two-Dimensional Arrays // Get maximum index in each dimension int rowMax = grid.GetUpperBound(0); int colMax = grid.GetUpperBound(1); // Loop over each row index for (int row = 0; row <= rowMax; row++) { // Loop over each column index for (int col = 0; col <= colMax; col++) { // do something with grid[row,col] } } Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 21 Game of Life Project We will work on this project for about a week. The entire application consists of: A Load event handler for the base Form (GameOfLife_Load). The Load event happens when the program/form is created and loaded into the computer system. It creates the 2D grid of Labels for display and the next generation 2D grid of strings by calling the MakeGrid( ) method. These methods are provided. A Click event handler (grid_Click) that is shared by all the Labels. This method toggles the Label's Text property between "*" and " ". Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 22 Game of Life Project A Click event handler for the Next button (btnNextGeneration_Click) that gets the user input n, the number of generations to simulate, and t, the time between generation updates, from the textboxes (txtGenerationsPerClick and txtUpdateTime) and causes n generations to be simulated, waiting t milliseconds between updates. This method is partially written. A Click event handler for the Clear button (btnClear_Click) that resets the application to its initial state. This method is provided. Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 23 Game of Life Project Three methods used by the Next button Click event handler. CountNeighbors receives a row index, row, and a column index, col, and returns the number of live neighbors to cell grid[row,col]. ComputeGeneration does not receive or return anything. This method uses CountNeighbors and the rules of Conway's Game of Life to compute the next generation value of a grid cell and store it in the corresponding nextGrid cell. It also increments generationCount. Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 24 Game of Life Project DisplayGeneration does not receive or return anything. This method copies the values in the nextGrid cells into the corresponding grid cells. It also updates the generation count label (lblGenerationCount) with the new generation number (generationCount). Two Click event handlers for the Load and Save buttons that will allow the user to load and save game configuration in textfiles. Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 25 grid_Click( ) grid_Click( ) is the Click event handler for the grid labels. We want to alternate between "*" and a space. Similar to the digit button handler in the SimpleRPNCalculator project, the only tricky part is we need to tell the compiler to treat the sender argument as a Label like so: Label cell = (Label) sender; Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 26 grid_Click( ) Otherwise the algorithm is simple 1. If cell.Text is a "*" then 1.1 Set cell.Text to a space (" ") Else (cell is a space) 1.2 Set cell.Text to "*" Write the code for grid_Click( ). Try running the program and clicking in a cell. Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 27 CountNeighbors( ) CountNeighbors( ) receives a row index, row, and a column index, col, and returns the number of live neighbors to cell grid[row,col]. How do we find the neighbors of grid[row,col]? [row,col] Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 28 CountNeighbors( ) The algorithm for this method is 1. Declare and initialize a counter variable to 0 2. For each of the neighbor cells, if it is live (i.e., its Text property is "*"), increment the counter variable. 3. Return the counter variable The tricky part is that we can only use legal indexes to access the neighbors (i.e. >= 0 and < the maximum index for the dimension). This is handled by the if-statements of Step 2. Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 29 CountNeighbors( ) Write the code for CountNeighbors( ). Since the rest of the program is not written yet, we can test this method in the grid_Click handler as follows. Declare two integer variables i and j Call the provided debugging method ParseGridName. This method receives a string that is the name of the cell and passes back two integers that are the cell's grid indexes: ParseGridName(cell.Name, out i, out j); Call CountNeighbors with i and j to find out the number of live neighbors the cell has and store it in an integer variable Show a MessageBox with the cell's name and the number of live neighbors it has. Monday, April 4 CS 205 Programming for the Sciences - Lecture 33 30