Class: Dialogue::Speaker

Inherits:
Object
  • Object
show all
Defined in:
lib/sapling/dialogue.rb

Overview

Speaker holds the functionality for going through a dialogue tree.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tree, debug = false) ⇒ Speaker

Returns a new instance of Speaker.



39
40
41
42
# File 'lib/sapling/dialogue.rb', line 39

def initialize(tree, debug = false)
  @tree = tree
  @debug = debug
end

Instance Attribute Details

#debugObject (readonly)

Status of verbose/debug mode. True = on; false = off.



37
38
39
# File 'lib/sapling/dialogue.rb', line 37

def debug
  @debug
end

#treeObject (readonly)

The tree, an instance of Gardner::Plot



35
36
37
# File 'lib/sapling/dialogue.rb', line 35

def tree
  @tree
end

Instance Method Details

#conversationObject

Conversation handles navigating the tree, until the option to end is reached.



46
47
48
49
50
51
52
53
54
55
56
# File 'lib/sapling/dialogue.rb', line 46

def conversation
  Dialogue.display_trunk(@tree.trunk, @debug)

  next_branch = 1
  until next_branch.zero?
    next_branch = talk(@tree.branches[next_branch], next_branch)
  end

  puts "\n#{@tree.branches[0]['desc']}"
  exit
end

#get_response(branch) ⇒ Integer

Get a response for the displayed branch

Parameters:

  • branch (Hash)

    A branch data set

Returns:

  • (Integer)

    the next branch



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/sapling/dialogue.rb', line 82

def get_response(branch)
  valid_options = branch['options'].keys.join(', ')

  print "\n[#{valid_options}]> "
  STDOUT.flush
  response = STDIN.gets.chomp

  until valid_options.include?(response) || response.to_i.zero?
    print "[## Invalid options. Valid options are #{valid_options}," \
      "or 0 to exit.\n[#{valid_options}]> "
    response = STDIN.gets.chomp
  end

  response.to_i
end

#talk(branch, branch_no) ⇒ Integer

Talk displays a branch, the options, and prompts for a response.

Parameters:

  • branch (Hash)

    A branch data set

  • branch_no (Integer)

    The branch number

Returns:

  • (Integer)

    The number of the next branch



63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/sapling/dialogue.rb', line 63

def talk(branch, branch_no)
  return 0 if terminal?(branch)

  Dialogue.display_branch(branch, branch_no, @debug)

  response = get_response(branch)

  unless response.zero?
    puts "(Your choice: #{branch['options'][response].keys[0]})"
    response = branch['options'][response].values[0].to_i
  end

  response
end

#terminal?(branch) ⇒ Boolean

Check if a branch is terminal

Parameters:

  • branch (Hash)

    A branch data set

Returns:

  • (Boolean)

    true if the branch is terminal, false otherwise



102
103
104
105
106
107
108
109
# File 'lib/sapling/dialogue.rb', line 102

def terminal?(branch)
  if branch['options'].empty?
    puts "\n#{branch['desc']}\n\n"
    return true
  end

  false
end