summaryrefslogtreecommitdiffstats
path: root/lib/Bot/Games/Game/Role/CurrentPlayer.pm
blob: 2dbe524cdf40d10e4b4950498a7e9a485b2910ad (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package Bot::Games::Game::Role::CurrentPlayer;
use Bot::Games::OO::Game::Role;

requires 'players', 'num_players', 'add_player';

has current_player => (
    is         => 'rw',
    isa        => 'Str',
    predicate  => 'has_current_player',
    command    => 1,
);

command previous_player => sub {
    my $self = shift;
    return unless $self->has_current_player;
    return $self->players->[$self->current_player_index - 1];
};

command next_player => sub {
    my $self = shift;
    return unless $self->has_current_player;
    return $self->players->[($self->current_player_index + 1) % $self->num_players];
};

sub current_player_index {
    my $self = shift;
    for (0..($self->num_players - 1)) {
        return $_ if $self->current_player eq $self->players->[$_];
    }
    return 0;
}

sub maybe_add_player {
    my $self = shift;
    my ($player) = @_;
    if (!grep { $player eq $_ } $self->players) {
        if ($self->add_player($player)) {
            $self->current_player($player);
        }
    }
}

no Bot::Games::OO::Game::Role;

1;