Skip to content

Instantly share code, notes, and snippets.

@mparker17
Created July 19, 2012 01:36
Show Gist options
  • Save mparker17/3140193 to your computer and use it in GitHub Desktop.
Save mparker17/3140193 to your computer and use it in GitHub Desktop.
Dice rolling
#!/usr/bin/ruby
def roll(num = 1, sides = 6, bonus = 0)
# Rand returns a number between 1 and the argument.
return (rand(sides-1) + 1 + bonus) * num;
end
# Parse a string in the following forms:
# - 1d4+1 or 1d4-1
# - d4+1 or d4-1
# - +1 or -1
# - 1d4
# - d4
def parse_command(command = "")
# Split up the command.
prefix_parts = command.split(/d/)
suffix_parts = prefix_parts[1].split(/\+|-/)
# The number of dice.
num = prefix_parts[0].empty? ? 1 : prefix_parts[0].to_i
# The type of dice.
sides = suffix_parts[0].to_i
# Bonus.
bonus = suffix_parts[1].empty? ? 0 : suffix_parts[1].to_i
# Tell the user what we're doing so if they mistyped it, they're not
# confused.
$stdout.write(sprintf("Rolling %d x %d-sided dice with bonus %d.", num, sides, bonus))
return roll(num, sides, bonus)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment