// Gustav Sörnäs - gusso230 #include "grid.h" #include "lifeutil.h" #include #include #include /* * Print a representation of the grid. * Alive cells show as 'X', dead show as '-'. */ void printGrid(Grid &grid) { for (int y = 0; y < grid.numRows(); y++) { for (int x = 0; x < grid.numCols(); x++) { if (grid.get(y, x)) { std::cout << 'X'; } else { std::cout << '-'; } } std::cout << std::endl; } } /* * Return 1 if (x, y) is in bounds and alive, otherwise 0. */ int checkPoint(Grid &grid, int y, int x) { return grid.inBounds(y, x) && grid.get(y, x) ? 1 : 0; } /* * Simulate the grid one time step and update it in-place. */ void simulate(Grid &grid) { Grid prevGrid(grid); for (int y = 0; y < grid.numRows(); y++) { for (int x = 0; x < grid.numCols(); x++) { int numNeighbours = checkPoint(prevGrid, y-1, x-1) + checkPoint(prevGrid, y-1, x ) + checkPoint(prevGrid, y-1, x+1) + checkPoint(prevGrid, y , x-1) + checkPoint(prevGrid, y , x+1) + checkPoint(prevGrid, y+1, x-1) + checkPoint(prevGrid, y+1, x ) + checkPoint(prevGrid, y+1, x+1); if (numNeighbours < 2) { grid.set(y, x, false); } else if (numNeighbours == 2) { // Do nothing. } else if (numNeighbours == 3) { grid.set(y, x, true); } else { grid.set(y, x, false); } } } } int main() { Grid grid; std::string filepath; std::cout << "file: "; std::cin >> filepath; std::ifstream input; input.open(filepath); int h, w; input >> h >> w; grid.resize(h, w); for (int y = 0; y < grid.numRows(); y++) { std::string line; std::getline(input, line); for (int x = 0; x < grid.numCols(); x++) { grid.set(y, x, line[x] == 'X'); } } input.close(); char prompt; bool running = true; while (running && (std::cout << "[a]nimate, [t]ick, [q]uit: ") && std::cin >> prompt) { switch (prompt) { case 'a': while (true) { clearConsole(); std::cout << std::endl; printGrid(grid); pause(100); simulate(grid); } case 't': simulate(grid); printGrid(grid); break; case 'q': running = false; break; } } }