Home: Fun With Perl: Perl Golf:
D&D dice roll



dw.worker.bee
Novice

Sep 22, 2011, 2:49 PM


Views: 252493
D&D dice roll

Hello, I'm new to the forum and wasn't sure if this belonged in Golf or Throw Down the Gauntlet. (I'm sure you will let me know) <smile>

When I'm on a boring phone meeting these days I work on my PERL, I'm a beginner and would like to write awesome code. The below code works but is clumsy. I'm betting someone can show me how to do it without so many variables and if/then statements. Just the subroutine.

If you ever played D&D, this would provide a random number within a certain range.

#!/usr/bin/perl
use strict;


sub dieRoll {
my ($drInValue, $drOutValue);
my ($drMult, $drDie, $drOper, $drAddVal, $drHold);
$drInValue = $_[0];
($drHold, $drAddVal) = split(/[\+\-]/, $drInValue);
($drMult, $drDie) = split(/[dD]/, $drHold);
for ($drMult; $drMult >= 1; $drMult--) {
$drOutValue += int(rand()*$drDie) + 1;
}
if ($drInValue =~ /\+/) {
$drOutValue += $drAddVal;
}
if ($drInValue =~ /\-/) {
$drOutValue -= $drAddVal;
}

return $drOutValue;
}


#...begin
my $count=0;
for ($count = 5; $count >= 1; $count--) {
my $RollTheDice="4d10+5";
print "Rolling the dice: $RollTheDice: $count: " . &dieRoll($RollTheDice). "\n";
}


Rolling the dice: 4d10+5: 5: 34
Rolling the dice: 4d10+5: 4: 27
Rolling the dice: 4d10+5: 3: 19
Rolling the dice: 4d10+5: 2: 24
Rolling the dice: 4d10+5: 1: 28