Skip to content

Instantly share code, notes, and snippets.

@dennyabraham
Created March 28, 2019 13:43
Show Gist options
  • Save dennyabraham/172d3a94e41b11772e11203d90be84b3 to your computer and use it in GitHub Desktop.
Save dennyabraham/172d3a94e41b11772e11203d90be84b3 to your computer and use it in GitHub Desktop.
a quick dice roller
class Dice
attr_accessor :collection
def initialize(*collection)
@collection = collection
end
def +(other)
@collection.last + other
self
end
def -(other)
@collection.last - other
self
end
def *(other)
@collection.last * other
self
end
def &(other)
@collection.concat(other.collection)
self
end
def inspect
@collection.map(&:inspect).join("\n=====\n")
end
end
class Die
Result = Struct.new(:sum, :dice)
def initialize(denomination)
@denomination = denomination
@count = 1
@bonus = 0
@result = Result.new(@denomination)
end
def roll
@result.dice = @count.times.map do
rand(@denomination) + 1
end
@result.sum = @result.dice.sum + @bonus
end
def +(other)
@bonus = other
self
end
def -(other)
@bonus = other * -1
self
end
def *(other)
@count = other
self
end
def inspect
roll
">> #{@count}d#{@denomination} + #{@count}\n" +
"dice #{@result.dice.to_s} \n" +
"bonus: #{@bonus} \n" +
"total: #{@result.sum}"
end
end
def d(denomination)
Dice.new(Die.new(denomination))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment