Skip to content

Instantly share code, notes, and snippets.

@Benjamin-Davies
Last active April 1, 2019 22:21
Show Gist options
  • Select an option

  • Save Benjamin-Davies/8c37062b402060eec906ffb35421ddd8 to your computer and use it in GitHub Desktop.

Select an option

Save Benjamin-Davies/8c37062b402060eec906ffb35421ddd8 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <time.h>
#include <unistd.h>
int WIDTH = 80;
int HEIGHT = 40;
char getCell(char *buffer, int x, int y) {
if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT)
return 0;
return buffer[x + y * WIDTH];
}
void setCell(char *buffer, int x, int y, char n) {
if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT)
return;
buffer[x + y * WIDTH] = n;
}
void clear(char *buffer) {
int i;
for (i = 0; i < WIDTH*HEIGHT; i++)
buffer[i] = 0;
}
void randomize(char *buffer) {
int i;
for (i = 0; i < WIDTH*HEIGHT; i++)
buffer[i] = rand() & 1;
}
void step(char *last, char *current) {
int x, y, c, xoff, yoff;
char l, n;
for (y = 0; y < HEIGHT; y++) {
for (x = 0; x < WIDTH; x++) {
c = 0;
for (yoff = -1; yoff <= 1; yoff++) {
for (xoff = -1; xoff <= 1; xoff++) {
if (yoff != 0 || xoff != 0)
if (getCell(last, x + xoff, y + yoff))
c++;
}
}
l = getCell(last, x, y);
if (l)
n = (c >= 2 && c <= 3) & 1;
else
n = (c == 3) & 1;
setCell(current, x, y, n);
}
}
}
void display(char *last, char *current) {
int x, y;
char l, c, n;
printf("\033[2J\033[H");
for (y = 0; y < HEIGHT; y++) {
for (x = 0; x < WIDTH; x++) {
l = getCell(last, x, y);
c = getCell(current, x, y);
n = l << 1 | c;
switch (n) {
case 0:
printf(" ");
break;
case 1:
printf("\e[33mo");
break;
case 2:
printf("\e[31mX");
break;
case 3:
printf("\e[32mO");
break;
}
}
printf("\n");
}
}
int main() {
char *last, *current, *temp;
struct winsize w;
ioctl(0, TIOCGWINSZ, &w);
WIDTH = w.ws_col;
HEIGHT = w.ws_row - 1;
last = malloc(WIDTH * HEIGHT);
current = malloc(WIDTH * HEIGHT);
srand(time(NULL));
randomize(last);
for (;;) {
step(last, current);
display(last, current);
usleep(100000);
temp = last;
last = current;
current = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment