From bec74c10056a67078af36205999c2af154792799 Mon Sep 17 00:00:00 2001 From: Raza Khan Date: Tue, 13 Jan 2026 19:12:49 +0530 Subject: [PATCH] Add living ASCII universe simulation --- CPP/livingAsciiUniverse.cpp | 108 ++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 CPP/livingAsciiUniverse.cpp diff --git a/CPP/livingAsciiUniverse.cpp b/CPP/livingAsciiUniverse.cpp new file mode 100644 index 0000000..39f09f4 --- /dev/null +++ b/CPP/livingAsciiUniverse.cpp @@ -0,0 +1,108 @@ +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +const int WIDTH = 80; +const int HEIGHT = 25; +const int MAX_AGE = 50; + +struct Star { + float x, y; + float vx, vy; + int age; + char symbol; +}; + +float randf(float min, float max) { + return min + static_cast(rand()) / RAND_MAX * (max - min); +} + +char brightness(int age) { + if (age < 10) return '.'; + if (age < 25) return '*'; + if (age < 40) return 'O'; + return '@'; +} + +int main() { + srand(static_cast(time(nullptr))); + vector stars; + + while (true) { + // Occasionally birth a new star + if (rand() % 3 == 0) { + stars.push_back({ + randf(0, WIDTH), + randf(0, HEIGHT), + randf(-0.05f, 0.05f), + randf(-0.05f, 0.05f), + 0, + '.' + }); + } + + // Clear screen + cout << "\033[2J\033[1;1H"; + + char space[HEIGHT][WIDTH]; + for (int i = 0; i < HEIGHT; i++) + for (int j = 0; j < WIDTH; j++) + space[i][j] = ' '; + + // Update stars + for (auto& s : stars) { + s.age++; + + // Simple gravity toward center + float cx = WIDTH / 2.0f; + float cy = HEIGHT / 2.0f; + + float dx = cx - s.x; + float dy = cy - s.y; + float dist = sqrt(dx * dx + dy * dy) + 0.01f; + + s.vx += dx / dist * 0.001f; + s.vy += dy / dist * 0.001f; + + s.x += s.vx; + s.y += s.vy; + + s.symbol = brightness(s.age); + + int ix = static_cast(s.x); + int iy = static_cast(s.y); + + if (ix >= 0 && ix < WIDTH && iy >= 0 && iy < HEIGHT) { + space[iy][ix] = s.symbol; + } + } + + // Remove dead stars + stars.erase( + remove_if(stars.begin(), stars.end(), + [](const Star& s) { return s.age > MAX_AGE; }), + stars.end() + ); + + // Render + for (int i = 0; i < HEIGHT; i++) { + for (int j = 0; j < WIDTH; j++) { + cout << space[i][j]; + } + cout << '\n'; + } + + cout << "\n🌌 Stars alive: " << stars.size() << endl; + cout << "Press Ctrl+C to exit" << endl; + + this_thread::sleep_for(chrono::milliseconds(80)); + } + + return 0; +}