CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



dw.worker.bee
Novice

Sep 22, 2011, 2:49 PM

Post #1 of 1 (89346 views)
D&D dice roll Can't Post

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

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives