in reply to two dice question

I just had a play and came up with this.
#!/usr/bin/perl use strict; use warnings; for (1..6){ print_dice($_); }; sub print_dice{ my $value = shift or die $!; my %diceHash = ( 1 => [0,2,0], 2 => [4,0,1], 3 => [4,2,1], 4 => [5,0,5], 5 => [5,2,5], 6 => [5,5,5] ); print "---------\n"; foreach my $face ($diceHash{$value}){ foreach my $line (@{$face}){ print '| '; my @map = split //, sprintf("%03b",$line); foreach my $dot (@map){ print $dot ? "#":" "," "; } print "|\n"; } } print "---------\n"; };
Output is:
--------- | | | # | | | --------- --------- | # | | | | # | --------- --------- | # | | # | | # | --------- --------- | # # | | | | # # | --------- --------- | # # | | # | | # # | --------- --------- | # # | | # # | | # # | ---------

Replies are listed 'Best First'.
Re^2: two dice question
by eric256 (Parson) on Jul 20, 2007 at 18:12 UTC

    I wanted to learn some Moose so here is an OO version.

    #!/usr/bin/perl use strict; { package Dice; use Moose; has sides => (is => 'rw', default => 6); has value => (is => 'ro'); my %diceHash = ( 1 => [0,2,0], 2 => [4,0,1], 3 => [4,2,1], 4 => [5,0,5], 5 => [5,2,5], 6 => [5,5,5] ); sub roll { my $self = shift; $self->{value} = int(rand() * $self->sides) + 1 ; return $self; } sub display { my $self = shift; my $out; $out .= "---------\n"; my $face = $diceHash{$self->value()}; foreach my $line (@{$face}){ $out .= '| '; my @map = split //, sprintf("%03b",$line); foreach my $dot (@map){ $out .= ($dot ? "#" : " ") . " "; } $out .= "|\n"; } $out .= "---------\n"; return $out; } } my $d6 = new Dice(); print $d6->roll()->display() for (1..10);

    ___________
    Eric Hodges