Class: Dice

Inherits:
Object
  • Object
show all
Defined in:
lib/easy_dice/dice.rb

Overview

Copyright © 2013 Adam Price (komidore64 at gmail dot com)

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see <www.gnu.org/licenses/>.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(count, sides = 1) ⇒ Dice

Returns a new instance of Dice.



21
22
23
# File 'lib/easy_dice/dice.rb', line 21

def initialize(count, sides = 1)
  @count, @sides = count, sides
end

Instance Attribute Details

#childObject

Returns the value of attribute child.



19
20
21
# File 'lib/easy_dice/dice.rb', line 19

def child
  @child
end

#countObject (readonly)

Returns the value of attribute count.



19
20
21
# File 'lib/easy_dice/dice.rb', line 19

def count
  @count
end

#parentObject

Returns the value of attribute parent.



19
20
21
# File 'lib/easy_dice/dice.rb', line 19

def parent
  @parent
end

#sidesObject (readonly)

Returns the value of attribute sides.



19
20
21
# File 'lib/easy_dice/dice.rb', line 19

def sides
  @sides
end

Instance Method Details

#+(n) ⇒ Object



31
32
33
34
35
36
# File 'lib/easy_dice/dice.rb', line 31

def +(n)
  n = Dice.new(n) if n.class == Fixnum
  n.parent = self
  bottom.child = n
  top
end

#maximumObject Also known as: max



44
45
46
47
48
# File 'lib/easy_dice/dice.rb', line 44

def maximum
  max = @sides > 1 ? @sides * @count : @count
  max += @child.maximum unless @child.nil?
  max
end

#minimumObject Also known as: min



38
39
40
41
42
# File 'lib/easy_dice/dice.rb', line 38

def minimum
  min = @count
  min += @child.minimum unless @child.nil?
  min
end

#rollObject



25
26
27
28
29
# File 'lib/easy_dice/dice.rb', line 25

def roll
  total = @count.times.inject(0) { |total, _| total += rand(@sides) + 1 }
  total += @child.roll unless @child.nil?
  total
end

#to_sObject



50
51
52
53
54
# File 'lib/easy_dice/dice.rb', line 50

def to_s
  str = @sides > 1 ? "#{@count}d#{@sides}" : "#{@count}"
  str << " + #{@child.to_s}" unless @child.nil?
  str
end