Skip to content

Instantly share code, notes, and snippets.

@JNjenga
Created August 18, 2020 14:43
Show Gist options
  • Select an option

  • Save JNjenga/a6d42e7cb053ea72ec304d6d7e7f24b3 to your computer and use it in GitHub Desktop.

Select an option

Save JNjenga/a6d42e7cb053ea72ec304d6d7e7f24b3 to your computer and use it in GitHub Desktop.
John Conway's Game of life
#include <stdio.h>
#include <unistd.h>
#ifdef _WIN32
#define clear() printf("\e[1;1H\e[2J");
#else
#define clear() write(STDOUT_FILENO, "\e[1;1H\e[2J",12);
#endif
#define MAX 1000
int neighbours[MAX][MAX];
int grid[MAX][MAX];
int max_cols = 0 , max_rows = 0;
void init()
{
max_rows = 64;
max_cols = 38;
for(int i = 0; i < max_rows; i++)
{
for(int j = 0; j < max_cols; j++)
{
grid[i][j] = 0;
neighbours[i][j] = 0;
}
}
// Glider
grid[0][1] = 1;
grid[1][2] = 1;
grid[2][0] = 1;
grid[2][1] = 1;
grid[2][2] = 1;
// Acron
grid[19][16] = 1;
grid[20][16] = 1;
grid[20][14] = 1;
grid[2][2] = 1;
}
void print_grid(int arr[MAX][MAX])
{
printf("[\n");
for(int i = 0; i < max_rows; i++)
{
printf("{");
for(int j = 0; j < max_cols; j++)
{
if(arr[i][j] == 0)
printf("-, ");
else {
printf("#, ");
}
}
printf("},");
printf("\n");
}
printf("]\n");
}
void tick()
{
for(int i = 0; i < max_rows + 5; i++)
{
for(int j = 0; j < max_cols + 5; j++)
{
// Determine number of neighbors
int n = 0;
int x, y;
// Left corner
x = i-1; y = j-1;
if(!(x < 0 || y < 0))
{
if(grid[x][y] == 1)
n++;
}
// Right corner
x = i-1; y = j+1;
if(!(x < 0 || y < 0))
{
if(grid[x][y] == 1)
n++;
}
// Bottom right corner
x = i+1; y = j+1;
if(!(x < 0 || y < 0))
{
if(grid[x][y] == 1)
n++;
}
// Bottom left corner
x = i+1; y = j-1;
if(!(x < 0 || y < 0))
{
if(grid[x][y] == 1)
n++;
}
// Top
x = i-1; y = j;
if(!(x < 0 || y < 0))
{
if(grid[x][y] == 1)
n++;
}
// Bottom
x = i+1; y = j;
if(!(x < 0 || y < 0))
{
if(grid[x][y] == 1)
n++;
}
// Left
x = i; y = j-1;
if(!(x < 0 || y < 0))
{
if(grid[x][y] == 1)
n++;
}
// Right
x = i; y = j+1;
if(!(x < 0 || y < 0))
{
if(grid[x][y] == 1)
n++;
}
neighbours[i][j] = n;
// printf("Neighbours at grid['%d']['%d'] : %d \n", i, j, n);
}
}
for(int i = 0; i< max_rows; i++)
{
for(int j = 0; j< max_cols; j++)
{
int n = neighbours[i][j];
if(grid[i][j] == 1)
{
if(n < 2) // Soltitude :(
grid[i][j] = 0;
else if(n > 3) // Overpopulation :(
grid[i][j] = 0;
else if(n == 2 || n == 3) // Survive :|
continue;
}else {
if(n == 3) // Birth :)
grid[i][j] = 1;
}
}
}
}
int main()
{
init();
printf("%d %d", max_cols, max_rows);
while(getchar())
{
clear(); // Clear screen
printf("\n\n\tHi, This is a simulation of Conway's game of life\n"
"\tBelow is a grid '#' represents alive while '-' represents dead \n");
printf("\n\n\tPress Enter (Return) to simulate a tick !\n\n");
print_grid(grid);
tick();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment