hwcurses.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include <chrono>
  2. #include <cstdio>
  3. #include <ctime>
  4. #include <functional>
  5. #include <iostream>
  6. #include <ncurses.h>
  7. #include <unistd.h>
  8. #include <thread>
  9. // dynamic, let's for loop hello
  10. /* let's add a timer
  11. function "subscribes" to a function that omits a signal whenever a second has pased
  12. */
  13. /*
  14. todo
  15. figure out namespaces, using, and auto
  16. formalize timer struct
  17. read about std function and std bind
  18. try to do with objects / classes instead
  19. centralize into event sender and subscriber
  20. */
  21. struct mysecondsdisplay {
  22. int intervalcount = 10;
  23. void myupdatedisplay() {
  24. intervalcount -= 1;
  25. mvprintw(intervalcount, intervalcount, "hello %d", intervalcount);
  26. refresh();
  27. if (intervalcount < 1) {
  28. intervalcount = 10;
  29. }
  30. }
  31. };
  32. //calls callbackfunc on specified interval based on accumulated deltatime
  33. class timer {
  34. public:
  35. std::function<void()> callbackfunc;
  36. timer(size_t interval_input, std::function<void()> callback): callbackfunc(callback), time_interval(interval_input){}
  37. //callbackfunc once enough time has accumulated
  38. void updatetime(double DeltaTime) {
  39. accumulator += DeltaTime;
  40. if (accumulator >= time_interval) {
  41. accumulator -= time_interval;
  42. callbackfunc();
  43. }
  44. }
  45. private:
  46. double accumulator = 0;
  47. size_t time_interval = 1; // only display every 1 seconds
  48. };
  49. int main() {
  50. initscr();
  51. nodelay(stdscr,FALSE);
  52. refresh();
  53. // printf("verification\n");
  54. auto starttime = std::chrono::system_clock::now(); // initial starttime
  55. mysecondsdisplay secdisp;
  56. timer clocktimer(1, [&]() { secdisp.myupdatedisplay();} );
  57. //calculate delta between current and previous time
  58. while (true) {
  59. auto currenttime = std::chrono::system_clock::now();
  60. std::chrono::duration<double> myDeltaTime = currenttime - starttime;
  61. double dtime = myDeltaTime.count();
  62. clocktimer.updatetime(dtime);
  63. starttime = currenttime;
  64. std::this_thread::sleep_for(std::chrono::milliseconds(250));
  65. }
  66. getch();
  67. endwin();
  68. return 0;
  69. }