Callback_11.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #include <array>
  2. #include <vector>
  3. #include <map>
  4. #include <iostream>
  5. /*
  6. * https://stackoverflow.com/questions/2298242/callback-functions-in-c
  7. */
  8. enum e_event_code { ALL, EVENT_PRESSED, EVENT_LONG_PRESSED, LV_EVENT_RELEASED, REDRAW } ;
  9. class cEvents {
  10. public:
  11. void* user_data = nullptr;
  12. void* param = nullptr;
  13. cEvents* prev = nullptr;
  14. enum e_event_code code;
  15. uint16_t x;
  16. uint16_t y;
  17. cEvents* event_get_code(cEvents* e) {
  18. std::cout << e->code << std::endl;
  19. return this;
  20. }
  21. bool event_send_code(cEvents* e) {
  22. return true;
  23. }
  24. };
  25. void player_jump(cEvents &e) {
  26. std::cout << "player jump" << std::endl;
  27. std::cout << "x: " << e.x << " / y: " << e.y << std::endl;
  28. e.x = 36;
  29. e.y = 47;
  30. };
  31. void player_crouch(cEvents& e) {
  32. std::cout << "player crouch" << std::endl;
  33. std::cout << "x: " << e.x << " / y: " << e.y << std::endl;
  34. }
  35. class game_core : public cEvents
  36. {
  37. // empty eventhandler (default)
  38. static void emptyEvent(cEvents& e) {
  39. std::cout << "empty event handler" << std::endl;
  40. }
  41. public:
  42. std::array<void(*)(cEvents&), 5> actions;
  43. game_core() {
  44. actions.fill(&emptyEvent);
  45. }
  46. //
  47. void execEvent(cEvents& e)
  48. {
  49. if (actions[e.code]) actions[e.code](e);
  50. }
  51. // update keybind from menu
  52. void addEventCb(enum e_event_code key_id, void(*new_action)(cEvents &))
  53. {
  54. actions[key_id] = new_action;
  55. }
  56. };
  57. int main() {
  58. game_core gc;
  59. cEvents e;
  60. gc.addEventCb(REDRAW, &player_jump);
  61. gc.addEventCb(EVENT_PRESSED, &player_crouch);
  62. e.code = EVENT_PRESSED;
  63. e.x = 12;
  64. e.y = 24;
  65. gc.execEvent(e);
  66. e.code = REDRAW;
  67. e.x = 39;
  68. e.y = 41;
  69. gc.execEvent(e);
  70. e.code = ALL;
  71. e.x = 39;
  72. e.y = 41;
  73. gc.execEvent(e);
  74. return 1;
  75. }