Class: GamesDice::Die

Inherits:
Object
  • Object
show all
Defined in:
lib/games_dice/die.rb

Overview

This class models the simplest, most-familiar kind of die.

An object of the class represents a basic die that rolls 1..#sides, with equal weighting for each value.

Examples:

Create a 6-sided die, and roll it

d = GamesDice::Die.new( 6 )
d.roll # => Integer in range 1..6
d.result # => same Integer value as just returned by d.roll

Create a 10-sided die, that rolls using a monkey-patch to SecureRandom

module SecureRandom
  def self.rand n
    random_number( n )
  end
end
d = GamesDice::Die.new( 10, SecureRandom )
d.roll # => (secure) Integer in range 1..10
d.result # => same Integer value as just returned by d.roll

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sides, prng = nil) ⇒ GamesDice::Die

Creates new instance of GamesDice::Die

Raises:

  • (ArgumentError)

26
27
28
29
30
31
32
# File 'lib/games_dice/die.rb', line 26

def initialize( sides, prng=nil )
  @sides = Integer(sides)
  raise ArgumentError, "sides value #{sides} is too low, it must be 1 or greater" if @sides < 1
  raise ArgumentError, "prng does not support the rand() method" if prng && ! prng.respond_to?(:rand)
  @prng = prng
  @result = nil
end

Instance Attribute Details

#mapsnil (readonly)

Rules for when to map return value of this die.


94
95
96
# File 'lib/games_dice/die.rb', line 94

def maps
  nil
end

#maxInteger (readonly)


51
52
53
# File 'lib/games_dice/die.rb', line 51

def max
  @sides
end

#minInteger (readonly)


45
46
47
# File 'lib/games_dice/die.rb', line 45

def min
  1
end

#prngObject (readonly)


41
42
43
# File 'lib/games_dice/die.rb', line 41

def prng
  @prng
end

#rerollsnil (readonly)

Rules for when to re-roll this die.


87
88
89
# File 'lib/games_dice/die.rb', line 87

def rerolls
  nil
end

#resultInteger (readonly)


38
39
40
# File 'lib/games_dice/die.rb', line 38

def result
  @result
end

#sidesInteger (readonly)


35
36
37
# File 'lib/games_dice/die.rb', line 35

def sides
  @sides
end

Instance Method Details

#all_valuesArray<Integer>


80
81
82
# File 'lib/games_dice/die.rb', line 80

def all_values
  (1..@sides).to_a
end

#each_value {|result| ... } ⇒ GamesDice::Die

Iterates through all possible results on die.

Yield Parameters:

  • result (Integer)

    A potential result from the die


74
75
76
77
# File 'lib/games_dice/die.rb', line 74

def each_value
  (1..@sides).each { |r| yield(r) }
  self
end

#probabilitiesGamesDice::Probabilities

Calculates probability distribution for this die.


57
58
59
# File 'lib/games_dice/die.rb', line 57

def probabilities
  @probabilities ||= GamesDice::Probabilities.for_fair_die( @sides )
end

#rollInteger

Simulates rolling the die


63
64
65
66
67
68
69
# File 'lib/games_dice/die.rb', line 63

def roll
  if @prng
    @result = @prng.rand(@sides) + 1
  else
    @result = rand(@sides) + 1
  end
end