Last active
September 14, 2024 12:41
-
-
Save origedit/dc9af62f79eb56faf98dcee3c0ff4df9 to your computer and use it in GitHub Desktop.
Conway's game of life in ansi c
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
size_t width, height; | |
char *grid1, *grid2, *oldg, *newg; | |
unsigned seed; | |
void shuffle() | |
{ | |
size_t i, n; | |
n = width * height; | |
for(i=0; i<n; ++i) | |
{ | |
oldg[i] = seed & 1; | |
seed = (seed>>2) + (seed*771); | |
} | |
} | |
void update() | |
{ | |
size_t i, j, k; | |
for(i=0; i<height; ++i) | |
for(j=0; j<width; ++j) | |
{ | |
int const dx[] = {-1, 0, 1, -1, 1, -1, 0, 1}; | |
int const dy[] = {-1, -1, -1, 0, 0, 1, 1, 1}; | |
int n = 0; | |
for(k=0; k<8; ++k) | |
{ | |
size_t x = (j + dx[k]) % width; | |
size_t y = (i + dy[k]) % height; | |
if(oldg[x + y*width]) | |
++n; | |
} | |
if(oldg[j + i*width]) | |
{ | |
newg[j + i*width] = n == 2 || n == 3; | |
}else{ | |
newg[j + i*width] = n == 3; | |
} | |
} | |
} | |
void show() | |
{ | |
/* reset the cursor */ | |
#ifdef _WIN32 | |
system("clear"); | |
#else | |
fputs("\033[1;1H", stdout); | |
#endif | |
size_t i, j; | |
for(i=0; i<height; ++i) | |
{ | |
for(j=0; j<width; ++j) | |
{ | |
char c = newg[j + i*width] ? '#' : ' '; | |
putchar(c); | |
putchar(c); | |
} | |
putchar('\n'); | |
} | |
} | |
int main() | |
{ | |
width = 40; | |
height = 40; | |
grid1 = (char *)malloc(width * height); | |
if(!grid1) | |
return 1; | |
grid2 = (char *)malloc(width * height); | |
if(!grid2) | |
return 1; | |
oldg = grid1; | |
newg = grid2; | |
seed = 123456; | |
shuffle(); | |
puts( | |
"write q to quit\n" | |
"write r to restard the board\n" | |
"anything else to run\n" | |
); | |
for(;;) | |
switch(getchar()) | |
{ | |
case 'q': | |
free(grid1); | |
free(grid2); | |
return 0; | |
case 'r': | |
shuffle(); | |
break; | |
default: | |
update(); | |
show(); | |
oldg = newg; | |
newg = newg==grid1 ? grid2 : grid1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment