Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Custom-faced Dice

by davido (Cardinal)
on Jan 03, 2004 at 07:59 UTC ( #318482=snippet: print w/replies, xml ) Need Help??
Description: There's nothing earth-shattering here; just a Perldoodle.

There are a lot of dice modules already on CPAN. This snippet isn't a replacement for those. It just offers a different twist. You can define the faces of the die. That allows for traditional six sided numeric-faced dice, or alphabet-faced dice, or even, magic-eight-ball style dice.

The object constructor (new) takes an array-ref (or an anonymous array) as its argument. That anon-array must enumerate the faces of the die.

The CPAN dice modules focus on simple numeric dice rolls, as well as "D&D notation". This package just focuses on custom dice faces.

See the examples below:

package Die;

use strict;
use warnings;

sub new {
    my ( $proto, $faces ) = @_;
    my $class = ref( $proto ) || $proto;
    my $self = {};
    unless ( defined( $faces ) && ref( $faces ) =~ m/ARRAY/ ) {
        die "Must initialize Die with an array ref of faces.\n";
        # Make copy of @$faces so that faces can't be 
        # corrupted from outside the package.
    $self->{Faces} = [@{$faces}];
    bless $self, $class;
    return $self;

sub roll {
    my $self = shift;
    return $self->{Faces}[ rand( @{ $self->{Faces} } ) ];

package main;
use strict;
use warnings;

my $six_sided   = Die->new( [1..6]     );
my $eight_sided = Die->new( [1..8]     );
my $alpha_faced = Die->new( ['A'..'Z'] );
my $eight_ball  = Die->new( [    "Yes",
                                "I'll never tell",
                                "Ask Again Later",
                                "Outlook positive",
                                "Don't bet on it",
                                "Of course"    
                            ] );

foreach ( $six_sided, $eight_sided, $alpha_faced, $eight_ball ) {
    print $_->roll(), "\n";
Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: snippet [id://318482]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2021-08-01 12:04 GMT
Find Nodes?
    Voting Booth?
    My primary motivation for participating at PerlMonks is: (Choices in context)

    Results (6 votes). Check out past polls.