#include <stdio.h>
#include <unistd.h>
#include <cstring>

#define PLAY_X 25
#define PLAY_Y 25

struct playfield
{
	bool buffer [PLAY_X][PLAY_Y];
};

void draw_field (playfield f)
{	
	printf("\033[H");

	char tempBuffer [2];
	tempBuffer[1] = 0;

	for (int y = 0; y < PLAY_Y; y++)
	{
		for (int x = 0; x < PLAY_X; x++)
		{
			tempBuffer[0] = f.buffer[x][y] + 34;
			printf(tempBuffer);
			printf(tempBuffer);
		}
		printf("\n");
	}
}

void update_fields(playfield& play1, playfield& play2)
{
	int sum = 0;

	for (int y = 1; y < (PLAY_Y - 1); y++)
	{
		for (int x = 1; x < (PLAY_X - 1); x++)
		{
			sum = 
			play1.buffer[x + 1][y] +
			play1.buffer[x - 1][y] +
			play1.buffer[x][y + 1] + 
 			play1.buffer[x][y - 1] +
			play1.buffer[x + 1][y + 1] +
			play1.buffer[x + 1][y - 1] +
			play1.buffer[x - 1][y + 1] +
			play1.buffer[x - 1][y - 1];

			if (((sum  < 2) || (sum > 3)) && (play1.buffer[x][y] == true))
				play2.buffer[x][y] = false;
			else if ((sum == 3) && (play1.buffer[x][y] == false))
				play2.buffer[x][y] = true;
			else
				play2.buffer[x][y] = play1.buffer[x][y];
		}
	}

	memcpy(play1.buffer, play2.buffer, sizeof(play2.buffer));
}

void empty_field(playfield& field)
{
	for (int x = 0; x < PLAY_X; x++)
 		for (int y = 0; y < PLAY_Y; y++)
			field.buffer[x][y] = 0;
}

void populate_field (playfield& field)
{

	empty_field(field);

	field.buffer[20][1] = true;
	field.buffer[22][2] = true;
	field.buffer[18][2] = true;
	field.buffer[22][4] = true;
	field.buffer[17][3] = true;
	field.buffer[17][4] = true;
	field.buffer[17][5] = true;
	field.buffer[18][5] = true;
	field.buffer[19][5] = true;
	field.buffer[20][5] = true;
	field.buffer[21][5] = true;
}	

int main()
{
	playfield a;
	playfield b;

	populate_field(a);
	empty_field(b);

while(1)
{
	draw_field(a);
	update_fields(a, b);
	usleep(500000);
}

return 0;
}
