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.

Revisions

  1. andrewmilson revised this gist Feb 24, 2016. No changes.
  2. andrewmilson revised this gist Feb 24, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion game-of-life.cc
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,5 @@
    #include <iostream>
    #include <string>
    #include <cstring>
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
  3. andrewmilson created this gist Feb 24, 2016.
    73 changes: 73 additions & 0 deletions game-of-life.cc
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,73 @@
    #include <iostream>
    #include <string>
    #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;
    }