timer.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // calls callbackfunc on specified interval based on accumulated deltatime
  2. #include "timer.hpp"
  3. #include <algorithm>
  4. #include <chrono>
  5. #include <cstddef>
  6. #include <memory>
  7. #include <ncurses.h>
  8. #include <string>
  9. #include <vector>
  10. // infinite timer
  11. timer::timer(std::string name_input, size_t interval_input,
  12. std::unique_ptr<timeraction> action_input)
  13. : time_interval(interval_input), name(name_input), is_infinite(true),
  14. action(std::move(action_input)) {}
  15. // limited timer
  16. timer::timer(std::string name, size_t interval_input, int triggeramount,
  17. std::unique_ptr<timeraction> action_input)
  18. : triggeramount(triggeramount), time_interval(interval_input), name(name),
  19. action(std::move(action_input)) {}
  20. // callbackfunc once enough time has accumulated
  21. void timer::updatetime(double DeltaTime) {
  22. accumulator += DeltaTime;
  23. if (!is_expired) {
  24. if (accumulator >= time_interval) {
  25. action->update(*this);
  26. accumulator -= time_interval;
  27. triggercounter++;
  28. if (!is_infinite && triggercounter >= triggeramount) {
  29. is_expired = true;
  30. }
  31. }
  32. }
  33. }
  34. void timermanager::addtimer(std::unique_ptr<timer> input_timer) {
  35. timers.push_back(std::move(input_timer));
  36. }
  37. void timermanager::updatetimers() {
  38. for (auto &mytimer : timers) {
  39. auto currenttime = std::chrono::steady_clock::now();
  40. std::chrono::duration<double> myDeltaTime = currenttime - prevtime;
  41. double dtime = myDeltaTime.count();
  42. mytimer->updatetime(dtime);
  43. prevtime = currenttime;
  44. mvprintw(12, 0, "updated timer %s", mytimer->name.c_str());
  45. }
  46. timers.erase(std::remove_if(timers.begin(), timers.end(),
  47. [](auto &timer) { return timer->is_expired; }),
  48. timers.end());
  49. // implement delete timers
  50. refresh();
  51. }
  52. timermanager::timermanager(): prevtime(std::chrono::steady_clock::now()){}
  53. swapaction::swapaction(std::vector<int> &input_vector): input_vector(input_vector){}
  54. void swapaction::update(const timer &input_timer){
  55. if (!iscomplete) {
  56. int temp = input_vector[it_i];
  57. input_vector[it_i] = input_vector[input_vector.size() -1 - it_i];
  58. input_vector[input_vector.size() - 1 - it_i] = temp;
  59. it_i++;
  60. if(it_i>=input_vector.size() / 2){iscomplete=true;}
  61. }
  62. }
  63. printaction::printaction(std::vector<balkjes> &input_vector): input_vector(input_vector) {}
  64. void printaction::update(const timer &input_timer) {
  65. if(!iscomplete) {
  66. // for each it_i add a balkje then eventually print it
  67. if (it_i>=10) {
  68. iscomplete=true;
  69. }
  70. }
  71. }