GoLGrid.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. namespace MultiAgentSystemPCL
  3. {
  4. public delegate void gridUpdated(bool[][] newGrid);
  5. public class GoLGrid
  6. {
  7. protected int WIDTH;
  8. protected int HEIGHT;
  9. bool[][] gridCells = null;
  10. public event gridUpdated gridUpdatedEvent = null;
  11. public GoLGrid(int _width, int _height, double _cellDensity)
  12. {
  13. WIDTH = _width;
  14. HEIGHT = _height;
  15. Random randomGen = new Random();
  16. gridCells = new bool[WIDTH][];
  17. for(int i = 0; i < WIDTH; i++) {
  18. gridCells[i] = new bool[HEIGHT];
  19. for (int j = 0; j < HEIGHT; j++)
  20. {
  21. if (randomGen.NextDouble() < _cellDensity)
  22. {
  23. gridCells[i][j] = true;
  24. }
  25. }
  26. }
  27. }
  28. public void Update(bool _withUpdate = true)
  29. {
  30. if (_withUpdate)
  31. {
  32. bool[][] newGrid = new bool[WIDTH][];
  33. for (int i = 0; i < WIDTH; i++)
  34. {
  35. newGrid[i] = new bool[HEIGHT];
  36. for (int j = 0; j < HEIGHT; j++)
  37. {
  38. int count = NbCellAround(i, j);
  39. if (count == 3 || (count == 2 && gridCells[i][j]))
  40. {
  41. newGrid[i][j] = true;
  42. }
  43. }
  44. }
  45. gridCells = newGrid;
  46. }
  47. if (gridUpdatedEvent != null)
  48. {
  49. gridUpdatedEvent(gridCells);
  50. }
  51. }
  52. private int NbCellAround(int _cellRow, int _cellCol)
  53. {
  54. int count = 0;
  55. int row_min = (_cellRow - 1 < 0 ? 0 : _cellRow - 1);
  56. int row_max = (_cellRow + 1 > WIDTH-1 ? WIDTH-1 : _cellRow + 1);
  57. int col_min = (_cellCol - 1 < 0 ? 0 : _cellCol - 1); ;
  58. int col_max = (_cellCol + 1 > HEIGHT-1 ? HEIGHT-1 : _cellCol + 1); ;
  59. for (int row = row_min; row <= row_max; row++)
  60. {
  61. for (int col = col_min; col <= col_max; col++)
  62. {
  63. if (gridCells[row][col] && !(row == _cellRow && col == _cellCol)) {
  64. count++;
  65. }
  66. }
  67. }
  68. return count;
  69. }
  70. public void ChangeState(int _row, int _col)
  71. {
  72. gridCells[_row][_col] = !gridCells[_row][_col];
  73. }
  74. }
  75. }