Class: Tabletop::Die

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/tabletop/randomizers.rb

Direct Known Subclasses

Coin, FudgeDie

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Die

:sides must be greater then or equal to 1. By default it is 6. If :value is nil, then #roll is called.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/tabletop/randomizers.rb', line 9

def initialize(params={})

  if params[:sides].nil?
    @sides = 6
  else
    @sides = Integer(params[:sides])
    raise ArgumentError if @sides < 2
  end

  if params[:value].nil?
    roll
  else
    self.value = params[:value]
  end
end

Instance Attribute Details

#sidesObject (readonly)

Returns the value of attribute sides.



5
6
7
# File 'lib/tabletop/randomizers.rb', line 5

def sides
  @sides
end

#valueObject

Returns the value of attribute value.



5
6
7
# File 'lib/tabletop/randomizers.rb', line 5

def value
  @value
end

Class Method Details

.new_from_string(string) ⇒ Object

Raises:

  • (ArgumentError)


25
26
27
28
29
# File 'lib/tabletop/randomizers.rb', line 25

def self.new_from_string(string)
  raise ArgumentError unless string.respond_to?(:split)
  v, s = string.split('/')
  Die.new(sides: s.to_i, value: v.to_i)
end

Instance Method Details

#<=>(operand) ⇒ Object

Compares based on value of the die



49
50
51
# File 'lib/tabletop/randomizers.rb', line 49

def <=>(operand)
  @value <=> operand.to_int
end

#rollObject

Sets @value to a random number n, where 1 <= n <= @sides



32
33
34
# File 'lib/tabletop/randomizers.rb', line 32

def roll
  @value = rand(sides)+1
end

#to_intObject

Returns the die’s value



54
55
56
# File 'lib/tabletop/randomizers.rb', line 54

def to_int
  @value
end

#to_sObject

Returns a string in the form “[@value]/d@sides”



37
38
39
# File 'lib/tabletop/randomizers.rb', line 37

def to_s
  "[#{value}]/d#{sides}"
end