AI-Termites
view release on metacpan or search on metacpan
lib/AI/Termites.pm view on Meta::CPAN
sub dim { shift->{dim} }
sub box { shift->{box} }
sub new_wood {
my $self = shift;
my $wood = { pos => $self->{box}->random_in_box,
taken => 0 };
}
sub new_termite {
my $self = shift;
my $termite = { pos => $self->{box}->random_in_box };
}
sub iterate {
my $self = shift;
$self->before_termites_move;
for my $term (@{$self->{termites}}) {
$self->termite_move($term);
}
$self->before_termites_action;
for my $term (@{$self->{termites}}) {
$self->termite_action($term);
}
$self->after_termites_action;
}
sub termite_move {
my ($self, $termite) = @_;
$termite->{pos} = $self->{box}->wrap( $termite->{pos} +
Math::Vector::Real->random_normal($self->{dim},
$self->{speed}));
}
sub before_termites_move {}
sub before_termites_action {}
sub after_termites_action {}
sub termite_action {
my ($self, $termite) = @_;
if (defined $termite->{wood_ix}) {
if ($self->termite_leave_wood_p($termite)) {
$self->termite_leave_wood($termite);
}
}
else {
my $wood_ix = $self->termite_take_wood_p($termite);
defined $wood_ix and $self->termite_take_wood($termite, $wood_ix);
}
}
sub termite_take_wood {
my ($self, $termite, $wood_ix) = @_;
my $wood = $self->{wood}[$wood_ix];
return if $wood->{taken};
$wood->{taken} = 1;
$self->{taken}++;
# print "taken: $self->{taken}\n";
defined $termite->{wood_ix} and die "termite is already carrying some wood";
$termite->{wood_ix} = $wood_ix;
}
sub termite_leave_wood {
my ($self, $termite) = @_;
my $wood_ix = delete $termite->{wood_ix} //
croak "termite can not leave wood because it is carrying nothing";
$self->{taken}--;
my $wood = $self->{wood}[$wood_ix];
$wood->{taken} = 0;
$wood->{pos}->set($termite->{pos});
}
1;
__END__
=head1 NAME
AI::Termites - Artificial termites simulation
=head1 SYNOPSIS
use AI::Termites;
my $termites = AI::Termites::VicinusOcurro->new(dim => 2,
n_wood => 1000,
n_termites => 100);
$termites->iterate for 0..10000;
=head1 DESCRIPTION
This module simulates a termites world based on the ideas described on
the book "Adventures in Modeling" by Vanessa Stevens Colella, Eric
Klopfer and Mitchel Resnick
(L<http://education.mit.edu/starlogo/adventures/>).
In this version, termites can move in a n-dimensional boxed space, and
are not limited to integer coordinates.
Also, the way they decide when to pick or leave wood are customizable,
allowing to investigate how changing the rules affects the emergent
behaviors.
The module implements several termite subspecies (subclasses):
=over 4
=item LoginquitasPostulo
This termites subspecie measures the distance to the nearest piece of
wood.
=item NemusNidor
This termite smells the wood.
=item PeractioBaro
( run in 0.528 second using v1.01-cache-2.11-cpan-0d23b851a93 )