MainWindow.xaml.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using MultiAgentSystemPCL;
  2. using System;
  3. using System.Linq;
  4. using System.Windows;
  5. using System.Windows.Input;
  6. using System.Windows.Media;
  7. using System.Windows.Shapes;
  8. using System.Windows.Threading;
  9. namespace GameOfLife
  10. {
  11. public partial class MainWindow : Window
  12. {
  13. DispatcherTimer updateTimer;
  14. bool running = false;
  15. GoLGrid grid;
  16. public MainWindow()
  17. {
  18. InitializeComponent();
  19. Loaded += MainWindow_Loaded;
  20. gridCanvas.MouseDown += gridCanvas_MouseDown;
  21. }
  22. void gridCanvas_MouseDown(object _sender, MouseButtonEventArgs _mouseEvent)
  23. {
  24. if (_mouseEvent.LeftButton == MouseButtonState.Pressed)
  25. {
  26. grid.ChangeState((int)(_mouseEvent.GetPosition(gridCanvas).X / 3), (int)(_mouseEvent.GetPosition(gridCanvas).Y / 3));
  27. grid.Update(false);
  28. }
  29. else if (_mouseEvent.RightButton == MouseButtonState.Pressed)
  30. {
  31. if (running)
  32. {
  33. updateTimer.Stop();
  34. }
  35. else
  36. {
  37. updateTimer.Start();
  38. }
  39. running = !running;
  40. }
  41. }
  42. void MainWindow_Loaded(object _sender, RoutedEventArgs _e)
  43. {
  44. grid = new GoLGrid((int) gridCanvas.ActualWidth / 3, (int) gridCanvas.ActualHeight / 3, 0.1);
  45. grid.gridUpdatedEvent += grid_gridUpdatedEvent;
  46. updateTimer = new DispatcherTimer();
  47. updateTimer.Tick += updateTimer_Tick;
  48. updateTimer.Interval = new TimeSpan(0, 0, 0, 0, 500);
  49. updateTimer.Start();
  50. running = true;
  51. }
  52. void grid_gridUpdatedEvent(bool[][] _grid)
  53. {
  54. gridCanvas.Children.Clear();
  55. for(int row = 0; row < _grid.Count(); row++) {
  56. for (int col = 0; col < _grid[0].Count(); col++)
  57. {
  58. if (_grid[row][col])
  59. {
  60. DrawCell(row, col);
  61. }
  62. }
  63. }
  64. }
  65. private void DrawCell(int _row, int _col)
  66. {
  67. Rectangle rect = new Rectangle();
  68. rect.Width = 3;
  69. rect.Height = 3;
  70. rect.Margin = new Thickness(3 * _row, 3 * _col, 0, 0);
  71. rect.Stroke = Brushes.Black;
  72. rect.Fill = Brushes.Black;
  73. gridCanvas.Children.Add(rect);
  74. }
  75. void updateTimer_Tick(object _sender, EventArgs _e)
  76. {
  77. grid.Update();
  78. }
  79. }
  80. }