diff options
| author | Elizabeth Alexander Hunt <me@liz.coffee> | 2026-07-02 11:55:17 -0700 |
|---|---|---|
| committer | Elizabeth Alexander Hunt <me@liz.coffee> | 2026-07-02 11:55:17 -0700 |
| commit | 6bf4b90c90f15f4ab60833bddf5b5756d1a6b1f6 (patch) | |
| tree | ed97e39ec77c5231ffd2c394493e68d00ddac5a4 /Homework/cs3460/gameoflife/LifeSimulator.cpp | |
| download | misc-undergrad-main.tar.gz misc-undergrad-main.zip | |
Diffstat (limited to 'Homework/cs3460/gameoflife/LifeSimulator.cpp')
| -rw-r--r-- | Homework/cs3460/gameoflife/LifeSimulator.cpp | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/Homework/cs3460/gameoflife/LifeSimulator.cpp b/Homework/cs3460/gameoflife/LifeSimulator.cpp new file mode 100644 index 0000000..daa4d45 --- /dev/null +++ b/Homework/cs3460/gameoflife/LifeSimulator.cpp @@ -0,0 +1,69 @@ +#include "LifeSimulator.hpp" + +LifeSimulator::LifeSimulator(std::uint8_t sizeX, std::uint8_t sizeY) : + m_width(sizeX), m_height(sizeY), + m_curr_grid(sizeY, std::vector<bool>(sizeX, false)), + m_buff_grid(sizeY, std::vector<bool>(sizeX, false)) +{ +} + +std::uint8_t wrapAround(std::int16_t delta, std::uint8_t pos, std::uint8_t max) +{ + if (pos + delta > max) + return 0; + if (pos + delta < 0) + return max; + return static_cast<std::uint8_t>(delta + pos); +} + +std::uint8_t LifeSimulator::getNeighbors(std::uint8_t x, std::uint8_t y) const +{ + std::uint8_t neighbors = 0; + for (std::int16_t dy = -1; dy <= 1; dy++) + for (std::int16_t dx = -1; dx <= 1; dx++) + if (!(dx == 0 && dy == 0)) + { + std::uint8_t wrappedX = wrapAround(dx, x, m_width - 1); + std::uint8_t wrappedY = wrapAround(dy, y, m_height - 1); + if (getCell(wrappedX, wrappedY)) + neighbors++; + } + return neighbors; +} + +void LifeSimulator::insertPattern(const Pattern& pattern, std::uint8_t startX, std::uint8_t startY) +{ + for (std::uint8_t y = startY; y < std::min(getSizeY(), static_cast<std::uint8_t>(startY + pattern.getSizeY())); ++y) + for (std::uint8_t x = startX; x < std::min(getSizeX(), static_cast<std::uint8_t>(startX + pattern.getSizeX())); ++x) + m_curr_grid.at(y).at(x) = pattern.getCell(x - startX, y - startY); +} + +void LifeSimulator::update() +{ +#pragma omp parallel for + for (char y = 0; y < m_height; ++y) + for (std::uint8_t x = 0; x < m_width; ++x) + { + std::uint8_t neighbors = getNeighbors(x, y); + if (getCell(x, y)) + m_buff_grid.at(y).at(x) = (neighbors == 2 || neighbors == 3); + else + m_buff_grid.at(y).at(x) = (neighbors == 3); + } + m_buff_grid.swap(m_curr_grid); +} + +std::uint8_t LifeSimulator::getSizeX() const +{ + return m_width; +} + +std::uint8_t LifeSimulator::getSizeY() const +{ + return m_height; +} + +bool LifeSimulator::getCell(std::uint8_t x, std::uint8_t y) const +{ + return m_curr_grid.at(y).at(x); +} |
