ldirko

game of life

Aug 17th, 2020 (edited)
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // game of life
  2. // fastled 16x16 matrix demo
  3. // Yaroslaw Turbin 18.08.2020
  4. // based on sketch https://github.com/CodingTrain/website/blob/master/CodingChallenges/CC_085_The_Game_of_Life/P5/sketch.js
  5. //
  6.  
  7.  
  8. #include "FastLED.h"
  9.  
  10. // Matrix size
  11. #define NUM_ROWS 16
  12. #define NUM_COLS 16
  13.  
  14. // LEDs pin
  15. #define DATA_PIN 3
  16.  
  17. // LED brightness
  18. #define BRIGHTNESS 255
  19.  
  20. #define NUM_LEDS NUM_ROWS * NUM_COLS
  21.  
  22. // Define the array of leds
  23. CRGB leds[NUM_LEDS];
  24. byte grid [NUM_LEDS];
  25. byte next [NUM_LEDS];
  26. byte counter = 0;
  27.  
  28.  
  29. void setup() {
  30.   FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
  31.   FastLED.setBrightness(BRIGHTNESS);
  32.   random16_set_seed(4832); // Awesome randomizer
  33. random16_add_entropy(analogRead(2));
  34. int ranstart = random16();
  35. }
  36.  
  37.  
  38. void loop() {
  39.  
  40.   if (counter == 0) { initarr ();
  41.                       counter=1; }
  42.  
  43. EVERY_N_MILLISECONDS(200) {
  44.     updatelife();
  45.       FastLED.show();
  46. }
  47.  
  48.  
  49. EVERY_N_MILLISECONDS(50000) {
  50. for (byte i = 0; i < 50; i++) {
  51.  
  52.   fadeToBlackBy(leds, NUM_LEDS, 255*i/49);
  53.         FastLED.delay(50);
  54.  
  55. }
  56.  
  57.     initarr ();
  58. }
  59.  
  60.  
  61. }
  62.  
  63.  
  64. void updatelife () {
  65. for (byte i = 0; i < NUM_COLS; i++) {
  66.     for (byte j = 0; j < NUM_ROWS; j++) {
  67.       byte state = grid[XY(i,j)];
  68.  
  69.       byte neighbors = countNeighbors(i, j);
  70.  
  71.       if (state == 0 && neighbors == 3) {
  72.         next[XY(i,j)] = 1;
  73.       } else if (state == 1 && (neighbors < 2 || neighbors > 3)) {
  74.         next[XY(i,j)] = 0;
  75.       } else {
  76.         next[XY(i,j)] = state;
  77.       }
  78.     }
  79.   }
  80.  
  81.  
  82.   for (int i = 0; i < NUM_LEDS; i++) {
  83.   grid [i] = next [i];
  84.   leds [i] = CHSV(grid [i] , 255, grid [i]*BRIGHTNESS);
  85.    
  86.     }
  87.  
  88. }
  89.  
  90.  
  91. uint16_t XY (uint8_t x, uint8_t y) { return (y * NUM_COLS + x);}   
  92.  
  93.  
  94. byte countNeighbors(byte x, byte y) {
  95.   int sum = 0;
  96.   for (int i = -1; i < 2; i++) {
  97.     for (int j = -1; j < 2; j++) {
  98.       int col = (x + i + NUM_COLS) % NUM_COLS;
  99.       int row = (y + j + NUM_ROWS) % NUM_ROWS;
  100.       sum +=  grid[XY(col,row)];
  101.     }
  102.   }
  103.   sum -= grid[XY(x,y)];
  104.   return sum;
  105. }
  106.  
  107.  void initarr () {
  108.   for (int i = 0; i < NUM_LEDS; i++) {
  109.       grid[i] = random8(2);
  110.    
  111.   }
  112. }
Add Comment
Please, Sign In to add comment