Skip to content

Instantly share code, notes, and snippets.

@andrewmilson
Last active February 25, 2016 11:37
Show Gist options
  • Save andrewmilson/4a4edc81d5850bd40264 to your computer and use it in GitHub Desktop.
Save andrewmilson/4a4edc81d5850bd40264 to your computer and use it in GitHub Desktop.
A wrapping implementation Conway's Game of Life in C++
#include <iostream>
#include <cstring>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define HEIGHT 100
#define WIDTH 300
using namespace std;
void next(int env[WIDTH][HEIGHT]) {
int cpy[WIDTH][HEIGHT];
memcpy(cpy, env, WIDTH * HEIGHT * sizeof(int));
for(int i = 0; i < WIDTH; i++) {
for(int j = 0; j < HEIGHT; j++) {
int NORTH = (HEIGHT + j - 1) % HEIGHT;
int SOUTH = (HEIGHT + j + 1) % HEIGHT;
int EAST = (WIDTH + i + 1) % WIDTH;
int WEST = (WIDTH + i - 1) % WIDTH;
int neighbours =
env[EAST][NORTH] + env[WEST][NORTH] +
env[EAST][SOUTH] + env[WEST][SOUTH] +
env[i][SOUTH] + env[i][NORTH] +
env[EAST][j] + env[WEST][j];
if(neighbours < 2 || neighbours > 3)
cpy[i][j] = 0;
if(neighbours == 2)
cpy[i][j] = env[i][j];
if(neighbours == 3)
cpy[i][j] = 1;
}
}
memcpy(env, cpy, WIDTH * HEIGHT * sizeof(int));
}
void print(int env[WIDTH][HEIGHT]) {
for(int i = 0; i < HEIGHT; i++) {
for(int j = 0; j < WIDTH; j++) {
cout << (env[j][i] ? '#' : ' ');
}
cout << endl;
}
}
int main(){
int todo[WIDTH][HEIGHT];
srand(time(NULL));
for(int i = 0; i < WIDTH; i++) {
for (int j = 0; j < HEIGHT; j++) {
todo[i][j] = rand() % 2;
}
}
while (true) {
system("clear");
print(todo);
next(todo);
system("sleep .1");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment