Created
July 15, 2012 06:52
-
-
Save tamalw/3115577 to your computer and use it in GitHub Desktop.
Drop table calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Item | |
attr_accessor :name, :odds | |
def initialize(name, odds) | |
@name = name | |
@odds = odds | |
end | |
end | |
class Dice | |
def initialize(items) | |
@range = 10000 | |
i = 0 | |
# @items = items.map do |item| | |
# lower = i | |
# i += item.odds * @range | |
# upper = i | |
# { :item => item, :lower_bound => lower, :upper_bound => upper} | |
# end | |
@items = [] | |
for item in items do | |
lower = i | |
i += item.odds * @range | |
upper = i | |
@items << { :item => item, :lower_bound => lower, :upper_bound => upper} | |
end | |
end | |
def spin | |
spun = rand(@range) | |
# result = @items.select do |item| | |
# spun >= item[:lower_bound] && spun < item[:upper_bound] | |
# end | |
result = [] | |
for item in @items do | |
if spun >= item[:lower_bound] && spun < item[:upper_bound] | |
result << item | |
end | |
end | |
result.empty? ? nil : result.first[:item] | |
end | |
end | |
dice = Dice.new [ | |
Item.new("Gear", 0.25), | |
Item.new("Enemy", 0.15), | |
Item.new("Tree", 0.20), | |
Item.new("Shield", 0.01), | |
Item.new("Oil", 0.05), | |
Item.new("Gold", 0.005), | |
Item.new("Cone", 0.05) | |
] | |
# Now testing it | |
spins = [] | |
cycles = 100000 | |
cycles.times do | |
weee = dice.spin | |
spins << (weee.nil? ? "Nothing" : weee.name) | |
end | |
results = spins.group_by { |s| s } | |
results.each do |name, entries| | |
count = entries.count | |
puts "#{name}\t\t#{count}\t#{1.0*count/cycles*100.00}%" | |
end | |
# name count % | |
# ---- ---- ---- | |
# Enemy 14935 14.935% | |
# Nothing 28490 28.49% | |
# Cone 4948 4.948% | |
# Tree 19914 19.914% | |
# Shield 1068 1.068% | |
# Gear 25080 25.080000000000002% | |
# Oil 5079 5.079000000000001% | |
# Gold 486 0.486% |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment