Skip to content

Instantly share code, notes, and snippets.

@fliiiix
Created October 20, 2014 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fliiiix/c04347d6b1b5f353c6e6 to your computer and use it in GitHub Desktop.
Save fliiiix/c04347d6b1b5f353c6e6 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <random>
#include <array>
#include <unistd.h>
class CGame
{
public:
CGame()
{
InitBoard();
}
~CGame()
{
}
void Step(const int stepCounter = 1)
{
for (int i = 0; i < stepCounter; ++i)
{
DoStep();
PrintBoard();
}
}
protected:
void InitBoard()
{
srand(time(NULL));
for(int y = 0; y < m_board_size_y; y++)
{
for(int x = 0; x < m_board_size_x; x++)
{
m_Board[y][x] = GetRandom();
}
}
}
void DoStep()
{
for(int y = 0; y < m_board_size_y; y++)
{
for(int x = 0; x < m_board_size_x; x++)
{
static const int livingCell = 1;
const int cell = m_Board[y][x];
const int neighbours = CountNeighbours(y, x);
int newCell = 0;
if(livingCell == cell)
{
if((2 == neighbours) || (3 == neighbours))
{
newCell = livingCell;
}
}
else
{
if(3 == neighbours)
{
newCell = livingCell;
}
}
tmp_Board[y][x] = newCell;
}
}
m_Board = tmp_Board;
}
void PrintBoard()
{
for(int y = 0; y < m_board_size_y; y++)
{
for(int x = 0; x < m_board_size_x; x++)
{
std::cout << m_Board[y][x];
}
std::cout << std::endl;
}
std::cout << std::endl;
}
int CountNeighbours(const int y, const int x)
{
int neighbours = 0;
neighbours += CountNeighboursOnLine(y, x, false);
if((y-1) >= 0)
{
neighbours += CountNeighboursOnLine(y-1, x);
}
if((y+1) <= m_board_size_y)
{
neighbours += CountNeighboursOnLine(y+1, x);
}
return neighbours;
}
private:
static const int m_board_size_x = 150;
static const int m_board_size_y = 40;
static constexpr double m_seed_population = 0.4; // represent a % value
std::array<std::array<int, m_board_size_x>, m_board_size_y> m_Board;
std::array<std::array<int, m_board_size_x>, m_board_size_y> tmp_Board;
int GetRandom()
{
std::random_device randomdevice;
std::mt19937 generate(randomdevice());
std::bernoulli_distribution distibution(m_seed_population);
return distibution(generate);
}
int CountNeighboursOnLine(const int y, const int x, const bool withSelf = true)
{
const int livingCell = 1;
int neighbours = 0;
if((x+1) < m_board_size_x)
{
if(livingCell == m_Board[y][x+1])
{
neighbours++;
}
}
if(withSelf)
{
if(livingCell == m_Board[y][x])
{
neighbours++;
}
}
if((x-1) >= 0)
{
if(livingCell == m_Board[y][x-1])
{
neighbours++;
}
}
return neighbours;
}
};
int main()
{
static const int iterations = 500;
static const int sleepTime = 100 * 2000;
CGame* game = new CGame();
for(int i = 0; i <= iterations; i++)
{
game->Step();
usleep(sleepTime);
system("clear");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment