Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Basic idea

  • Loading branch information...
commit 9fec5944148277313e4d93cbe176178982b4a5bd 1 parent 1455f0d
@jtpalmer authored
Showing with 123 additions and 1 deletion.
  1. +64 −1 lib/Games/Joypad.pm
  2. +22 −0 lib/Games/Joypad/Event.pm
  3. +37 −0 t/01-basic.t
View
65 lib/Games/Joypad.pm
@@ -1,8 +1,71 @@
package Games::Joypad;
use strict;
use warnings;
+use Games::Joypad::Event;
-# ABSTRACT: Undocumented module
+use parent qw(Exporter);
+
+# ABSTRACT: Abstract joypad
+
+use constant {
+ NEUTRAL => 0,
+ UP => 1,
+ DOWN => 2,
+ LEFT => 5,
+ RIGHT => 6,
+};
+
+our @EXPORT_OK = qw(
+ NEUTRAL
+ NORTH
+ SOUTH
+ WEST
+ EAST
+);
+
+our %EXPORT_TAGS = ( all => [qw( NEUTRAL NORTH SOUTH WEST EAST )], );
+
+sub new {
+ my ( $class, %params ) = @_;
+
+ $class = ref $class if ref $class;
+
+ my $self = {
+ handlers => [],
+ pressed => {},
+ stack => [],
+ direction => NEUTRAL,
+ };
+
+ return bless $self, $class;
+}
+
+sub add_event_handler {
+ my ( $self, $handler ) = @_;
+
+ push @{ $self->{handlers} }, $handler;
+}
+
+sub direction {
+ my $self = shift;
+
+ if (@_) {
+ $self->{direction} = $_[0];
+
+ my $event = Games::Joypad::Event->new(direction => $_[0]);
+ $self->_publish_event($event);
+ }
+
+ return $self->{direction};
+}
+
+sub _publish_event {
+ my ( $self, $event ) = @_;
+
+ for my $handler ( @{ $self->{handlers} }) {
+ $handler->($event);
+ }
+}
1;
View
22 lib/Games/Joypad/Event.pm
@@ -0,0 +1,22 @@
+package Games::Joypad::Event;
+use strict;
+use warnings;
+
+# ABSTRACT: Joypad event
+
+sub new {
+ my $class = shift;
+
+ $class = ref $class if ref $class;
+
+ my $self = {@_};
+
+ return bless $self, $class;
+}
+
+sub direction {
+ return $_[0]->{direction};
+}
+
+1;
+
View
37 t/01-basic.t
@@ -0,0 +1,37 @@
+use strict;
+use warnings;
+use Test::More;
+use Games::Joypad;
+
+my $joypad = Games::Joypad->new();
+
+my $direction;
+
+$joypad->add_event_handler(
+ sub {
+ my ($event) = @_;
+
+ isa_ok($event, 'Games::Joypad::Event');
+
+ $direction = $event->direction();
+ }
+);
+
+$direction = undef;
+$joypad->direction( Games::Joypad::UP );
+is( $direction, Games::Joypad::UP );
+
+$direction = undef;
+$joypad->direction( Games::Joypad::DOWN );
+is( $direction, Games::Joypad::DOWN );
+
+$direction = undef;
+$joypad->direction( Games::Joypad::LEFT );
+is( $direction, Games::Joypad::LEFT );
+
+$direction = undef;
+$joypad->direction( Games::Joypad::RIGHT );
+is( $direction, Games::Joypad::RIGHT );
+
+done_testing();
+
Please sign in to comment.
Something went wrong with that request. Please try again.