nsnake
Classic snake game for the terminal
AnimationGameOfLife.cpp
1 #include <Display/Animations/AnimationGameOfLife.hpp>
2 #include <Engine/Graphics/Colors.hpp>
3 #include <Engine/Helpers/Utils.hpp>
4 
5 static ColorPair white;
6 static ColorPair yellow = Colors::pair("yellow", "default");
7 
8 AnimationGameOfLife::AnimationGameOfLife(Window* window):
9  Animation(window),
10  cells(NULL)
11 { }
12 AnimationGameOfLife::~AnimationGameOfLife()
13 {
14  SAFE_DELETE(cells);
15 }
16 void AnimationGameOfLife::load()
17 {
18  unsigned int width = window->getW();
19  unsigned int height = window->getH();
20 
21  cells = new Array2D<bool>(width, height);
22 
23  // TODO: define an initial pattern?
24  for (unsigned int i = 0; i < width; i++)
25  for (unsigned int j = 0; j < height; j++)
26  cells->set(i, j, Utils::Random::booleanWithChance(0.20));
27 
28  timer.start();
29 }
30 void AnimationGameOfLife::update()
31 {
32  // Updating only at the right time!
33  if (timer.delta_ms() < 200)
34  return;
35 
36  // Dont update the edges
37  for (unsigned int i = 1; i < (cells->width() - 1); i++)
38  {
39  for (unsigned int j = 1; j < (cells->height() - 1); j++)
40  {
41  // The neighbors, biatch!
42  // Suppose the cell is [x], the neighbors are numbered
43  // from 0 to 7 like this:
44  //
45  // [0][1][2]
46  // [3][X][4]
47  // [5][6][7]
48  //
49  bool n[8];
50 
51  n[0] = cells->at(i - 1, j - 1);
52  n[1] = cells->at(i , j - 1);
53  n[2] = cells->at(i + 1, j - 1);
54  n[3] = cells->at(i - 1, j );
55  n[4] = cells->at(i + 1, j );
56  n[5] = cells->at(i - 1, j + 1);
57  n[6] = cells->at(i , j + 1);
58  n[7] = cells->at(i + 1, j + 1);
59 
60  int alive = 0;
61  for (int x = 0; x < 8; x++)
62  if (n[x])
63  alive++;
64 
65  if (cells->at(i, j))
66  {
67  // Cell is currently alive!
68  if (alive < 2)
69  cells->set(i, j, false);
70 
71  else if (alive < 4)
72  cells->set(i, j, true);
73 
74  else
75  cells->set(i, j, false);
76  }
77  else
78  {
79  // Cell is currently dead!
80  if (alive == 3)
81  cells->set(i, j, true);
82  }
83  }
84  }
85 
86  timer.start();
87 }
88 void AnimationGameOfLife::draw()
89 {
90  for (unsigned int i = 0; i < (cells->width()); i++)
91  {
92  for (unsigned int j = 0; j < (cells->height()); j++)
93  {
94  int c = ' ';
95  ColorPair p = white;
96 
97  if (cells->at(i, j))
98  {
99  c = '#';
100  p = yellow;
101  }
102  window->printChar(c, i, j, p);
103  }
104  }
105 }
106