diff options
Diffstat (limited to 'lab1/src/life.cpp')
| -rw-r--r-- | lab1/src/life.cpp | 104 |
1 files changed, 104 insertions, 0 deletions
diff --git a/lab1/src/life.cpp b/lab1/src/life.cpp new file mode 100644 index 0000000..cf5c6c9 --- /dev/null +++ b/lab1/src/life.cpp @@ -0,0 +1,104 @@ +// Gustav Sörnäs - gusso230 + +#include "grid.h" +#include "lifeutil.h" + +#include <iostream> +#include <fstream> +#include <string> + +/* + * Print a representation of the grid. + * Alive cells show as 'X', dead show as '-'. + */ +void printGrid(Grid<bool> &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<bool> &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<bool> &grid) { + Grid<bool> 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<bool> 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; + } + } +} |
