Module: Lich::DragonRealms::DRCT
- Defined in:
- documented/dragonrealms/commons/common-travel.rb
Overview
Common travel utilities for DragonRealms scripts.
Provides methods to navigate between rooms, visit merchants to buy and sell items, and search for empty rooms. All navigation is performed via the go2 script using the map.
Constant Summary collapse
- DIRECTION_REVERSE =
Direction reversal mapping for path reversal Note: With frozen_string_literal: true, string literals are already frozen
{ 'northeast' => 'southwest', 'southwest' => 'northeast', 'northwest' => 'southeast', 'southeast' => 'northwest', 'north' => 'south', 'south' => 'north', 'east' => 'west', 'west' => 'east', 'up' => 'down', 'down' => 'up' }.freeze
- SELL_SUCCESS_PATTERNS =
Patterns indicating successful sale at a merchant
[ /hands? you \d+ (?:kronars|lirums|dokoras)/i ].freeze
- SELL_FAILURE_PATTERNS =
Patterns indicating failed sale attempt
[ /I need to examine the merchandise first/, /That's not worth anything/, /I only deal in pelts/, /There's folk around here that'd slit a throat for this/ ].freeze
- BUY_PRICE_PATTERNS =
Patterns that match merchant responses containing the price for a buy offer.
Each pattern includes a named capture group
amountthat extracts the price in the merchant's text. The amount may be numeric or spelled out (e.g., "100" or "one hundred"). [ /prepared to offer it to you for (?<amount>.*) (?:kronar|lirum|dokora)s?/, /Let me but ask the humble sum of (?<amount>.*) coins/, /it would be just (?<amount>\d*) (?:kronar|lirum|dokora)s?/, /for a (?:mere )?(?<amount>\d*) (?:kronar|lirum|dokora)s?/, /I can let that go for\.\.\.(?<amount>.*) (?:kronar|lirum|dokora)s?/, /cost you (?:just )?(?<amount>.*) (?:kronar|lirum|dokora)s?/, /it may be yours for just (?<amount>.*) (?:kronar|lirum|dokora)s?/, /I'll give that to you for (?<amount>.*) (?:kronar|lirum|dokora)s?/, /I'll let you have it for (?<amount>.*) (?:kronar|lirum|dokora)s?/i, /I ask that you give (?<amount>.*) copper (?:kronar|lirum|dokora)s?/, /it'll be (?<amount>.*) (?:kronar|lirum|dokora)s?/, /the price of (?<amount>.*) coins? is all I ask/, /tis only (?<amount>.*) (?:kronar|lirum|dokora)s?/, /That will be (?<amount>.*) copper (?:kronar|lirum|dokora)s? please/, /That'll be (?<amount>.*) copper (?:kronar|lirum|dokora)s?/, /to you for (?<amount>.*) (?:kronar|lirum|dokora)s?/, /I ask (?<amount>.*) copper (?:kronar|lirum|dokora)s or if you would prefer/, /Cost you just (?<amount>.*) (?:kronar|lirum|dokora)s?, okie dokie\?/i, /It will cost just (?<amount>.*) (?:kronar|lirum|dokora)s?/i, /I would suggest (?<amount>.*) (?:kronar|lirum|dokora)s?/i, /to you for (?<amount>.*) (?:kronar|lirum|dokora)s?/i, /asking (?<amount>.*) (?:kronar|lirum|dokora)s?/i ].freeze
- BUY_NON_PRICE_PATTERNS =
Patterns indicating buy action without price info
[ 'You decide to purchase', 'Buy what' ].freeze
- ASK_SUCCESS_PATTERNS =
Patterns indicating successful ASK request
[ /hands you/ ].freeze
- ASK_FAILURE_PATTERNS =
Patterns indicating failed ASK request
[ /does not seem to know anything about that/, /All I know about/, /To whom are you speaking/, /Usage: ASK/ ].freeze
- MAX_WALK_TO_RETRIES =
Maximum number of times walk_to will retry navigation before giving up. Prevents unbounded recursion (and eventual SystemStackError) when the game server connection is lost or go2 repeatedly fails.
3- WALK_TO_UNRESOLVED_WAIT =
Seconds walk_to waits for Room.current to resolve a room it could not resolve at first, before treating the room as unresolved. This also bounds how fast a caller that loops on walk_to without checking the result retries from such a room.
1- MAX_UNREACHABLE_SEARCHES =
find_empty_room gives up after this many searches in a row in which walk_to reached none of the search rooms. Searches that reach a room but find it occupied are not counted: those wait for max_search_attempts.
3
Class Method Summary collapse
-
.ask_for_item?(room, name, item) ⇒ Boolean
Visit a merchant and ask for an item.
-
.buy_item(room, item) ⇒ Object
Visit a merchant and buy an item by offering their asking price.
-
.dispose(item, trash_room = nil, worn_trashcan = nil, worn_trashcan_verb = nil) ⇒ void
Discards an item in a trash room or worn container.
-
.find_empty_room(search_rooms, idle_room, predicate = nil, min_mana = 0, strict_mana = false, max_search_attempts = Float::INFINITY, prioritize_buddies = false) ⇒ Boolean
Finds and navigates to an empty room suitable for casting or resting.
-
.find_sorted_empty_room(search_rooms, idle_room, predicate = nil) ⇒ Boolean
Finds an empty room after sorting the search list by distance from the current room.
-
.get_hometown_target_id(hometown, target) ⇒ Integer?
Looks up a room id for a location within a hometown.
-
.order_item(room, item_number) ⇒ Object
Visit a merchant and order from a menu.
-
.refill_lockpick_container(lockpick_type, hometown, container, count) ⇒ void
Buys lockpicks and stores them in a container at the locksmith.
-
.retreat(ignored_npcs = []) ⇒ void
Calls DRC.retreat if there are unignored NPCs in the current room.
-
.reverse_path(path) ⇒ Array<String>?
Reverses a path to travel backwards along the same route.
-
.sell_item(room, item) ⇒ Object
Visit a merchant and sell an item.
-
.sort_destinations(target_list) ⇒ Array<Integer>
Sorts a list of room ids by shortest path distance from the current room.
-
.tag_to_id(target) ⇒ Object
The id of the nearest room tagged
target, measured from the room Room.current resolves, or nil (with a message) when there is none or the current room is still unresolved after walk_to_current_room's wait. -
.time_to_room(origin, destination) ⇒ Integer?
Returns the shortest path distance in moves from origin to destination.
-
.walk_to(target_room, restart_on_fail = true, retry_depth: 0) ⇒ Boolean
Navigate to
target_roomusing the go2 script.
Class Method Details
.ask_for_item?(room, name, item) ⇒ Boolean
Visit a merchant and ask for an item. Usually this is for bundling ropes or gem pouches.
Returns false without asking when the walk to room fails.
141 142 143 144 145 146 147 148 149 150 |
# File 'documented/dragonrealms/commons/common-travel.rb', line 141 def ask_for_item?(room, name, item) return false unless walk_to_merchant(room, "asking #{name} for #{item}") case DRC.bput("ask #{name} for #{item}", *ASK_SUCCESS_PATTERNS, *ASK_FAILURE_PATTERNS) when *ASK_SUCCESS_PATTERNS true else false end end |
.buy_item(room, item) ⇒ Object
Visit a merchant and buy an item by offering their asking price. Usually for restocking ammunition or other misc items.
Returns nil without buying when the walk to room fails, so nothing
is bought from whichever merchant stands in another room.
125 126 127 128 129 130 131 132 133 134 135 |
# File 'documented/dragonrealms/commons/common-travel.rb', line 125 def buy_item(room, item) return unless walk_to_merchant(room, "buying #{item}") all_patterns = BUY_PRICE_PATTERNS + BUY_NON_PRICE_PATTERNS result = DRC.bput("buy #{item}", *all_patterns) match_data = BUY_PRICE_PATTERNS.lazy.filter_map { |p| p.match(result) }.first amount = match_data[:amount] if match_data fput("offer #{amount}") if amount end |
.dispose(item, trash_room = nil, worn_trashcan = nil, worn_trashcan_verb = nil) ⇒ void
This method returns an undefined value.
Discards an item in a trash room or worn container.
Walks to the trash room if provided, then calls DRCI.dispose_trash to drop or remove the item from a worn container. If trash_room is nil, only attempts to dispose via the worn container.
213 214 215 216 217 218 |
# File 'documented/dragonrealms/commons/common-travel.rb', line 213 def dispose(item, trash_room = nil, worn_trashcan = nil, worn_trashcan_verb = nil) return unless item DRCT.walk_to(trash_room) unless trash_room.nil? DRCI.dispose_trash(item, worn_trashcan, worn_trashcan_verb) end |
.find_empty_room(search_rooms, idle_room, predicate = nil, min_mana = 0, strict_mana = false, max_search_attempts = Float::INFINITY, prioritize_buddies = false) ⇒ Boolean
Finds and navigates to an empty room suitable for casting or resting.
Searches a list of rooms for one that is empty (no non-grouped players), optionally meets a custom predicate, and has sufficient mana if required. If no suitable room is found, waits at the idle room and retries. Stops after MAX_UNREACHABLE_SEARCHES consecutive unreachable searches or when max_search_attempts is reached.
With prioritize_buddies true, first looks for a room with a friend and no nemesis, running the predicate only in such rooms. On reaching the last room without finding a suitable buddy room, retries without the buddy pass.
Mana is checked if min_mana > 0 and the character is not a Moon Mage or Trader. If strict_mana is false (default), relaxes the mana requirement if empty rooms are found but none meet the mana threshold.
482 483 484 |
# File 'documented/dragonrealms/commons/common-travel.rb', line 482 def find_empty_room(search_rooms, idle_room, predicate = nil, min_mana = 0, strict_mana = false, max_search_attempts = Float::INFINITY, prioritize_buddies = false) find_empty_room_search(search_rooms, idle_room, predicate, min_mana, strict_mana, max_search_attempts, prioritize_buddies, []) end |
.find_sorted_empty_room(search_rooms, idle_room, predicate = nil) ⇒ Boolean
Finds an empty room after sorting the search list by distance from the current room.
Sorts the search rooms using sort_destinations, then calls find_empty_room to search them in order from nearest to farthest.
643 644 645 646 |
# File 'documented/dragonrealms/commons/common-travel.rb', line 643 def find_sorted_empty_room(search_rooms, idle_room, predicate = nil) sorted_rooms = sort_destinations(search_rooms) find_empty_room(sorted_rooms, idle_room, predicate) end |
.get_hometown_target_id(hometown, target) ⇒ Integer?
Mutates $common_travel_debug by reading it; consider it advisory only
Looks up a room id for a location within a hometown.
Retrieves the id for a named target (e.g. 'bank', 'locksmithing') within a hometown from the town data. On first failure, waits 2 seconds and retries (to handle potential data loading delays). Logs debug messages if $common_travel_debug is truthy.
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 |
# File 'documented/dragonrealms/commons/common-travel.rb', line 700 def get_hometown_target_id(hometown, target) hometown_data = get_data('town')[hometown] target_id = hometown_data[target] && hometown_data[target]['id'] unless target_id Lich::Messaging.msg('plain', "DRCT: get_hometown_target_id failed first attempt for #{target} in #{hometown}. Trying again.") if $common_travel_debug pause 2 hometown_data = get_data('town')[hometown] target_id = hometown_data[target] && hometown_data[target]['id'] unless target_id Lich::Messaging.msg('plain', "DRCT: get_hometown_target_id failed second attempt for #{target} in #{hometown}. Likely target doesn't exist.") if $common_travel_debug target_id = nil else Lich::Messaging.msg('plain', "DRCT: get_hometown_target_id succeeded second attempt for #{target} in #{hometown}.") if $common_travel_debug end end Lich::Messaging.msg('plain', "DRCT: target_id = #{target_id}") if $common_travel_debug target_id end |
.order_item(room, item_number) ⇒ Object
Visit a merchant and order from a menu.
Returns nil without ordering when the walk to room fails: ORDER takes
a menu number, so the same ORDER in another shop could buy another item.
156 157 158 159 160 161 162 |
# File 'documented/dragonrealms/commons/common-travel.rb', line 156 def order_item(room, item_number) return unless walk_to_merchant(room, "ordering #{item_number}") return if DRC.bput("order #{item_number}", 'Just order it again', 'you don\'t have enough coins') == 'you don\'t have enough coins' DRC.bput("order #{item_number}", 'takes some coins from you') end |
.refill_lockpick_container(lockpick_type, hometown, container, count) ⇒ void
This method returns an undefined value.
Buys lockpicks and stores them in a container at the locksmith.
Walks to the locksmith location for the hometown, buys the specified number of lockpicks, and puts them on the given container. If the locksmith location is not found, the walk fails, or putting away fails, logs a message and stops. Exits the shop when done (if an "out" exit exists) to keep the room clear.
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 |
# File 'documented/dragonrealms/commons/common-travel.rb', line 232 def refill_lockpick_container(lockpick_type, hometown, container, count) return if count < 1 room = get_data('town')[hometown]['locksmithing']['id'] if room.nil? Lich::Messaging.msg('bold', 'DRCT: No locksmith location found for current hometown. Skipping refilling.') return end walk_to(room) if Room.current.id != room Lich::Messaging.msg('bold', 'DRCT: Could not reach locksmith location. Skipping refilling.') return end count.times do buy_item(room, "#{lockpick_type} lockpick") unless DRCI.put_away_item_unsafe?('my lockpick', "my #{container}", 'on') Lich::Messaging.msg('bold', "DRCT: Failed to put lockpick on #{container}. Check your lockpick settings - mixing types in a container is not allowed.") break end end # Be polite to Thieves, who need the room to be empty DRC.fix_standing move('out') if XMLData.room_exits.include?('out') end |
.retreat(ignored_npcs = []) ⇒ void
This method returns an undefined value.
Calls DRC.retreat if there are unignored NPCs in the current room.
Filters the NPCs in the room by the ignored_npcs list and only retreats if at least one NPC remains after filtering.
444 445 446 447 448 |
# File 'documented/dragonrealms/commons/common-travel.rb', line 444 def retreat(ignored_npcs = []) return if DRRoom.unignored_npcs(ignored_npcs).empty? DRC.retreat(ignored_npcs) end |
.reverse_path(path) ⇒ Array<String>?
Reverses a path to travel backwards along the same route.
Takes an array of directions and returns them in reverse order with each direction reversed using DIRECTION_REVERSE. Returns nil and logs an error if a direction has no reverse mapping (e.g. abbreviations like 'ne' instead of 'northeast').
678 679 680 681 682 683 684 685 686 687 |
# File 'documented/dragonrealms/commons/common-travel.rb', line 678 def reverse_path(path) path.reverse.map do |dir| reversed = DIRECTION_REVERSE[dir] unless reversed Lich::Messaging.msg('bold', "DRCT: No reverse direction found for '#{dir}'. Use full direction names (e.g., 'northeast' not 'ne'). Path must be an array.") return nil end reversed end end |
.sell_item(room, item) ⇒ Object
Visit a merchant and sell an item. Usually to sell junk at pawn shops.
The item is referenced through Lich::DragonRealms::DRCI.item_ref, like the DRCI verbs: a
noun gets "my ", while "my sword" and "#
Returns false without selling when the item is not in hand or the
walk to room fails, so the item is never offered in another room.
108 109 110 111 112 113 114 115 116 117 118 |
# File 'documented/dragonrealms/commons/common-travel.rb', line 108 def sell_item(room, item) return false unless DRCI.in_hands?(item) return false unless walk_to_merchant(room, "selling #{item}") case DRC.bput("sell #{DRCI.item_ref(item)}", *SELL_SUCCESS_PATTERNS, *SELL_FAILURE_PATTERNS) when *SELL_SUCCESS_PATTERNS true when *SELL_FAILURE_PATTERNS false end end |
.sort_destinations(target_list) ⇒ Array<Integer>
Sorts a list of room ids by shortest path distance from the current room.
Uses dijkstra pathfinding from the current room to order the targets from nearest to farthest. If a room has no path or pathfinding fails, it is removed (except the current room itself, which is always kept). Returns the input list if pathfinding fails entirely.
621 622 623 624 625 626 627 628 629 630 631 632 |
# File 'documented/dragonrealms/commons/common-travel.rb', line 621 def sort_destinations(target_list) target_list = target_list.collect(&:to_i) _previous, shortest_distances = Map.dijkstra(Room.current.id) # Pathfinding failed; hand back what was asked for rather than nothing. return target_list if shortest_distances.nil? target_list.delete_if { |room_num| shortest_distances[room_num].nil? && room_num != Room.current.id } # The current room is kept above even without a distance, so sort on a # fallback rather than handing nil to the comparator. dijkstra seeds the # source at 0, so this is defensive rather than a live case. target_list.sort_by { |room_num| shortest_distances[room_num] || Float::INFINITY } end |
.tag_to_id(target) ⇒ Object
The id of the nearest room tagged target, measured from the room
Room.current resolves, or nil (with a message) when there is none or
the current room is still unresolved after walk_to_current_room's wait.
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 |
# File 'documented/dragonrealms/commons/common-travel.rb', line 398 def tag_to_id(target) target_list = Map.rooms_by_tag(target) if target_list.empty? Lich::Messaging.msg('bold', "DRCT: No go2 targets matching '#{target}' found.") return nil end start = walk_to_current_room if start.nil? ("cannot find the nearest room tagged '#{target}'") return nil end start_room = start.id if target_list.include?(start_room) Lich::Messaging.msg('plain', "DRCT: You're already here.") return start_room end _previous, shortest_distances = start.dijkstra(target_list) if shortest_distances.nil? Lich::Messaging.msg('bold', "DRCT: Pathfinding failed while looking for a '#{target}' tag.") return nil end target_list.delete_if { |room_id| shortest_distances[room_id].nil? } if target_list.empty? Lich::Messaging.msg('bold', "DRCT: Couldn't find a path from here to any room with a '#{target}' tag.") return nil end target_id = target_list.sort { |a, b| shortest_distances[a] <=> shortest_distances[b] }.first unless target_id && (destination = Map[target_id]) Lich::Messaging.msg('bold', "DRCT: Something went wrong! Debug failed with target_id=#{target_id}, destination=#{destination}, tag='#{target}'.") return nil end target_id end |
.time_to_room(origin, destination) ⇒ Integer?
Returns the shortest path distance in moves from origin to destination.
Uses dijkstra pathfinding to compute the minimum number of moves. Returns nil if pathfinding fails or no path exists.
656 657 658 659 660 661 662 663 664 |
# File 'documented/dragonrealms/commons/common-travel.rb', line 656 def time_to_room(origin, destination) # Results are keyed by Integer room id, and dijkstra only terminates # early when the destination compares as an Integer. destination = destination.to_i _previous, shortest_paths = Map.dijkstra(origin, destination) return nil if shortest_paths.nil? shortest_paths[destination] end |
.walk_to(target_room, restart_on_fail = true, retry_depth: 0) ⇒ Boolean
Navigate to target_room using the go2 script.
Room.current (the map's resolver, Map.current) is the only rule for where the character is, both for the start room and for arrival, so walk_to is exactly as strict as that resolver and no stricter. From a room it cannot resolve, even after waiting WALK_TO_UNRESOLVED_WAIT seconds, walk_to sends nothing and returns false; this holds for tag targets too (see tag_to_id).
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 344 345 346 347 348 349 350 351 352 353 354 355 356 |
# File 'documented/dragonrealms/commons/common-travel.rb', line 285 def walk_to(target_room, restart_on_fail = true, retry_depth: 0) target_room = tag_to_id(target_room) if map_tag?(target_room) return false if target_room.nil? room_num = target_room.to_i current_id = walk_to_current_room_id return true if room_num == current_id return walk_to_unresolved_failure(room_num) if current_id.nil? DRC.fix_standing script_handle = start_script('go2', [room_num.to_s], force: true) timer = Time.now prev_room = XMLData.room_description + XMLData.room_title Flags.add('travel-closed-shop', 'The door is locked up tightly for the night', 'You smash your nose', '^A servant (blocks|stops)') Flags.add('travel-engaged', 'You are engaged') begin while Script.running.include?(script_handle) if Flags['travel-closed-shop'] Flags.reset('travel-closed-shop') kill_script(script_handle) if /You open/ !~ DRC.bput('open door', 'It is locked', 'You .+', 'What were') restart_on_fail = false break end timer = Time.now script_handle = start_script('go2', [room_num.to_s]) end if Flags['travel-engaged'] Flags.reset('travel-engaged') kill_script(script_handle) DRC.retreat timer = Time.now script_handle = start_script('go2', [room_num.to_s]) end if (Time.now - timer) > 90 kill_script(script_handle) pause 0.5 while Script.running.include?(script_handle) break unless restart_on_fail timer = Time.now script_handle = start_script('go2', [room_num.to_s]) end if Script.running?('escort') || Script.running?('bescort') || (XMLData.room_description + XMLData.room_title) != prev_room || XMLData.room_description =~ /The terrain constantly changes as you travel along on your journey/ timer = Time.now end prev_room = XMLData.room_description + XMLData.room_title pause 0.5 end ensure Flags.delete('travel-closed-shop') Flags.delete('travel-engaged') end current_id = walk_to_current_room_id arrived = current_id == room_num if !arrived && restart_on_fail return walk_to_unresolved_failure(room_num) if current_id.nil? if retry_depth >= MAX_WALK_TO_RETRIES Lich::Messaging.msg('bold', "DRCT: Failed to navigate to room #{room_num} after #{MAX_WALK_TO_RETRIES} retries, giving up.") return false end Lich::Messaging.msg('bold', "DRCT: Failed to navigate to room #{room_num}, attempting again (#{retry_depth + 1}/#{MAX_WALK_TO_RETRIES}).") return walk_to(room_num, true, retry_depth: retry_depth + 1) end arrived end |