| 14 | using namespace af; |
| 15 | |
| 16 | int main(int, char**) { |
| 17 | try { |
| 18 | static const float h_kernel[] = {1, 1, 1, 1, 0, 1, 1, 1, 1}; |
| 19 | static const int reset = 500; |
| 20 | static const int game_w = 128, game_h = 128; |
| 21 | |
| 22 | af::info(); |
| 23 | |
| 24 | std::cout << "This example demonstrates the Conway's Game of Life " |
| 25 | "using ArrayFire" |
| 26 | << std::endl |
| 27 | << "There are 4 simple rules of Conways's Game of Life" |
| 28 | << std::endl |
| 29 | << "1. Any live cell with fewer than two live neighbours " |
| 30 | "dies, as if caused by under-population." |
| 31 | << std::endl |
| 32 | << "2. Any live cell with two or three live neighbours lives " |
| 33 | "on to the next generation." |
| 34 | << std::endl |
| 35 | << "3. Any live cell with more than three live neighbours " |
| 36 | "dies, as if by overcrowding." |
| 37 | << std::endl |
| 38 | << "4. Any dead cell with exactly three live neighbours " |
| 39 | "becomes a live cell, as if by reproduction." |
| 40 | << std::endl |
| 41 | << "Each white block in the visualization represents 1 alive " |
| 42 | "cell, black space represents dead cells" |
| 43 | << std::endl; |
| 44 | |
| 45 | af::Window myWindow(512, 512, "Conway's Game of Life using ArrayFire"); |
| 46 | |
| 47 | int frame_count = 0; |
| 48 | |
| 49 | // Initialize the kernel array just once |
| 50 | const af::array kernel(3, 3, h_kernel, afHost); |
| 51 | array state; |
| 52 | state = (af::randu(game_h, game_w, f32) > 0.5).as(f32); |
| 53 | |
| 54 | while (!myWindow.close()) { |
| 55 | myWindow.image(state); |
| 56 | frame_count++; |
| 57 | |
| 58 | // Generate a random starting state |
| 59 | if (frame_count % reset == 0) |
| 60 | state = (af::randu(game_h, game_w, f32) > 0.5).as(f32); |
| 61 | |
| 62 | // Convolve gets neighbors |
| 63 | af::array nHood = convolve(state, kernel); |
| 64 | |
| 65 | // Generate conditions for life |
| 66 | // state == 1 && nHood < 2 ->> state = 0 |
| 67 | // state == 1 && nHood > 3 ->> state = 0 |
| 68 | // else if state == 1 ->> state = 1 |
| 69 | // state == 0 && nHood == 3 ->> state = 1 |
| 70 | af::array C0 = (nHood == 2); |
| 71 | af::array C1 = (nHood == 3); |
| 72 | |
| 73 | // Update state |