Code archives/Algorithms/D&D Dice Roller

This code has been declared by its author to be Public Domain code.

Download source code

D&D Dice Roller by Chroma2008
My old D&D roots flared up while I was messing around with arrays today. Maybe I'll use this in the future.

Accepts any sided die input. Use is simple:

Print RollDice("3d6")
Print RollDice("1d6+2")
Print RollDice("1d20-3")

etc etc
SeedRnd MilliSecs()

Local dice$ = "1d20+3"

For i = 1 To 20
	Print "Rolling "+dice+": "++RollDice(dice) 
Next

End

Function RollDice:Int(die$)
	If Left$(die,1) = "d" Then die = "1" + die
	Local roll$[] = die.split("d")
	Local ppos = Instr(roll[1],"+")
	Local mpos = Instr(roll[1],"-")
	Local bonus%, total%
	If ppos > 0
		bonus = Int(Mid$(roll[1], ppos+1, roll[1].length-ppos))
		roll[1] = Left(roll[1], ppos-1)
	ElseIf mpos > 0
		bonus = Int(Mid$(roll[1], mpos, roll[1].length-mpos+1))
		roll[1] = Left(roll[1], mpos-1)
	EndIf
	For Local i% = 1 To Int(roll[0])
		total:+ Rand(Int(roll[1]))
	Next
	Return total + bonus
End Function

Comments

Ryudin2008
Very nice! I think all of us D&D guys have done this at some point.


slenkar2008
thanks, im always doing games that need dice rolls


slenkar2008
is there an easy way to see if the number is within certain values?


*2008
If you require a Blitz .bb version go to
http://www.blitzbasic.com/codearcs/codearcs.php?code=2124


Chroma2009
Well I guess this would do just as well...


Local attackRoll% = RollDice(1,20,3)     '1d20+3

Function RollDice%(rolls%, die%, bonus%)
	Local dieTotal%, i%
	For i = 1 to rolls
		dieTotal :+ Rand(die)
	Next
	Return dieTotal + bonus
End Function



Code Archives Forum