Created
September 1, 2016 18:03
-
-
Save itarato/f0f3b12bd03a6a1babfa027d22fe75f4 to your computer and use it in GitHub Desktop.
Game of life
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <chrono> | |
#include <thread> | |
#include <cstdlib> | |
#include <ctime> | |
#include <cstring> | |
using namespace std; | |
#define W 120 | |
#define H 40 | |
#define WTIME 42000 | |
#define loop(a, b) for (int a = 0; a < (b); a++) | |
int m[H][W]; | |
int nmap[8][2] = {{1, -1}, {1, 0}, {1, 1}, {0, -1}, {0, 1}, {-1, -1}, {-1, 0}, {-1, 1}}; | |
int colors[6] = {103, 43, 105, 45, 101, 41}; | |
void print() { | |
loop(y, H) { | |
loop(x, W) { | |
if (m[y][x]) cout << "\033[" << colors[m[y][x] - 1] << "m \e[0m"; | |
else cout << ' '; | |
} | |
cout << endl; | |
} | |
} | |
void clr() { | |
loop(i, W * (H + 1)) cout << "\e[A"; | |
} | |
void step() { | |
int temp[H][W]; | |
loop(y, H) loop(x, W) { | |
int total = 0; | |
loop(n, 8) { | |
int ny = (y + nmap[n][0] + H) % H; | |
int nx = (x + nmap[n][1] + W) % W; | |
if (m[ny][nx] > 0) total++; | |
} | |
temp[y][x] = m[y][x] ? min(6, m[y][x] + 1) : 0; | |
if (m[y][x]) { | |
if (total < 2 || total > 3) temp[y][x] = 0; | |
} else if (total == 3) temp[y][x] = 1; | |
} | |
memcpy(m, temp, sizeof(m)); | |
} | |
int main() { | |
chrono::microseconds wait(WTIME); | |
srand(time(0)); | |
loop(y, H) loop(x, W) m[y][x] = rand() % 10 > 2 ? 1 : 0; | |
for (;;) { | |
clr(); | |
step(); | |
print(); | |
std::this_thread::sleep_for(wait); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment