Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions CPP/livingAsciiUniverse.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
#include <iostream>
#include <vector>
#include <chrono>
#include <thread>
#include <cmath>
#include <algorithm>
#include <cstdlib>

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<float>(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<unsigned>(time(nullptr)));
vector<Star> 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<int>(s.x);
int iy = static_cast<int>(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;
}