Advertisement
Crafticus

Die Roller

Sep 3rd, 2014
402
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.55 KB | None | 0 0
  1. class Dice
  2.     attr_reader :die, :maxSum, :minSum
  3.  
  4.     def initialize(*args)
  5.         @die = args.dup.freeze
  6.         @values = Array.new(@die.size, 1)
  7.         @maxSum = @die.inject(:+)
  8.         @minSum = @die.size
  9.     end
  10.  
  11.     def roll
  12.         @die.map { |d| rand(d) + 1 }
  13.     end
  14.  
  15.     def roll_sum(num = 0)
  16.         t = roll.sort
  17.  
  18.         if (num > 0) then
  19.             t.slice!(0, num)
  20.         elsif (num < 0) then
  21.             t.slice!(num, num.abs)
  22.         end
  23.  
  24.         t.inject { |sum, x| sum + x }
  25.     end
  26.  
  27.     def roll_assoc
  28.         @die.map { |d| [rand(d) + 1, d] }
  29.     end
  30.  
  31.     def roll_sorted
  32.         roll_assoc.sort do |a, b|
  33.             if (a[0] == b[0]) then
  34.                 a[1] <=> b[1]
  35.             else
  36.                 a[0] <=> b[0]
  37.             end
  38.         end
  39.     end
  40.  
  41.     def incr
  42.         i = 0
  43.         while (i < @die.size) do
  44.             @values[i] += 1
  45.             if (@values[i] > @die[i]) then
  46.                 @values[i] = 1
  47.                 i += 1
  48.             else
  49.                 break
  50.             end
  51.         end
  52.     end
  53.  
  54.     def sum
  55.         @values.inject(:+)
  56.     end
  57.  
  58.     def min?
  59.         sum == @minSum
  60.     end
  61.  
  62.     def max?
  63.         sum == @maxSum
  64.     end
  65.  
  66.     def max
  67.         @values.max
  68.     end
  69.  
  70.     def min
  71.         @values.min
  72.     end
  73.  
  74.     def inspect
  75.         @values
  76.     end
  77. end
  78.  
  79. myDice = Dice.new(20, 20)
  80. maxRolls = Hash.new(0)
  81. minRolls = Hash.new(0)
  82. totalRolls = 0
  83.  
  84. loop do
  85.     maxRolls[myDice.max] += 1
  86.     minRolls[myDice.min] += 1
  87.  
  88.     totalRolls += 1
  89.  
  90.     myDice.incr
  91.     break if (myDice.min?)
  92. end
  93.  
  94. puts "#{totalRolls} total rolls"
  95.  
  96. difficulty = 17
  97. difficultyTotal = 0
  98.  
  99. maxRolls.each_pair do |roll, total|
  100.     printf("%2d: %4d (%.2f%%)\n", roll, total, total.fdiv(totalRolls) * 100)
  101.     difficultyTotal += total if roll >= difficulty
  102. end
  103.  
  104. printf("%.2f%% success vs (%d)\n", difficultyTotal.fdiv(totalRolls), difficulty)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement