| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- using System;
- namespace MultiAgentSystemPCL
- {
- public delegate void gridUpdated(bool[][] newGrid);
- public class GoLGrid
- {
- protected int WIDTH;
- protected int HEIGHT;
- bool[][] gridCells = null;
- public event gridUpdated gridUpdatedEvent = null;
- public GoLGrid(int _width, int _height, double _cellDensity)
- {
- WIDTH = _width;
- HEIGHT = _height;
- Random randomGen = new Random();
- gridCells = new bool[WIDTH][];
- for(int i = 0; i < WIDTH; i++) {
- gridCells[i] = new bool[HEIGHT];
- for (int j = 0; j < HEIGHT; j++)
- {
- if (randomGen.NextDouble() < _cellDensity)
- {
- gridCells[i][j] = true;
- }
- }
- }
- }
- public void Update(bool _withUpdate = true)
- {
- if (_withUpdate)
- {
- bool[][] newGrid = new bool[WIDTH][];
- for (int i = 0; i < WIDTH; i++)
- {
- newGrid[i] = new bool[HEIGHT];
- for (int j = 0; j < HEIGHT; j++)
- {
- int count = NbCellAround(i, j);
- if (count == 3 || (count == 2 && gridCells[i][j]))
- {
- newGrid[i][j] = true;
- }
- }
- }
- gridCells = newGrid;
- }
- if (gridUpdatedEvent != null)
- {
- gridUpdatedEvent(gridCells);
- }
- }
- private int NbCellAround(int _cellRow, int _cellCol)
- {
- int count = 0;
- int row_min = (_cellRow - 1 < 0 ? 0 : _cellRow - 1);
- int row_max = (_cellRow + 1 > WIDTH-1 ? WIDTH-1 : _cellRow + 1);
- int col_min = (_cellCol - 1 < 0 ? 0 : _cellCol - 1); ;
- int col_max = (_cellCol + 1 > HEIGHT-1 ? HEIGHT-1 : _cellCol + 1); ;
- for (int row = row_min; row <= row_max; row++)
- {
- for (int col = col_min; col <= col_max; col++)
- {
- if (gridCells[row][col] && !(row == _cellRow && col == _cellCol)) {
- count++;
- }
- }
- }
- return count;
- }
- public void ChangeState(int _row, int _col)
- {
- gridCells[_row][_col] = !gridCells[_row][_col];
- }
- }
- }
|