/t_backcompat/Timer.pm

http://github.com/PerlGameDev/SDL · Perl · 81 lines · 44 code · 8 blank · 29 comment · 11 complexity · 3f6a0ecb21aa8c410ef6b42e3d5a9cf1 MD5 · raw file

  1. #!/usr/bin/env perl
  2. #
  3. # Timer.pm
  4. #
  5. # Copyright (C) 2005 David J. Goehrig <dgoehrig@cpan.org>
  6. #
  7. # ------------------------------------------------------------------------------
  8. #
  9. # This library is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU Lesser General Public
  11. # License as published by the Free Software Foundation; either
  12. # version 2.1 of the License, or (at your option) any later version.
  13. #
  14. # This library is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. # Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public
  20. # License along with this library; if not, write to the Free Software
  21. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. #
  23. # ------------------------------------------------------------------------------
  24. #
  25. # Please feel free to send questions, suggestions or improvements to:
  26. #
  27. # David J. Goehrig
  28. # dgoehrig@cpan.org
  29. #
  30. package SDL::Timer;
  31. use strict;
  32. use warnings;
  33. use Carp;
  34. use SDL;
  35. sub new {
  36. my $proto = shift;
  37. my $class = ref($proto) || $proto;
  38. my $self = {};
  39. my $func = shift;
  40. my (%options) = @_;
  41. Carp::confess "SDL::Timer::new no delay specified\n"
  42. unless ( $options{-delay} );
  43. $$self{-delay} = $options{-delay} || $options{-d} || 0;
  44. $$self{-times} = $options{-times} || $options{-t} || 0;
  45. if ( $$self{-times} ) {
  46. $$self{-routine} = sub { &$func($self); $$self{-delay} if ( --$$self{-times} ) };
  47. } else {
  48. $$self{-routine} = sub { &$func; $$self{-delay} };
  49. }
  50. $$self{-timer} = SDL::NewTimer( $$self{-delay}, $$self{-routine} );
  51. Carp::confess "Could not create timer, ", SDL::get_error(), "\n"
  52. unless ( $self->{-timer} );
  53. bless $self, $class;
  54. return $self;
  55. }
  56. sub DESTROY {
  57. my $self = shift;
  58. SDL::RemoveTimer( $$self{-timer} ) if ( $$self{-timer} );
  59. $$self{-timer} = 0;
  60. }
  61. sub run {
  62. my ( $self, $delay, $times ) = @_;
  63. $$self{-delay} = $delay;
  64. $$self{-times} = $times;
  65. SDL::RemoveTimer( $$self{-timer} ) if ( $$self{-timer} );
  66. $$self{-timer} = SDL::AddTimer( $$self{-delay}, SDL::PerlTimerCallback, $$self{-routine} );
  67. }
  68. sub stop {
  69. my ($self) = @_;
  70. SDL::RemoveTimer( $$self{-timer} ) if ( $$self{-timer} );
  71. $$self{-timer} = 0;
  72. }
  73. 1;