Heh. Gotta love AD&D auto-dicerollers. 4d6, all 1's are 2's, drop the lowest. *laughs*
There's a much better way of doing what you're doing.
sub roll_die
{
my ($sides, $min) = @_;
return int(rand($sides - $min + 1) + $min);
}
sub my_roller
{
my ($num_dice, $sides, $min_value, $num_to_drop) = @_;
$num_dice ||= 3;
$min_value ||= 1;
$num_to_drop ||= 0;
return () unless $num_dice >= 1;
return () unless $num_dice > $num_to_drop;
my @values =
sort { $a <=> $b }
map { roll_die($sides, $min_value) } 1 .. $num_dice;
return @values[$num_to_drop .. $#values];
}
my @values = my_roller(4, 6, 2, 1);
print "@values\n";
This code has been tested relatively thoroughly. You should be able to just drop the functions into your existing code, or run it separately as provided.
Improvements made over what you posted:
- I separated out the thing that actually does the rolling from the thing that does the collating of the values. This is important because you might want to change them separately.
- I also made a function to do the collating. This is important because you want to roll dice for reasons other than generating stats. For example, you can get a combat roll by my $roll = my_roller(1, 20); In other words, 1d20.
If you want an explanation of how the code works, please ask.
------
We are the carpenters and bricklayers of the Information Age.
The idea is a little like C++ templates, except not quite so brain-meltingly complicated. -- TheDamian, Exegesis 6
Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.