Skip to content

Instantly share code, notes, and snippets.

@alepez
Last active December 12, 2018 10:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alepez/eceab9121d606c2ff2c69a6d46a37ada to your computer and use it in GitHub Desktop.
Save alepez/eceab9121d606c2ff2c69a6d46a37ada to your computer and use it in GitHub Desktop.
trooper.c
#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];
}
static char spaceship[] = " "
" "
" "
" XX XX "
" XX "
" XX "
" X X X X "
" X X "
" "
" X X "
" XX XX "
" XXXX "
" "
" XX "
" XX "
" "
" "
" "
" "
" ";
static char cloverleaf[] = " "
" "
" "
" "
" X X "
" XXX XXX "
" X X X "
" X X X X "
" XX X XX "
" "
" XX X XX "
" X X X X "
" X X X "
" XXX XXX "
" X X "
" "
" "
" "
" "
" ";
static char* states[] = {cloverleaf, spaceship};
void game(int w, int h, char* state) {
unsigned univ[h][w];
for_xy univ[y][x] = *(state++) != ' ';
unsigned cicles = 2;
while (--cicles) {
show(univ, w, h);
evolve(univ, w, h);
usleep(100000);
}
}
int main(int c, char** v) {
int stateId = c == 2 ? atoi(v[1]) : 0;
game(20, 20, states[stateId]);
}
#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_yx for_y for_x
#define w 18
#define h 22
void show(void* u) {
int(*univ)[w] = (int(*)[w])u;
printf("\033[H");
for_y {
for_x printf(univ[y][x] ? "\033[07m \033[m" : " ");
printf("\033[E");
}
fflush(stdout);
}
static char state[] =
" xxxxxxxx x x x x x x x "
" x x x xxxxxxxxxxxxxx x xxxx xxxx x xxxxx xxxxx xx xx x xx xx "
" xx x x x x x x x x xx xx x x x x x x xxxxxx x xx xx "
" ";
void game(char* state) {
int univ[h][w];
for_yx univ[y][x] = *(state++) != ' ';
show(univ);
}
int main(int argc, char** argv) {
(void)argc;
(void)argv;
game(state);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment