Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

D20 dice throw parser

by Luca Benini (Scribe)
on Dec 17, 2004 at 13:40 UTC ( [id://415624]=CUFP: print w/replies, xml ) Need Help??

This code snippet contains a bug free(R) expression allowing you to parse D20 notation dice, so you can parse strings like 3D6,3D6+4 and 3D6+4x1000 obtaining as result (for 3D6+4x1000):
$dtime = 3
$dface = 6
$addfact = 4
$mulfact = 1000
The snippet set also right default value is a field is missing, so you can use returned value directly for calculation
#!/usr/bin/perl -w use strict; my @sample=("3D6+","3D6","3D6+4","3D6+4x1000"); ##############################THE BIG, THE ONE my $rexp='^([1-9][0-9]*)[Dd]([1-9][0-9]*)(\+([1-9][0-9]*)(x([1-9][0-9] +*))?)?$'; my ($dtime,$dface,$foo,$addfact,$bar,$mulfact); foreach (@sample) { if (/$rexp/) { map{$_=0 if !defined($_)}($dtime,$dface,$foo,$addfact,$bar)=($ +1,$2,$3,$4,$5); $mulfact=(!defined($6))?1:$6; print "$_ is $dtime dices with $dface faces plus $addfact all +mult by $mulfact\n"; } }

Replies are listed 'Best First'.
Re: D20 dice throw parser
by thor (Priest) on Dec 17, 2004 at 13:53 UTC
    What about Games::Die::Dice?

    thor

    Feel the white light, the light within
    Be your own disciple, fan the sparks of will
    For all of us waiting, your kingdom will come

      It doesn't parse the xDIGIT* component. I've developed it for teasure generator, that require this features.
        What about this:
        use Game::Die::Dice; my $input = "1D4x10"; my ($pass_to_module, $mult) = split('x', $input); $mult = defined($mult) ? $mult : 1; my $dice = new Games::Die::Dice($pass_to_module); my $treasure -= $mult * $dice->roll();

        Alternatively, submit a patch to the maintainers of that module so that it accepts multipliers. Something to consider though: what about rolls like "1d4x10+10"? Your current approach probably doesn't handle this...

        thor

        Feel the white light, the light within
        Be your own disciple, fan the sparks of will
        For all of us waiting, your kingdom will come

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (2)
As of 2024-03-19 04:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found