Skip to content

Instantly share code, notes, and snippets.

@kareiva
Last active May 8, 2024 13:35
Show Gist options
  • Save kareiva/7ab6bd6ec5d699a0e4eb4d97c698c985 to your computer and use it in GitHub Desktop.
Save kareiva/7ab6bd6ec5d699a0e4eb4d97c698c985 to your computer and use it in GitHub Desktop.
Quick and dirty implementation of Conway's Game of Life in C
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include <unistd.h>
#include <string.h>
int main (void)
{
struct winsize w;
ioctl(0, TIOCGWINSZ, &w);
int cols = w.ws_col - 1;
int rows = (w.ws_row - 1) * 2;
int i, j;
float iteration = 0.9;
srand(time(NULL));
bool matrix[rows][cols];
bool matrix_next[rows][cols];
bool n[8];
int sum_neighbours;
for (i=0; i < rows; i++) {
for (j=0; j < cols; j++) {
matrix[i][j] = ! (rand() & 100);
}
}
// main loop
while(true) {
printf("1\e[1;1H\e[2J");
for (i=0; i < rows; i+=2) {
for (j=0; j < cols; j++) {
if (matrix[i][j] && matrix[i+1][j]) printf("█");
else if (matrix[i][j] && ! matrix[i+1][j]) printf("▀");
else if (! matrix[i][j] && matrix[i+1][j]) printf("▄");
else printf(" ");
}
printf("\n");
}
// conways loop
for (i=0; i < rows; i++) {
for (j=0; j < cols; j++) {
sum_neighbours = 0;
n[0] = matrix[i-1][j-1]; n[1] = matrix[i-1][j];
n[2] = matrix[i-1][j+1]; n[3] = matrix[i][j+1];
n[4] = matrix[i][j-1]; n[5] = matrix[i+1][j+1];
n[6] = matrix[i+1][j]; n[7] = matrix[i+1][j-1];
if (i == 0) { n[0] = n[1] = n[2] = false; }
if (i == (rows-1)) { n[5] = n[6] = n[7] = false; }
if (j == 0) { n[0] = n[4] = n[7] = false; }
if (j == (cols-1)) { n[2] = n[3] = n[5] = false; }
for (int k=0; k<8; k++) {
if (n[k]) { sum_neighbours++; }
}
if (matrix[i][j]) {
matrix_next[i][j] = ! (sum_neighbours < 2 || sum_neighbours > 3) ;
}
else {
matrix_next[i][j] = (sum_neighbours == 3);
}
}
}
memcpy(matrix,matrix_next,sizeof(bool)*cols*rows);
usleep(100000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment