Advertisement
avr39-ripe

consoleGraphKeyExample

Apr 26th, 2020
493
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. #include <iostream>
  2. #include <chrono>
  3. #include <thread>
  4. #include <conio.h>
  5.  
  6. int main()
  7. {
  8.     const char* CSI{ "\033[" };
  9.     const char* hideCursor{ "?25l" };
  10.     const char* clearScreen{ "2J" };
  11.  
  12.     const int minX{ 1 };
  13.     const int minY{ 1 };
  14.     const int maxX{ 79 };
  15.     const int maxY{ 24 };
  16.  
  17.     const int kbDeltaY{ 1 };
  18.     std::cout << CSI << hideCursor;
  19.     for (int x{ 1 }, y{ 1 }, dx = { 1 }, dy = { 1 }; ; x += dx, y += dy)
  20.     {
  21.         if (_kbhit())
  22.         {
  23.             auto key{ _getch() };
  24.             if (key == 'w' or key == 'W') { dy = dy <= 0 ? dy : -dy; };
  25.             if (key == 's' or key == 'S') { dy = dy >= 0 ? dy : -dy; };
  26.             if (key == 'a' or key == 'A') { dx = dx <= 0 ? dx : -dx; };
  27.             if (key == 'd' or key == 'S') { dx = dx >= 0 ? dx : -dx; };
  28.         }
  29.  
  30.         if (y > maxY or y < minY) { dy = dy * (-1); y += dy; } // check vertical limits
  31.         if (x > maxX or x < minX) { dx = dx * (-1); x += dx; } // check horizontal limits
  32.  
  33.         std::cout << CSI << clearScreen << '\n'; // clear screan before draw each frame
  34.  
  35.         // ANSI ESCAPE CONTROL SEQUENCE
  36.         // https://ru.wikipedia.org/wiki/%D0%A3%D0%BF%D1%80%D0%B0%D0%B2%D0%BB%D1%8F%D1%8E%D1%89%D0%B8%D0%B5_%D0%BF%D0%BE%D1%81%D0%BB%D0%B5%D0%B4%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D1%81%D1%82%D0%B8_ANSI
  37.         // CSI y;xH - positioned output to y,x coordinates on console
  38.         // CSI NUMBERm - colored output to console
  39.         // CSI 0m - restore defaults after colord output to console
  40.         std::cout << CSI << y << ";" << x << "H" << CSI << 31 << "m" << " * " << CSI << "0m" << '\n';
  41.  
  42.         std::this_thread::sleep_for(std::chrono::milliseconds(100)); // some delay between frames
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement