Module: Lich::Stash

Defined in:
documented/stash.rb

Overview

Container management and item manipulation for script inventory and hand control.

Provides methods to stash items from hands, equip items into hands, find containers and items, and track bandolier weapons. Caches container and bandolier state to avoid redundant lookups.

Constant Summary collapse

HANDS =

Symbol array of valid hand names.

%i[right left].freeze
ITEM_CONFIRM_TRIES =
20
ITEM_CONFIRM_SLEEP =
0.1
OPEN_CONFIRM =

Pattern matching responses to open attempts.

Matches success ("You open", already open), failure ("You can't", "locked"), and permission errors ("You don't seem", "You need").

Examples:

"You open the bag." =~ OPEN_CONFIRM #=> 0
"That is locked." =~ OPEN_CONFIRM #=> 24

See Also:

/^You open|^That is already open|^It is already open|^You can't|^You don't seem|^You need|is locked/.freeze

Class Method Summary collapse

Class Method Details

.add_to_bag(bag, item) ⇒ Boolean

Drags an item into a bag using _drag, with special handling for bandolier weapons.

Sends _drag command and waits for the item to leave both hands or arrive in the bag. If the item dissolves into vapor (bandolier), records it and returns true. Retries for up to 2 seconds, polling every 0.1 seconds.

Parameters:

  • bag (GameObj, String) —

    the destination container name or GameObj

  • item (GameObj) —

    the item to move

Returns:

  • (Boolean) —

    true if the item was placed, false if the operation timed out

See Also:



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'documented/stash.rb', line 90

def self.add_to_bag(bag, item)
  bag = container(bag)
  try_or_fail(command: "_drag ##{item.id} ##{bag.id}") do |result|
    # Check for vapor message first (bandolier)
    if result.is_a?(String) && result =~ /As you drop .+ it dissolves into vapor\./
      @bandolier_weapon[item.name] = "unknown"
      return true
    end

    20.times {
      return true if @bandolier_weapon[item.name]
      return true if ![GameObj.right_hand, GameObj.left_hand].map(&:id).compact.include?(item.id) && @weapon_displayer.include?(bag.id)
      return true if (![GameObj.right_hand, GameObj.left_hand].map(&:id).compact.include?(item.id) && bag.contents.to_a.map(&:id).include?(item.id))
      return true if item.name =~ /^ethereal \w+$/ && ![GameObj.right_hand, GameObj.left_hand].map(&:id).compact.include?(item.id)
      sleep 0.1
    }
    return false
  end
end

.container(param) ⇒ GameObj

Gets a container and opens it if closed, caching it in @weapon_displayer.

Calls find_container, opens it if needed via look-in and open commands, and tracks the container id in @weapon_displayer to avoid re-checking on future calls.

Parameters:

  • param (GameObj, String) —

    container name or GameObj

Returns:

  • (GameObj) —

    the opened container

Raises:

  • (RuntimeError) —

    if the container cannot be found

See Also:



52
53
54
55
56
57
58
59
60
# File 'documented/stash.rb', line 52

def self.container(param)
  container_to_check = find_container(param)
  unless @weapon_displayer.include?(container_to_check.id)
    result = Lich::Util.issue_command("look in ##{container_to_check.id}", /In the .*$|That is closed\.|^You glance at/, silent: true, quiet: true) if container_to_check.contents.nil?
    fput "open ##{container_to_check.id}" if result.include?('That is closed.')
    @weapon_displayer.push(container_to_check.id) if GameObj.containers.find { |item| item[0] == container_to_check.id }.nil?
  end
  return container_to_check
end

.container_holding(item) ⇒ GameObj?

Returns the container Lich knows the item to be inside, from the looked-in registries or the inventory tree.

Returns:

  • (GameObj, nil) —

    the container Lich knows the item to be inside, from the looked-in registries or the inventory tree



633
634
635
636
637
638
639
640
# File 'documented/stash.rb', line 633

