#include "life.h" using namespace std; const int life::subscript = ostream::xalloc(); life::life(const life_matrix_t initial_matrix) : g(0) { //Copy initial_matrix into matrix. for (size_t y = 1; y <= life_ymax; ++y) { for (size_t x = 1; x <= life_xmax; ++x) { matrix[y][x] = initial_matrix[y - 1][x - 1]; } //left and right edges matrix[y][0] = matrix[y][life_xmax + 1] = false; } //top and bottom edges for (size_t x = 0; x < life_xmax + 2; ++x) { matrix[0][x] = matrix[life_ymax + 1][x] = false; } } life& life::operator++() { _life_matrix_t newmatrix; //uninitialized variable for (size_t y = 1; y <= life_ymax; ++y) { for (size_t x = 1; x <= life_xmax; ++x) { //How many of the 8 neighbors of element x, y are on? int count = -matrix[y][x]; for (size_t y1 = y - 1; y1 <= y + 1; ++y1) { for (size_t x1 = x - 1; x1 <= x + 1; ++x1) { count += matrix[y1][x1]; } } // Laws of Survival, Birth, and Death newmatrix[y][x] = count==2 ? matrix[y][x] : count == 3; } } //Copy newmatrix into matrix. for (size_t y = 1; y <= life_ymax + 1; ++y) { for (size_t x = 1; x <= life_xmax + 1; ++x) { matrix[y][x] = newmatrix[y][x]; } } ++g; return *this; } ostream& operator<<(ostream& ost, const set_life_foreground& f) { ost.iword(life::subscript) = f.c; return ost; } ostream& operator<<(ostream& ost, const life& li) { const long character = ost.iword(life::subscript); const char full = character == 0 ? 'X' : character; for (size_t y = 1; y <= life_ymax; ++y) { for (size_t x = 1; x <= life_xmax; ++x) { cout << (li.matrix[y][x] ? full : '.'); } cout << "\n"; } return ost; }