Skip to content

Instantly share code, notes, and snippets.

@naezith
Last active September 1, 2022 13:18
Show Gist options
  • Save naezith/7f9798cae6b34a2b3ddaa21222f2ef46 to your computer and use it in GitHub Desktop.
Save naezith/7f9798cae6b34a2b3ddaa21222f2ef46 to your computer and use it in GitHub Desktop.
Spiral animation in Terminal, a bit dirty
#include <iostream>
#include <vector>
#include <string>
#include <unistd.h>
using namespace std;
const string CSI{"\x1b["};
const string CYAN{CSI + "36m"};
const string RED{CSI + "31m"};
const string GREEN{CSI + "32m"};
const string YELLOW{CSI + "33m"};
const string RESET{CSI + "30m"};
ostream &curpos(int row, int col) {
return cout << CSI << row << ';' << col << 'H';
}
typedef vector<vector<char>> field;
const char empty = ' ';
char filled = '@';
enum Direction {
RIGHT,
DOWN,
LEFT,
UP,
NONE
};
void init(field& f) {
for(unsigned i = 0; i < 25; ++i) {
f.emplace_back();
for(unsigned j = 0; j < 51; ++j)
f[i].push_back(empty);
}
}
bool fill(field& f, unsigned x, unsigned y, Direction c) {
if(y < f.size() && x < f[y].size()) {
if(f[y][x] == empty) {
f[y][x] = filled;
curpos(y+1, x+1);
string color = c == RIGHT ? RED :
c == DOWN ? GREEN :
c == LEFT ? YELLOW :
c == UP ? CYAN : RESET;
string color_bg = color;
color_bg.replace(color_bg.find("3"), 1, "4");
std::cout << color_bg << color << filled;
return true;
}
}
return false;
}
Direction c = RIGHT;
bool iterate(field& f, unsigned& x, unsigned& y, Direction& d, int style) {
if(style == 0) c = d;
else if(style == 1) c = (Direction) ((c + 1) % 4);
else if(style == 2) c = (Direction) (rand() % 4);
else if(style == 4) c = NONE;
if(fill(f, x, y, c)) return true;
if(d == RIGHT) {
if(fill(f, ++x, y, c)) return true;
--x;
d = DOWN;
}
else if(d == DOWN) {
if(fill(f, x, ++y, c)) return true;
--y;
d = LEFT;
}
else if(d == LEFT) {
if(fill(f, --x, y, c)) return true;
++x;
d = UP;
}
else if(d == UP) {
if(fill(f, x, --y, c)) return true;
++y;
d = RIGHT;
}
return false;
}
bool iterateMulti(field& f, unsigned& x, unsigned& y, Direction& d, int style) {
bool success = false;
for(int i = 0; i < 5; ++i)
if(iterate(f, x, y, d, style))
success = true;
if(style != 4) usleep(d == UP || d == DOWN ? 18000 : 1050);
else usleep(10000);
return success;
}
void run(int style) {
field f;
init(f);
Direction d = RIGHT;
unsigned x = 0, y = 0;
while(iterateMulti(f, x, y, d, style)) {}
}
int main() {
system("CLS");
run(2);
run(4);
run(1);
run(4);
run(0);
run(4);
curpos(27, 0);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment