Skip to content

Instantly share code, notes, and snippets.

@mobp
Created June 4, 2010 20:10
Show Gist options
  • Save mobp/425879 to your computer and use it in GitHub Desktop.
Save mobp/425879 to your computer and use it in GitHub Desktop.
game of life (torus)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include <unistd.h>
#define WIDTH 40
#define HEIGHT 20
int grid[HEIGHT][WIDTH];
int new_generation[HEIGHT][WIDTH];
int adjacency_cell(int y, int x)
{
if (y < 0)
y += HEIGHT;
if (x < 0)
x += WIDTH;
return (grid[y%HEIGHT][x%WIDTH]);
}
int live_or_die(int y, int x)
{
if (y >= HEIGHT) {
for (int y=0; y < HEIGHT; y++) {
for (int x=0; x < WIDTH; x++) {
grid[y][x] = new_generation[y][x];
}
}
return 0;
}
int state = adjacency_cell(y-1, x-1)
+ adjacency_cell(y-1, x)
+ adjacency_cell(y-1, x+1)
+ adjacency_cell(y, x-1)
+ adjacency_cell(y, x+1)
+ adjacency_cell(y+1, x-1)
+ adjacency_cell(y+1, x)
+ adjacency_cell(y+1, x+1);
switch (grid[y][x]) {
case 0:
if (state == 3)
new_generation[y][x] = 1;
else
new_generation[y][x] = 0;
break;
case 1:
if (state == 2 || state == 3)
new_generation[y][x] = 1;
else
new_generation[y][x] = 0;
break;
default:
break;
}
if (x >= WIDTH-1) {
x=0;
y++;
} else {
x++;
}
return live_or_die(y, x);
}
void screen_clear(void)
{
printf("\x1b[2J"); // 画面をクリア
fflush(stdout); // 標準出力のバッファをフラッシュ
printf("\x1b[1;1H"); // カーソルを左上隅に設定
}
void draw(void)
{
screen_clear();
for (int y=0; y < HEIGHT; y++) {
for (int x=0; x < WIDTH; x++) {
if (grid[y][x] == 0)
printf("□");
else
printf("■");
}
printf("\n");
}
printf("\n");
}
void grid_init()
{
srand(time(0));
for (int y=0;y < HEIGHT; y++) {
for (int x=0; x < WIDTH; x++) {
grid[y][x] = (int)(rand() * (1 - 0 + 1.0) / (1.0 + RAND_MAX));
}
}
}
int main(void)
{
grid_init();
draw();
getc(stdin);
for (;;) {
live_or_die(0, 0);
draw();
sleep(1);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment