Created
December 27, 2012 11:19
-
-
Save kotnik/4387520 to your computer and use it in GitHub Desktop.
Game of Life in C.
This file contains 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 <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#define for_x for (int x = 0; x < w; x++) | |
#define for_y for (int y = 0; y < h; y++) | |
#define for_xy for_x for_y | |
void show(void *u, int w, int h) | |
{ | |
int (*univ)[w] = u; | |
printf("\033[H"); | |
for_y { | |
for_x printf(univ[y][x] ? "\033[07m \033[m" : " "); | |
printf("\033[E"); | |
} | |
fflush(stdout); | |
} | |
void evolve(void *u, int w, int h) | |
{ | |
unsigned (*univ)[w] = u; | |
unsigned new[h][w]; | |
for_y for_x { | |
int n = 0; | |
for (int y1 = y - 1; y1 <= y + 1; y1++) | |
for (int x1 = x - 1; x1 <= x + 1; x1++) | |
if (univ[(y1 + h) % h][(x1 + w) % w]) | |
n++; | |
if (univ[y][x]) n--; | |
new[y][x] = (n == 3 || (n == 2 && univ[y][x])); | |
} | |
for_y for_x univ[y][x] = new[y][x]; | |
} | |
void game(int w, int h) | |
{ | |
unsigned univ[h][w]; | |
for_xy univ[y][x] = rand() < RAND_MAX / 10 ? 1 : 0; | |
while (1) { | |
show(univ, w, h); | |
evolve(univ, w, h); | |
usleep(200000); | |
} | |
} | |
int main(int c, char **v) | |
{ | |
int w = 0, h = 0; | |
if (c > 1) w = atoi(v[1]); | |
if (c > 2) h = atoi(v[2]); | |
if (w <= 0) w = 30; | |
if (h <= 0) h = 30; | |
game(w, h); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you very much for your code, this helps me a lot