Skip to content

Instantly share code, notes, and snippets.

@ccooke
Created September 22, 2013 21:58
Show Gist options
  • Save ccooke/6664274 to your computer and use it in GitHub Desktop.
Save ccooke/6664274 to your computer and use it in GitHub Desktop.
a partial dice expression grammar
module Dice
class Parser
attr_reader :terms
EXPRESSION = %r{^
(?<conditional> > | < | = | ){0}
(?<condition> \g<conditional> (?<condition_number> \d+ ) ){0}
(?<penetrating> !p ){0}
(?<componding> !! ){0}
(?<explode> ! ){0}
(?<decoration> \g<componding> | \g<penetrating> | \g<explode> ){0}
(?<die_size> \d+ | f ){0}
(?<keep_highest> kh | k ){0}
(?<keep_lowest> kl ){0}
(?<drop_highest> dh ){0}
(?<drop_lowest> dl | d ){0}
(?<keep> (\g<keep_lowest> | \g<keep_highest>) (?<keep_num> \d* ) ){0}
(?<drop> (\g<drop_highest> | \g<drop_lowest>) (?<drop_num> \d* ) ){0}
(?<reroll> r \g<condition>? ){0}
(?<die_modifier> \g<drop> | \g<keep> | \g<reroll> ){0}
(?<mathlink> \+ | - | \* | / ){0}
(?<die> (?<count> \d* ) d \g<die_size> \g<decoration>? \g<die_modifier>* ){0}
(?<constant> (?<constant_number> \d+ ) ){0}
(?<dice_string>
\g<die>
|
\g<constant>
){0}
\g<mathlink> \g<dice_string>
}ix
def initialize(string, options = {})
string.gsub! /\s+/, ''
unless string.start_with? '+'
string = '+' + string
end
@terms = []
while string != ""
@terms << string.match( EXPRESSION )
raise "Invalid dice expression at '#{string}'" if @terms.last.nil?
string = @terms.last.post_match
end
end
end
end
t = Dice::Parser.new ARGV[0].dup
require 'pp'
pp t.terms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment