1
0

card_timer.xx 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. struct card_timer
  2. {
  3. ev::dynamic_loop&m_loop;
  4. std::vector<ct_timer*> m_timers;
  5. std::vector<int> m_timers_free;
  6. card_timer(ev::dynamic_loop&loop)
  7. :m_loop(loop)
  8. {
  9. grow();
  10. }
  11. ~card_timer()
  12. {
  13. for(auto&i:m_timers)
  14. delete i;
  15. }
  16. void grow()
  17. {
  18. int on=m_timers.size();
  19. int n=on<<1;
  20. if(n==0)
  21. n=4;
  22. m_timers.resize(n);
  23. for(int i=on;i<n;i++)
  24. {
  25. m_timers[i]=new ct_timer();
  26. m_timers[i]->m_id=i;
  27. m_timers_free.push_back(i);
  28. }
  29. }
  30. void alloc_timer(int delay_ms,int ct,int type)
  31. {
  32. if(m_timers_free.empty())
  33. grow();
  34. int id=m_timers_free.back(); m_timers_free.pop_back();
  35. m_timers[id]->start<card_timer,&card_timer::on_timer>(m_loop,this,delay_ms,ct,type);
  36. }
  37. void free_timer(int ct,int type)
  38. {
  39. for(int i=0,len=m_timers.size();i<len;i++)
  40. {
  41. if(m_timers[i]->m_ct==ct && m_timers[i]->m_type==type)
  42. {
  43. m_timers[i]->stop();
  44. m_timers_free.push_back(i);
  45. break;
  46. }
  47. }
  48. }
  49. virtual void on_ct_timer(int ct,int type)=0;
  50. void on_timer(ev::timer&t,int)
  51. {
  52. ct_timer&tmp=*(ct_timer*)&t;
  53. on_ct_timer(tmp.m_ct,tmp.m_type);
  54. }
  55. };