Skip to content

Instantly share code, notes, and snippets.

@s992
Created February 21, 2014 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s992/9141872 to your computer and use it in GitHub Desktop.
Save s992/9141872 to your computer and use it in GitHub Desktop.
Dice Roller
import javax.swing.JOptionPane
// for: http://www.raymondcamden.com/index.cfm/2014/2/21/Friday-Puzzler-Rolling-the-die
class DiceRoller {
static Random random = new Random()
static void main( String[] args ) {
String roller = JOptionPane.&showInputDialog "Enter your roll:"
String message
if( !validateRoller( roller ) ) {
message = "Your roll was invalid. Please enter a properly formatted roll."
JOptionPane.showMessageDialog( null, message, "Error!", 2 )
main()
} else {
Map rolls = roll( roller );
message = """Total: ${rolls.final}
Individual rolls: ${rolls.rolls.join(', ')}"""
JOptionPane.showMessageDialog( null, message, "Roll Results", 1 )
}
}
static Map roll( String roller ) {
Map rolls = [ final: 0, rolls: [] ]
ArrayList params = roller.split(/d|\+|-/).collect { Integer.parseInt( it ) }
Integer count = params[ 0 ]
Integer sides = params [ 1 ]
Integer modifier = params[ 2 ] ?: 0;
if( modifier != 0 ) {
modifier = roller.contains("-") ? -modifier : modifier
}
(1..count).each {
Integer thisRoll = actualRoll( sides )
rolls.rolls << thisRoll
rolls.final += thisRoll
}
rolls.final += modifier
rolls
}
private static Integer actualRoll( Integer sides ) {
random.nextInt( sides ) + 1
}
private static Boolean validateRoller( String roller ) {
Integer rollerSize = roller.split(/d|\+|-/).size()
rollerSize > 1 && rollerSize <= 3
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment