-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdie.rb
36 lines (31 loc) · 797 Bytes
/
die.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Die
attr_reader :result
def initialize(sides)
unless [4, 6, 8, 10, 12, 20].include?(sides.to_i)
raise ArgumentError, "There is no such thing as a d#{sides}."
end
@sides = sides
end
def roll
@result = rand(1..@sides.to_i)
end
def to_s
# "[d#{@sides}] #{@result}"
"#{@result}/#{@sides}"
end
end
# TODO: Separate group rolling logic into "roll ndn" for calling manually, versus "roll_dice" for parsing from string
def roll_dice(string) # eg. "2d8+1d10"
groups = string.split("+")
dice = []
groups.each do |group_str|
num, sides = group_str.split("d")
num.to_i.times do
dice << Die.new(sides)
end
end
dice.map(&:roll) # Roll each die
sum = dice.map(&:result).inject(:+)
puts "#{sum} (#{dice.join(", ")})"
sum
end