From d3ae7832ab0beae40bac664a5ce9da21804d9916 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustav=20S=C3=B6rn=C3=A4s?= Date: Sun, 16 Aug 2020 03:49:43 +0200 Subject: initial lab1 --- lab1/src/life.cpp | 104 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 lab1/src/life.cpp (limited to 'lab1/src') 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 +#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; + } + } +} -- cgit v1.2.1