def self.container_holding(item)
  entry = GameObj.containers.find { |_id, items| items.to_a.any? { |obj| obj.id == item.id } }
  return GameObj.inv.to_a.find { |obj| obj.id == entry.first } || GameObj[entry.first] if entry

  snapshot = inventory(refresh: false)
  parent = snapshot && snapshot[item.id]&.parent_item
  parent && GameObj[parent.id]
end

.empty_hand?(hand) ⇒ Boolean

Parameters:

  • hand (Symbol) —

    :right or :left

Returns:

  • (Boolean)


621
622
623
624
# File 'documented/stash.rb', line 621

def self.empty_hand?(hand)
  obj = hand == :right ? GameObj.right_hand : GameObj.left_hand
  obj.nil? || obj.id.nil?
end

.equip_hands(left: false, right: false, both: false) ⇒ void

This method returns an undefined value.

Executes stashed restore actions for one or both hands.

Pops the most recent proc from $fill_left_hand_actions, $fill_right_hand_actions, or $fill_hands_actions and calls it to restore the item(s) that were in hand before the matching stash_hands call. When no hand is specified, prefers right hand if available, then left hand. Does nothing if no matching actions are queued.

Parameters:

  • left (Boolean) (defaults to: false) —

    restore the left hand (default false)

  • right (Boolean) (defaults to: false) —

    restore the right hand (default false)

  • both (Boolean) (defaults to: false) —

    restore both hands; overrides left and right (default false)

See Also:



721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
# File 'documented/stash.rb', line 721

def self.equip_hands(left: false, right: false, both: false)
  if both
    for action in $fill_hands_actions.pop
      action.call
    end
  elsif left
    for action in $fill_left_hand_actions.pop
      action.call
    end
  elsif right
    for action in $fill_right_hand_actions.pop
      action.call
    end
  else
    if $fill_right_hand_actions.length > 0
      for action in $fill_right_hand_actions.pop
        action.call
      end
    elsif $fill_left_hand_actions.length > 0
      for action in $fill_left_hand_actions.pop
        action.call
      end
    end
  end
end

.find_bandolier_bag(item) ⇒ String?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Finds the bandolier bag containing an item, using the mist indicator.

Issues "inventory containers" and searches each container for the item by looking for the line "Surrounded by some swirling mist is ". Caches the result in @bandolier_weapon. Returns nil (stored as "unknown") if not found in any container. Waits for round time before each command.

Parameters:

  • item (GameObj) —

    the item to find in a bandolier

Returns:

  • (String, nil) —

    the cached container id, or nil if the item is in no bandolier



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'documented/stash.rb', line 141

