Module: MadderLib::Conditional::Likely::Phrase

Included in:
Phrase
Defined in:
lib/madderlib/conditional/likely.rb

Overview

Likely::Phrase

Introduces support for proportional selection from multiple Instructions in a given Phrase

This is a very fancy way of saying ‘weighted choices’. Using Phrase#alternately, multiple Instructions can be added to the same Phrase. Each one will either use the DEFAULT_WEIGHT, if not otherwise specified, or:

  • a numeric value

  • a Proc / lambda / block / closure which returns a numeric value

The weights for all Instructions are totalled prior to each execution of the Builder. A random weight is chosen, and that defines the Instruction to be used

See: Likely::Instruction

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(target) ⇒ Object

:nodoc:



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/madderlib/conditional/likely.rb', line 26

def self.included(target) #:nodoc:
	#	before each run, we need to prepare ourself
	target.add_prepare do |phrase, context|
		#	no point in likelihood when there's only one choice
		unless phrase.instructions.size < 2
			weights = []
			phrase.instructions.each do |instruction|
				#	put on a default weight if no other option
				while (tester = instruction.conditional_likely_tester).nil?
					instruction.likely(DEFAULT_WEIGHT)
				end

				weight = tester.to_i(context)
				raise Error, 'invalid weight for instruction : #{instruction.words}' unless weight
				weights << weight
			end

			#	easy distributions
			total = 0
			Range.new(0, weights.size - 1).each do |index|
				weight, instruction = weights[index], phrase.instructions[index]

				state = context.state(instruction)
				state[:likely_lower] = total
				state[:likely_upper] = (total += weight)
			end

			#	choose a random value
			state = context.state(phrase)
			state[:likely_total] = total
			state[:likely_count] = rand(total) # Range.new(0, total).rand_inclusive
		end
	end
end

Instance Method Details

#likely(*args, &block) ⇒ Object Also known as: weight, weighted, weighing, odds

Adds proportional logic to the current Instruction

See: Instruction#likely



66
67
68
# File 'lib/madderlib/conditional/likely.rb', line 66

def likely(*args, &block)
	self.instruction.likely *args, &block
end