Skip to content

Instantly share code, notes, and snippets.

@tonykero
Created July 29, 2017 16:56
Show Gist options
  • Save tonykero/285768f26dd3b37fc4663e66a505d527 to your computer and use it in GitHub Desktop.
Save tonykero/285768f26dd3b37fc4663e66a505d527 to your computer and use it in GitHub Desktop.
cursos position playground
#include <iostream>
#include <thread>
#include <atomic>
#include <chrono>
#include <string>
#include <array>
#if defined _WIN32
#include <windows.h>
#elif defined __linux__
#endif
void set_cursor_position(unsigned int x, unsigned int y)
{
#if defined _WIN32
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos = {x, y};
SetConsoleCursorPosition(hConsole, pos);
#elif defined __linux__
std::cout << "\033[" + std::to_string(y) + ";" + std::to_string(x) + "H";
#endif
}
char in = '\0';
bool processChar = false;
void render()
{
auto start = std::chrono::high_resolution_clock::now();
std::array<std::string, 20> board;
std::string left = " ", right = " ";
std::string str;
int y = 0;
while(true)
{
// render
set_cursor_position(0, 0);
str = left + "#" + right;
std::string output = "\0";
for(int k = 0; k < 20; k++)
{
if(k != y)
board[k] = " ";
else
board[k] = str;
output += board[k] + "\n";
}
std::cout << output << std::endl;
// process event
if(processChar)
{
if(in == 'q')
{
left.erase(left.begin());
right += ' ';
}
else if(in == 'd')
{
right.erase(right.begin());
left += ' ';
}
else if(in == 'z')
{
y--;
}
else if(in == 's')
{
y++;
}
processChar = false;
}
//y++;
y %= 20;
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> elapsed = end-start;
if( elapsed.count() < 2000 )
std::this_thread::sleep_for( std::chrono::duration<double, std::milli>(2000) - elapsed );
}
}
void processInputs()
{
while(true)
{
std::cin >> in;
processChar = true;
}
}
int main()
{
std::thread t1(render),
t2(processInputs);
t1.join();
t2.join();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment