Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Ruby Dice Roller plus! (See related posts)

So you are happy with the original Ruby Dice roller, but wish you could combine dice rolls or add bonuses just like you might in D&D?

Well wish no more!

class Dicer
  attr_accessor :rolls, :total, :bonus

  def initialize
    @rolls = []
    @total = 0
    @bonus = 0
  end

  def +(bonus)
    if bonus.instance_of?(Fixnum)
      @bonus += bonus
      @total += bonus
    else
      @rolls += bonus.rolls
      @total += bonus.total
      @bonus += bonus.total
    end
    self
  end
end

class Fixnum

  def d(sides=2)
    out = Dicer.new{|h,k| h[k] = []}
    self.times {
      out.rolls << 1 + rand(sides)
    }
    out.total = out.rolls.inject{|sum,n| sum + n}
    out
  end

end



Usage:
>> d = Dicer.new
=> #<Dicer:0x1107f4c @rolls=[], @total=0, @bonus=0>
>> 3.d(6)
=> #<Dicer:0x1106d40 @rolls=[2, 3, 4], @total=9, @bonus=0>
>> 3.d(6)+1
=> #<Dicer:0x11056c0 @rolls=[3, 1, 1], @total=6, @bonus=1>
>> 3.d(6)+2+1.d(4)
=> #<Dicer:0x1103320 @rolls=[2, 5, 1, 3], @total=13, @bonus=5>

You need to create an account or log in to post comments to this site.


Click here to browse all 7718 code snippets

Related Posts