def self.find_bandolier_bag(item)
  # Return cached value if valid and item exists in inventory
  cached_id = @bandolier_weapon[item.name]
  return cached_id if cached_id && cached_id != "unknown" &&
                      GameObj.inv.any? { |inv_item| inv_item.id == cached_id }

  # Regex patterns for parsing
  look_in_regex = Regexp.union(
    /^I could not find what you were referring to./,
    /^Surrounded by some swirling mist is /,
    /^In the /,
    /contains (?:DOSE|TINCTURE)s of the following /,
    /There is nothing in there\./,
    /<exposeContainer/,
    /<dialogData/,
    /<container/,
    /you glance/,
    /That is closed\./
  )

  item_regex = %r{<a exist="(?<id>[^"]+)" noun="(?<noun>[^"]+)">(?<name>[^<]+)</a>}

  # Collect all containers from inventory
  waitrt?
  results = Lich::Util.issue_command("inventory containers", /^You are holding /, timeout: 3, silent: true, quiet: true)
  containers = results.flat_map { |line|
    line.scan(item_regex).map { |id, _noun, _name| GameObj[id] }
  }.compact

  # Find container with the item using mist indicator
  item_noun_regex = /\b#{Regexp.escape(item.noun)}\b/
  found_container = containers.find do |container|
    waitrt?
    results = Lich::Util.issue_command(
      "look in ##{container.id}",
      look_in_regex,
      timeout: 2,
      silent: true,
      quiet: true
    )

    results.any? { |line|
      line.include?("Surrounded by some swirling mist is") && line.match?(item_noun_regex)
    }
  end

  @bandolier_weapon[item.name] = found_container&.id || "unknown"
end

.find_container(param, loud_fail: true) ⇒ GameObj?

Finds a container in inventory matching a name pattern.

Searches inventory with substring matching and allows words to be non-adjacent ("vultite bag" matches "vultite leather sack"). Accepts GameObj or String.

Examples:

Lich::Stash.find_container("lootsack") #=> #<GameObj ...>
Lich::Stash.find_container("vultite bag") #=> matches "vultite leather bag"

Parameters:

  • param (GameObj, String) —

    a container name or GameObj with a name to match

  • loud_fail (Boolean) (defaults to: true) —

    raise RuntimeError if container not found (default true)

Returns:

  • (GameObj, nil) —

    the container, or nil if loud_fail is false and not found

Raises:

  • (RuntimeError) —

    when loud_fail is true and the container cannot be found



31
32
33
34
35
36
37
38
39
40
41
# File 'documented/stash.rb', line 31

def self.find_container(param, loud_fail: true)
  param = param.name if param.is_a?(GameObj) # (Lich::Gemstone::GameObj)
  found_container = GameObj.inv.find do |container|
    container.name =~ %r[#{param.strip}]i || container.name =~ %r[#{param.sub(' ', ' .*')}]i
  end
  if found_container.nil? && loud_fail
    fail "could not find Container[name: #{param}]"
  else
    return found_container
  end
end

.find_item(param, loud_fail: true) ⇒ GameObj?

Resolve an item reference to a GameObj without sending anything.

Parameters:

  • param (GameObj, Integer, String, Symbol) —

    a GameObj; an id; a ready-list slot (:weapon, :shield, ...); or a name matched the way find_container matches, case-insensitive and with words allowed to be non-adjacent ("vultite broadsword" matches "vultite hand-forged broadsword")

  • loud_fail (Boolean) (defaults to: true) —

    raise when nothing matches

Returns:

  • (GameObj, nil) —

    the best candidate from find_items for a name

Raises:

  • (RuntimeError) —

    when loud_fail and the item is missing



371
372
373
374
375
376
377
378
379
380
381
382
# File 'documented/stash.rb', line 371

def self.find_item(param, loud_fail: true)
  return param if param.is_a?(GameObj)

  found = case param
          when Integer then GameObj[param.to_s]
          when Symbol then find_ready_item(param)
          when String
            param =~ /\A\d+\z/ ? GameObj[param] : find_items(param).first
          end
  fail "could not find Item[#{param.inspect}]" if found.nil? && loud_fail
  found
end

.find_items(name) ⇒ Array<GameObj>

Every distinct item a name could mean, best first, without sending anything. Ordered by how specific the match is (whole name, then part of the name, then noun only) and then by where the item is (hands, ready list, worn, containers), which is the order the game itself resolves a bare noun in. Items with identical names are interchangeable and collapse to the first.

Parameters:

Returns:

  • (Array<GameObj>) —

    empty when nothing matches



393
394
395
396
397
398
399
400
# File 'documented/stash.rb', line 393

def self.find_items(name)
  ranked = known_items_ranked.select { |obj, _loc| name_matches?(obj, name) }
  ranked = inventory_matches(name).map { |obj| [obj, 4] } if ranked.empty?
  ranked.sort_by.with_index { |(obj, loc), i| [match_specificity(obj, name), loc, i] }
        .map(&:first)
        .uniq(&:id)
        .uniq(&:name)
end

.free_hand(hand) ⇒ void

This method returns an undefined value.

Free a hand for an item we are about to put there.

stash_hands is the public empty_hand/empty_right_hand API: it pushes a "put this back" action onto the process-wide $fill_*_hand_actions stacks that equip_hands / fill_hand pop. wield and hands displace an item on purpose and never restore it, so leaving an entry behind would corrupt the stack another script is using. Stash, then drop the entry we just added, leaving any pre-existing entries untouched.

Parameters:

  • hand (Symbol) —

    :right or :left



484
485
486
487
488
489
490
# File 'documented/stash.rb', line 484

def self.free_hand(hand)
  return if empty_hand?(hand)
  stack = hand == :right ? ($fill_right_hand_actions ||= []) : ($fill_left_hand_actions ||= [])
  depth = stack.length
  stash_hands(**{ hand => true })
  stack.pop while stack.length > depth
end

.hand_holding(item) ⇒ Symbol?

Returns :right or :left when the item is in that hand.

Returns:

  • (Symbol, nil) —

    :right or :left when the item is in that hand



460
461
462
463
464
465
466
# File 'documented/stash.rb', line 460

def self.hand_holding(item)
  id = item.is_a?(GameObj) ? item.id : item.to_s
  return nil if id.nil?
  return :right if GameObj.right_hand&.id == id
  return :left if GameObj.left_hand&.id == id
  nil
end

.hands(right: :keep, left: :keep) ⇒ Hash{Symbol => GameObj, nil}

Reconcile both hands to a wanted state without dropping anything.

Stash.hands(right: 'broadsword', left: :shield)   # wield both
Stash.hands(right: nil)                           # empty the right hand, leave left alone
Stash.hands(left: :keep, right: 'runestaff')

Each hand takes :keep (leave it, the default), nil (empty it), or any item reference find_item accepts. An item already in the other hand is swapped across rather than stashed and fetched.

Returns:

  • (Hash{Symbol => GameObj, nil}) —

    what each hand holds afterwards



564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
# File 'documented/stash.rb', line 564

def self.hands(right: :keep, left: :keep)
  wanted = { right: right, left: left }
  resolved = wanted.transform_values { |want| want == :keep || want.nil? ? want : find_item(want) }
  if resolved[:right].is_a?(GameObj) && resolved[:left].is_a?(GameObj) && resolved[:right].id == resolved[:left].id
    raise ArgumentError, "hands: #{resolved[:right].name} was asked for in both hands"
  end

  # A wanted item sitting in the hand the caller asked to keep can only be
  # moved by a swap, which would change that hand. Refuse before touching anything.
  HANDS.each do |hand|
    other = hand == :right ? :left : :right
    item = resolved[hand]
    next unless item.is_a?(GameObj) && wanted[other] == :keep && hand_holding(item) == other
    raise ArgumentError, "hands: #{item.name} is in the #{other} hand, which was asked to be kept"
  end

  # Both wanted items are present but in each other's hands: one swap.
  if resolved[:right].is_a?(GameObj) && resolved[:left].is_a?(GameObj) &&
     hand_holding(resolved[:right]) == :left && hand_holding(resolved[:left]) == :right
    waitrt?
    dothistimeout 'swap', 3, /^You don't have anything to swap!|^You swap/
  end

  # Empty first, so a wanted item can land in a freed hand. A hand asked to
  # be emptied that is holding the item wanted in the OTHER hand needs a
  # swap, not a stash: stashing would drag the wanted item into a container
  # only for the wield below to fetch it straight back out. If the other
  # hand is occupied by something unwanted, stash THAT and then swap, so
  # the item the caller asked for never goes into a container.
  HANDS.each do |hand|
    next unless resolved[hand].nil? && wanted.key?(hand) && !(wanted[hand] == :keep)
    next if empty_hand?(hand)
    other = hand == :right ? :left : :right
    other_item = resolved[other]
    if other_item.is_a?(GameObj) && hand_holding(other_item) == hand
      free_hand(other) unless empty_hand?(other)
      if empty_hand?(other)
        waitrt?
        dothistimeout 'swap', 3, /^You don't have anything to swap!|^You swap/
        next if empty_hand?(hand)
      end
    end
    free_hand(hand)
  end

  HANDS.each do |hand|
    item = resolved[hand]
    next unless item.is_a?(GameObj)
    wield(item, hand: hand)
  end

  { right: GameObj.right_hand&.id ? GameObj.right_hand : nil,
    left: GameObj.left_hand&.id ? GameObj.left_hand : nil }
end

.in_hand?(item) ⇒ Boolean

Returns:

  • (Boolean)


469
470
471
# File 'documented/stash.rb', line 469

def self.in_hand?(item)
  !hand_holding(item).nil?
end

.inventory(refresh: true) ⇒ Lich::Common::Inventory::Snapshot?

The full inventory tree, refreshed on request through the game's inventory manager. This is what knows about items in containers Lich has never looked in, and whether each container is closed right now.

Parameters:

  • refresh (Boolean) (defaults to: true) —

    ask the game for a fresh tree (one command)

Returns:



408
409
410
411
412
413
# File 'documented/stash.rb', line 408

def self.inventory(refresh: true)
  return nil unless defined?(Lich::Common::Inventory)
  refresh ? Lich::Common::Inventory.refresh : Lich::Common::Inventory.current
rescue StandardError
  nil
end

.open_container(id) ⇒ Boolean

Returns whether the container is open afterwards.

Parameters:

  • id (String) —

    container id

Returns:

  • (Boolean) —

    whether the container is open afterwards



452
453
454
455
456
457
# File 'documented/stash.rb', line 452

def self.open_container(id)
  waitrt?
  result = dothistimeout("open ##{id}", 3, OPEN_CONFIRM)
  return true if result =~ /^You open|already open/
  false
end

.open_path_to(item) ⇒ Boolean

Open every closed container between the item and the player, outermost first, confirming each. Locked containers are left alone.

Parameters:

  • item (GameObj)

Returns:

  • (Boolean) —

    false when a container on the way is locked or would not open



420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'documented/stash.rb', line 420

def self.open_path_to(item)
  snapshot = inventory(refresh: false) || inventory
  entry = snapshot && snapshot[item.id]
  return true if entry.nil? # Inventory does not know it; nothing to open

  chain = []
  parent = entry.parent_item
  while parent
    chain.unshift(parent)
    parent = parent.parent_item
  end
  chain.each do |container|
    next unless container.closed?
    return false if container.locked?
    return false unless open_container(container.id)
  end
  true
end

.stash_hands(right: false, left: false, both: false) ⇒ void

This method returns an undefined value.

Removes an item or items from hand(s) and stashes them, recording restore actions.

Removes items from one or both hands using remove/wear for worn items, or get for other locations. Consulted the ReadyList to decide whether to stow in a sheath or default stow container. Pushes a proc onto $fill_right_hand_actions, $fill_left_hand_actions, or $fill_hands_actions that will restore the item when equip_hands is called with the matching flag. Does nothing if the hand is already empty. Uses ReadyList and StowList for sheath and stow container configuration.

Parameters:

  • right (Boolean) (defaults to: false) —

    stash the right hand (default false)

  • left (Boolean) (defaults to: false) —

    stash the left hand (default false)

  • both (Boolean) (defaults to: false) —

    stash both hands; overrides right and left (default false)

See Also:



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'documented/stash.rb', line 204

def self.stash_hands(right: false, left: false, both: false)
  $fill_hands_actions ||= Array.new
  $fill_left_hand_actions ||= Array.new
  $fill_right_hand_actions ||= Array.new

  actions = Array.new
  right_hand = GameObj.right_hand
  left_hand = GameObj.left_hand

  # extending to use sheath / 2sheath wherever possible
  unless ReadyList.valid?
    ReadyList.check(silent: true, quiet: true)
  end
  # extending to use default stow container wherever possible
  unless StowList.valid?
    StowList.check(silent: true, quiet: true)
  end
  if ReadyList.sheath
    unless ReadyList.secondary_sheath
      sheath = second_sheath = ReadyList.sheath
    else
      sheath = ReadyList.sheath if ReadyList.sheath
      second_sheath = ReadyList.secondary_sheath if ReadyList.secondary_sheath
    end
  elsif ReadyList.secondary_sheath
    sheath = second_sheath = ReadyList.secondary_sheath
  else
    sheath = second_sheath = nil
  end
  # weaponsack for both hands
  if UserVars.weapon.is_a?(String) && UserVars.weaponsack.is_a?(String) && !UserVars.weapon.empty? && !UserVars.weaponsack.empty? && (right_hand.name =~ /#{Regexp.escape(UserVars.weapon.strip)}/i || right_hand.name =~ /#{Regexp.escape(UserVars.weapon).sub(' ', ' .*')}/i)
    weaponsack = nil unless (weaponsack = find_container(UserVars.weaponsack, loud_fail: false)).is_a?(GameObj) # (Lich::Gemstone::GameObj)
  end
  # lootsack for both hands
  if !UserVars.lootsack.is_a?(String) || UserVars.lootsack.empty?
    lootsack = nil
  else
    lootsack = nil unless (lootsack = find_container(UserVars.lootsack, loud_fail: false)).is_a?(GameObj) # (Lich::Gemstone::GameObj)
  end
  # finding another container if needed
  other_containers_var = nil
  other_containers = proc {
    results = Lich::Util.issue_command('inventory containers', /^(?:You are (?:carrying nothing|holding no containers) at this time|You are wearing)/, silent: true, quiet: true)
    other_containers_ids = results.to_s.scan(/exist=\\"(.*?)\\"/).flatten - [lootsack.id]
    other_containers_var = GameObj.inv.find_all { |obj| other_containers_ids.include?(obj.id) }
    other_containers_var
  }

  if (left || both) && left_hand.id
    waitrt?
    if (left_hand.noun =~ /shield|buckler|targe|heater|parma|aegis|scutum|greatshield|mantlet|pavis|arbalest|bow|crossbow|yumi|arbalest/) && @worn_items[left_hand.name] != false && Lich::Stash::wear_to_inv(left_hand)
      actions.unshift proc {
        fput "remove ##{left_hand.id}"
        20.times { break if GameObj.left_hand.id == left_hand.id || GameObj.right_hand.id == left_hand.id; sleep 0.1 }

        if GameObj.right_hand.id == left_hand.id
          dothistimeout 'swap', 3, /^You don't have anything to swap!|^You swap/
        end
      }
    else
      actions.unshift proc {
        if left_hand.name =~ /^ethereal \w+$/
          fput "rub #{left_hand.noun} tattoo"
          20.times { break if (GameObj.left_hand.name == left_hand.name) || (GameObj.right_hand.name == left_hand.name); sleep 0.1 }
        elsif @bandolier_weapon[left_hand.name]
          fput "rub ##{find_bandolier_bag(left_hand)}"
          20.times { break if (GameObj.left_hand.name == left_hand.name) || (GameObj.right_hand.name == left_hand.name); sleep 0.1 }
        else
          fput "get ##{left_hand.id}"
          20.times { break if (GameObj.left_hand.id == left_hand.id) || (GameObj.right_hand.id == left_hand.id); sleep 0.1 }
        end

        if GameObj.right_hand.id == left_hand.id || (GameObj.right_hand.name == left_hand.name && left_hand.name =~ /^ethereal \w+$/)
          dothistimeout 'swap', 3, /^You don't have anything to swap!|^You swap/
        end
      }
      if (ready_item = ReadyList.ready_list.find { |_k, v| v.id.eql?(GameObj.left_hand.id) }) && ReadyList.store_list[ready_item[0]]
        result = Lich::Stash.add_to_bag(sheath, GameObj.left_hand) if ReadyList.store_list[ready_item[0]].eql?("put in sheath")
        result = Lich::Stash.add_to_bag(second_sheath, GameObj.left_hand) if ReadyList.store_list[ready_item[0]].eql?("put in secondary sheath")
        result = Lich::Stash.add_to_bag(StowList.default, GameObj.left_hand) if ["worn if possible, stowed otherwise", "stowed"].include?(ReadyList.store_list[ready_item[0]])
      elsif !second_sheath.nil? && GameObj.left_hand.type =~ /weapon/
        result = Lich::Stash.add_to_bag(second_sheath, GameObj.left_hand)
      elsif weaponsack && GameObj.left_hand.type =~ /weapon/
        result = Lich::Stash::add_to_bag(weaponsack, GameObj.left_hand)
      elsif lootsack
        result = Lich::Stash::add_to_bag(lootsack, GameObj.left_hand)
      else
        result = nil
      end
      if result.nil? || !result
        for container in other_containers.call
          result = Lich::Stash::add_to_bag(container, GameObj.left_hand)
          break if result
        end
      end
    end
  end
  if (right || both) && right_hand.id
    waitrt?
    actions.unshift proc {
      if right_hand.name =~ /^ethereal \w+$/
        fput "rub #{right_hand.noun} tattoo"
        20.times { break if GameObj.left_hand.name == right_hand.name || GameObj.right_hand.name == right_hand.name; sleep 0.1 }
      elsif @bandolier_weapon[right_hand.name]
        fput "rub ##{find_bandolier_bag(right_hand)}"
        20.times { break if GameObj.left_hand.name == right_hand.name || GameObj.right_hand.name == right_hand.name; sleep 0.1 }
      else
        fput "get ##{right_hand.id}"
        20.times { break if GameObj.left_hand.id == right_hand.id || GameObj.right_hand.id == right_hand.id; sleep 0.1 }
      end

      if GameObj.left_hand.id == right_hand.id || (GameObj.left_hand.name == right_hand.name && right_hand.name =~ /^ethereal \w+$/)
        dothistimeout 'swap', 3, /^You don't have anything to swap!|^You swap/
      end
    }
    if (ready_item = ReadyList.ready_list.find { |_k, v| v.id.eql?(GameObj.right_hand.id) }) && ReadyList.store_list[ready_item[0]]
      result = Lich::Stash.add_to_bag(sheath, GameObj.right_hand) if ReadyList.store_list[ready_item[0]].eql?("put in sheath")
      result = Lich::Stash.add_to_bag(second_sheath, GameObj.right_hand) if ReadyList.store_list[ready_item[0]].eql?("put in secondary sheath")
      result = Lich::Stash.add_to_bag(StowList.default, GameObj.right_hand) if ["worn if possible, stowed otherwise", "stowed"].include?(ReadyList.store_list[ready_item[0]])
    elsif !sheath.nil? && GameObj.right_hand.type =~ /weapon/
      result = Lich::Stash.add_to_bag(sheath, GameObj.right_hand)
    elsif weaponsack && GameObj.right_hand.type =~ /weapon/
      result = Lich::Stash::add_to_bag(weaponsack, GameObj.right_hand)
    elsif lootsack
      result = Lich::Stash::add_to_bag(lootsack, GameObj.right_hand)
    else
      result = nil
    end
    sleep 0.1
    if result.nil? || !result
      for container in other_containers.call
        result = Lich::Stash::add_to_bag(container, GameObj.right_hand)
        break if result
      end
    end
  end
  $fill_hands_actions.push(actions) if both
  $fill_left_hand_actions.push(actions) if left
  $fill_right_hand_actions.push(actions) if right
end

.try_or_fail(seconds: 2, command: nil) {|String| ... } ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Issues a command and waits for a condition with a timeout.

Sends a command via fput, then polls the block until it returns true or the timeout expires. Raises if the timeout is exceeded.

Parameters:

  • seconds (Integer) (defaults to: 2) —

    timeout in seconds (default 2)

  • command (String) (defaults to: nil) —

    the command to send via fput

Yields:

  • (String) —

    the result of the command; block should return true when done

Raises:

  • (RuntimeError) —

    when the block never returns true within the timeout



73
74
75
76
77
78
# File 'documented/stash.rb', line 73

def self.try_or_fail(seconds: 2, command: nil)
  result = fput(command)
  expiry = Time.now + seconds
  wait_until do yield(result) || Time.now > expiry end
  fail "Error[command: #{command}, seconds: #{seconds}]" if Time.now > expiry
end

.wear_to_inv(item) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Attempts to wear an item, moving it from inventory to worn slots.

Sends wear command and waits for the item to leave both hands and appear in inventory. Returns false if the wear location is full ("You can only wear two items in that location."). Retries for up to 2 seconds, polling every 0.1 seconds. Records worn status in @worn_items.

Parameters:

  • item (GameObj) —

    the item to wear

Returns:

  • (Boolean) —

    true if successfully worn, false if the location is full or worn failed



119
120
121
122
123
124
125
126
127
128
129
# File 'documented/stash.rb', line 119

def self.wear_to_inv(item)
  try_or_fail(command: "wear ##{item.id}") do |result|
    20.times {
      return true if (![GameObj.right_hand, GameObj.left_hand].map(&:id).compact.include?(item.id) && GameObj.inv.to_a.map(&:id).include?(item.id))
      return true if item.name =~ /^ethereal \w+$/ && ![GameObj.right_hand, GameObj.left_hand].map(&:id).compact.include?(item.id)
      sleep 0.1
    } unless result.is_a?(String) && result =~ /You can only wear two items in that location\./

    return @worn_items[item.name] = false
  end
end

.wield(param, hand: nil) ⇒ GameObj

Get a named item into a hand.

Worn items are removed, items in containers are fetched (opening the container first when Lich knows it is closed), and the target hand is emptied through stash_hands beforehand so nothing is dropped. When no hand is given the item goes wherever the game puts it.

Parameters:

  • param (GameObj, Integer, String, Symbol) —

    see find_item

  • hand (Symbol, nil) (defaults to: nil) —

    :right, :left, or nil for either

Returns:

  • (GameObj) —

    the item now in hand

Raises:

  • (RuntimeError) —

    when the item cannot be found or never arrives



503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
# File 'documented/stash.rb', line 503

def self.wield(param, hand: nil)
  fail "wield: hand must be :right, :left or nil, got #{hand.inspect}" unless hand.nil? || HANDS.include?(hand)
  if param.is_a?(String) && param !~ /\A\d+\z/
    candidates = find_items(param)
    fail "could not find Item[#{param.inspect}]" if candidates.empty?
    item = candidates.first
    echo "wield: #{param} -> #{item.name} (of #{candidates.size} kinds: #{candidates.map(&:name).join(', ')})" if candidates.size > 1
  else
    item = find_item(param)
  end

  holding = hand_holding(item)
  if holding
    return item if hand.nil? || holding == hand
    waitrt?
    dothistimeout 'swap', 3, /^You don't have anything to swap!|^You swap/
    return item if hand_holding(item) == hand
    fail "wield: could not move #{item.name} to the #{hand} hand"
  end

  waitrt?
  if hand
    free_hand(hand)
  elsif !empty_hand?(:right) && !empty_hand?(:left)
    free_hand(:right)
  end

  fail "wield: a container holding #{item.name} is locked or would not open" unless open_path_to(item)

  fetch = worn?(item) ? "remove ##{item.id}" : "get ##{item.id}"
  fput fetch
  ITEM_CONFIRM_TRIES.times { break if in_hand?(item); sleep ITEM_CONFIRM_SLEEP }

  # Did not arrive: the usual cause is a container closed since Lich last
  # saw inside it. Ask the game for the current tree, open, try once more.
  unless in_hand?(item)
    inventory
    fail "wield: a container holding #{item.name} is locked or would not open" unless open_path_to(item)
    fput fetch
    ITEM_CONFIRM_TRIES.times { break if in_hand?(item); sleep ITEM_CONFIRM_SLEEP }
  end
  fail "wield: #{item.name} did not arrive in hand" unless in_hand?(item)

  if hand && hand_holding(item) != hand
    dothistimeout 'swap', 3, /^You don't have anything to swap!|^You swap/
    fail "wield: could not move #{item.name} to the #{hand} hand" unless hand_holding(item) == hand
  end
  item
end

.worn?(item) ⇒ Boolean

Returns whether the item is in worn inventory (needs REMOVE, not GET).

Returns:

  • (Boolean) —

    whether the item is in worn inventory (needs REMOVE, not GET)



627
628
629
# File 'documented/stash.rb', line 627

def self.worn?(item)
  GameObj.inv.to_a.any? { |obj| obj.id == item.id }
end