package Dice; use A_Die; my $debug = 0; sub new{ my $class = shift; my $self = {}; $self->{NUM_DICE} = 0; $self->{DICE} = []; bless ($self, $class); return $self; } sub num_dice { my $self = shift; return $self->{NUM_DICE}; } sub dice { my $self = shift; return ( $self->{DICE} ); } sub add_die { my $self = shift; my $die = A_Die->new(); ${$self->dice}[$#{$self->dice} + 1] = $die; $self->{NUM_DICE}++; print "new die added: " . $die->info() . "\n" if $debug; return $die; } sub show_dice { my $self = shift; my $i; print "No dice\n" unless @{$self->dice}; for $i (0..$#{$self->dice}) { print ${$self->dice}[$i]->info() . "\n"; } } sub rem_die { my $self = shift; return -1 if @_ != 1; # should be oaoo arg my $arg = shift; my $die; my $i; for ($i=0;$i<=$#{$self->dice};$i++) { last if $arg == ${$self->dice}[$i]; } #assert: $i is the index of the array where die referenced by $arg is located or is 1 greater than $#dice $die = splice(@{$self->dice},$i,1); #should remove that element and return it $self->{NUM_DICE}--; if ($debug) { print ($die == $arg ? "die removed: \$die = $die\n" : "failed to remove die: \$arg = $arg\n"); } $die == $arg ? return $die : return -1; } sub roll_all { my $self = shift; for $i (0..$#{$self->dice}) { ${$self->dice}[$i]->roll(); } } sub toString{ my $self = shift; my $i; my $retstring; if (@{$self->dice} == 0) { $retstring = "No dice\n" } else { for $i (0..$#{$self->dice}) { $retstring = $retstring . ${$self->dice}[$i]->toString(); $retstring = $retstring. " " unless $i == $#{$self->dice}; } } return $retstring; } sub toTextArt{ my $self = shift; my $art; my $textrow; my $NUM_ROWS = 5; @dieFaces[1..6]=( ["/---\\", "| |", "| * |", "| |", "\\---/"], ["/---\\", "| *|", "| |", "|* |", "\\---/"], ["/---\\", "| *|", "| * |", "|* |", "\\---/"], ["/---\\", "|* *|", "| |", "|* *|", "\\---/"], ["/---\\", "|* *|", "| * |", "|* *|", "\\---/"], ["/---\\", "|* *|", "|* *|", "|* *|", "\\---/"] ); if (@{$self->dice} == 0) { $art = "/---\\\n" . "| |\n" . "| |\n" . "| |\n" . "\\---/\n"; } else { for $textrow (0..$NUM_ROWS) { for $die (0..$#{$self->dice}) { $art = $art . $dieFaces[${$self->dice}[$die]->value][$textrow]; } $art = $art . "\n"; } } return $art } 1;