// Gustav Sörnäs - gusso230 #include "grid.h" #include "lifeutil.h" #include #include #include /* * Ask for a file and read it, storing the initial state in `grid`. */ void askAndReadFile(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(); } /* * Print a representation of the grid. * Alive cells show as 'X', dead show as '-'. */ void printGrid(const 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 whether (x, y) is in bounds and alive. */ bool checkPoint(const 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 = 0; for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <= 1; dx++) { if ((dx != 0 || dy != 0) && checkPoint(prevGrid, y+dy, x+dx)) { numNeighbours++; } } } 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; askAndReadFile(grid); 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; } } }