Top Level Namespace

Includes:
Win32

Defined Under Namespace

Modules: Lich, SessionVars, Win32, Win32Enum, WinAPI, Wine Classes: Hash, MatchData, NilClass, Numeric, String

Constant Summary collapse

LICH_VERSION =

The current version of the Lich5 project.

Examples:

Current version

puts LICH_VERSION # => '5.17.1'
'5.17.1'
REQUIRED_RUBY =

x-release-please-version

'2.6'
'3.2'
TESTING =

Indicates whether the application is in testing mode.

Returns:

  • (Boolean)

    true if testing is enabled, false otherwise

false
DIRMAP =

transcoding migrated 2024-06-13 A mapping of direction abbreviations to their corresponding codes.

Examples:

DIRMAP['out']  # => 'K'
DIRMAP['ne']   # => 'B'

See Also:

{
  'out'  => 'K',
  'ne'   => 'B',
  'se'   => 'D',
  'sw'   => 'F',
  'nw'   => 'H',
  'up'   => 'I',
  'down' => 'J',
  'n'    => 'A',
  'e'    => 'C',
  's'    => 'E',
  'w'    => 'G',
}
SHORTDIR =

A mapping of full direction names to their abbreviations.

Examples:

SHORTDIR['northeast'] # => 'ne'
SHORTDIR['southwest'] # => 'sw'

See Also:

{
  'out'       => 'out',
  'northeast' => 'ne',
  'southeast' => 'se',
  'southwest' => 'sw',
  'northwest' => 'nw',
  'up'        => 'up',
  'down'      => 'down',
  'north'     => 'n',
  'east'      => 'e',
  'south'     => 's',
  'west'      => 'w',
}
LONGDIR =

A mapping of direction abbreviations to their full names.

Examples:

LONGDIR['ne']   # => 'northeast'
LONGDIR['sw']   # => 'southwest'

See Also:

{
  'out'  => 'out',
  'ne'   => 'northeast',
  'se'   => 'southeast',
  'sw'   => 'southwest',
  'nw'   => 'northwest',
  'up'   => 'up',
  'down' => 'down',
  'n'    => 'north',
  'e'    => 'east',
  's'    => 'south',
  'w'    => 'west',
}
MINDMAP =

A mapping of mental state descriptions to their corresponding codes.

Examples:

MINDMAP['clear as a bell'] # => 'A'
MINDMAP['muddled']         # => 'D'
{
  'clear as a bell' => 'A',
  'fresh and clear' => 'B',
  'clear'           => 'C',
  'muddled'         => 'D',
  'becoming numbed' => 'E',
  'numbed'          => 'F',
  'must rest'       => 'G',
  'saturated'       => 'H',
}
ICONMAP =

A mapping of icon names to their corresponding codes.

Examples:

ICONMAP['IconKNEELING']  # => 'GH'
ICONMAP['IconDEAD']      # => 'B'
{
  'IconKNEELING'  => 'GH',
  'IconPRONE'     => 'G',
  'IconSITTING'   => 'H',
  'IconSTANDING'  => 'T',
  'IconSTUNNED'   => 'I',
  'IconHIDDEN'    => 'N',
  'IconINVISIBLE' => 'D',
  'IconDEAD'      => 'B',
  'IconWEBBED'    => 'C',
  'IconJOINED'    => 'P',
  'IconBLEEDING'  => 'O',
}
Frontend =

Top-level alias so all consumers can use bare Frontend

Lich::Common::Frontend
KRAMDOWN_LOADED =

Attempt to install and require kramdown, tracking if it loaded successfully

begin
  Lich::Util.install_gem_requirements({ 'kramdown' => false })
  require 'kramdown'
  true
rescue Gem::ConflictError => e
  # Gem version conflict - kramdown can't be activated due to dependency issues
  warn "TextStripper: Kramdown gem conflict detected (#{e.message}). Restart Lich5 to resolve."
  false
rescue LoadError => e
  # Kramdown gem not found or couldn't be loaded
  warn "TextStripper: Kramdown could not be loaded (#{e.message}). Restart Lich5 to resolve."
  false
rescue StandardError => e
  # Catch any other gem-related errors
  warn "TextStripper: Error loading kramdown (#{e.class}: #{e.message}). Restart Lich5 to resolve."
  false
end
QStrike =

Top-level convenience alias

Lich::Gemstone::QStrike
HAVE_GTK =
false

Constants included from Win32

Win32::HKEY_LOCAL_MACHINE, Win32::IDICANCEL, Win32::IDINO, Win32::IDIOK, Win32::IDIYES, Win32::KEY_ALL_ACCESS, Win32::KEY_CREATE_SUB_KEY, Win32::KEY_ENUMERATE_SUB_KEYS, Win32::KEY_EXECUTE, Win32::KEY_NOTIFY, Win32::KEY_QUERY_VALUE, Win32::KEY_READ, Win32::KEY_SET_VALUE, Win32::KEY_WOW64_32KEY, Win32::KEY_WOW64_64KEY, Win32::KEY_WRITE, Win32::MB_ICONERROR, Win32::MB_ICONQUESTION, Win32::MB_ICONWARNING, Win32::MB_OK, Win32::MB_OKCANCEL, Win32::MB_YESNO, Win32::PROCESS_QUERY_INFORMATION, Win32::PROCESS_VM_READ, Win32::REG_BINARY, Win32::REG_DWORD, Win32::REG_DWORD_BIG_ENDIAN, Win32::REG_DWORD_LITTLE_ENDIAN, Win32::REG_EXPAND_SZ, Win32::REG_LINK, Win32::REG_MULTI_SZ, Win32::REG_NONE, Win32::REG_QWORD, Win32::REG_QWORD_LITTLE_ENDIAN, Win32::REG_SZ, Win32::SEE_MASK_NOCLOSEPROCESS, Win32::SIZEOF_CHAR, Win32::SIZEOF_LONG, Win32::STILL_ACTIVE, Win32::SW_SHOW, Win32::SW_SHOWNORMAL, Win32::TOKEN_QUERY, Win32::TokenElevation

Instance Method Summary collapse

Instance Method Details

#_echo(*messages) ⇒ void

This method returns an undefined value.

Sends a message to the script's output without formatting.

Parameters:

  • messages (Array<String>)

    messages to send



273
274
275
276
277
278
279
280
281
282
283
# File 'documented/global_defs.rb', line 273

def _echo(*messages)
  _respond if messages.empty?
  if (script = Script.current)
    unless script.no_echo
      messages.each { |message| _respond("[#{script.custom? ? 'custom/' : ''}#{script.name}: #{message.to_s.chomp}]") }
    end
  else
    messages.each { |message| _respond("[(unknown script): #{message.to_s.chomp}]") }
  end
  nil
end

#_respond(first = "", *messages) ⇒ void

This method returns an undefined value.

Sends a response to the client without formatting.

Parameters:

  • first (String, Array) (defaults to: "")

    first message or array of messages to send

  • messages (Array<String>)

    additional messages to send



2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
# File 'documented/global_defs.rb', line 2356

def _respond(first = "", *messages)
  str = ''
  begin
    if first.is_a?(Array)
      first.flatten.each { |ln| str += sprintf("%s\r\n", ln.to_s.chomp) }
    else
      str += sprintf("%s\r\n", first.to_s.chomp)
    end
    # str.gsub!(/\r?\n/, "\r\n") if $frontend == 'genie'
    messages.flatten.each { |message| str += sprintf("%s\r\n", message.to_s.chomp) }
    str.split(/\r?\n/).each { |line| Script.new_script_output(line); Buffer.update(line, Buffer::SCRIPT_OUTPUT) } # fixme: strip/separate script output?
    str_sent = false
    if $_CLIENT_
      until str_sent
        wait_while { !XMLData.safe_to_respond? }
        str_sent = $_CLIENT_.puts_if(str) { XMLData.safe_to_respond? }
      end
    end
    if $_DETACHABLE_CLIENT_
      str_sent = false
      until str_sent
        wait_while { !XMLData.safe_to_respond? }
        begin
          str_sent = $_DETACHABLE_CLIENT_.puts_if(str) { XMLData.safe_to_respond? }
        rescue
          break
        end
      end
    end
  rescue
    puts $!
    puts $!.backtrace.first
  end
end

#abort!void

This method returns an undefined value.

Aborts the current script execution.



123
124
125
# File 'documented/global_defs.rb', line 123

def abort!
  Script.exit!
end

#alias_deprecatedvoid Also known as: reallybleeding?

This method returns an undefined value.

Handles deprecated alias commands.



3268
3269
3270
3271
# File 'documented/global_defs.rb', line 3268

def alias_deprecated
  # todo: add command reference, possibly add calling script
  echo "The alias command you're attempting to use is deprecated.  Fix your script."
end

#before_dying { ... } ⇒ void

This method returns an undefined value.

Registers a block of code to run before the script exits.

Yields:

  • code to execute before dying



111
112
113
# File 'documented/global_defs.rb', line 111

def before_dying(&code)
  Script.at_exit(&code)
end

#bin2dec(n) ⇒ Integer

Converts a binary string representation to a decimal number.

Parameters:

  • n (String)

    the binary string to convert

Returns:

  • (Integer)

    decimal representation of the number



562
563
564
# File 'documented/global_defs.rb', line 562

def bin2dec(n)
  [("0" * 32 + n.to_s)[-32..-1]].pack("B32").unpack("N")[0]
end

#bound?Boolean

Checks if the character is bound.

Returns:

  • (Boolean)

    true if bound



1770
1771
1772
1773
# File 'documented/global_defs.rb', line 1770

def bound?
  return Status.bound? if XMLData.game =~ /GS/
  fail "Error: toplevel bound? command not enabled in #{XMLData.game}"
end

#calmed?Boolean

Checks if the character is calmed.

Returns:

  • (Boolean)

    true if calmed



1798
1799
1800
1801
# File 'documented/global_defs.rb', line 1798

def calmed?
  return Status.calmed? if XMLData.game =~ /GS/
  fail "Error: toplevel calmed? command not enabled in #{XMLData.game}"
end

#cast(spell, target = nil, results_of_interest = nil) ⇒ Boolean

Casts a spell on a target.

Parameters:

  • spell (String, Integer, Spell)

    the spell to cast

  • target (String, nil) (defaults to: nil)

    optional target for the spell

  • results_of_interest (String, nil) (defaults to: nil)

    optional results to track

Returns:

  • (Boolean)

    true if the spell was cast successfully



1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
# File 'documented/global_defs.rb', line 1846

def cast(spell, target = nil, results_of_interest = nil)
  if spell.is_a?(Spell)
    spell.cast(target, results_of_interest)
  elsif ((spell.is_a?(Integer)) or (spell.to_s =~ /^[0-9]+$/)) and (find_spell = Spell[spell.to_i])
    find_spell.cast(target, results_of_interest)
  elsif (spell.is_a?(String)) and (find_spell = Spell[spell])
    find_spell.cast(target, results_of_interest)
  else
    echo "cast: invalid spell (#{spell})"
    false
  end
end

#check_mind(string = nil) ⇒ Boolean, String

Checks the character's mental state based on a string or value.

Parameters:

  • string (String, nil) (defaults to: nil)

    optional string to check against

Returns:

  • (Boolean, String)

    true if a match is found, or the character's mind text if no parameters are provided



1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
# File 'documented/global_defs.rb', line 1154

def check_mind(string = nil)
  if string.nil?
    return XMLData.mind_text
  elsif (string.is_a?(String)) and (string.to_i == 0)
    if string =~ /#{XMLData.mind_text}/i
      return true
    else
      return false
    end
  elsif string.to_i.between?(0, 100)
    return string.to_i <= XMLData.mind_value.to_i
  else
    echo("check_mind error! You must provide an integer ranging from 0-100, the common abbreviation of how full your head is, or provide no input to have check_mind return an abbreviation of how filled your head is."); sleep 1
    return false
  end
end

#checkarea(*strings) ⇒ Boolean, String

Checks the current area against specified strings.

Parameters:

  • strings (Array<String>)

    area names to check against

Returns:

  • (Boolean, String)

    true if a match is found, or the area title if no parameters are provided



1479
1480
1481
1482
1483
1484
1485
1486
# File 'documented/global_defs.rb', line 1479

def checkarea(*strings)
  strings.flatten!
  if strings.empty?
    XMLData.room_title.split(',').first.sub('[', '')
  else
    XMLData.room_title.split(',').first =~ /#{strings.join('|')}/i
  end
end

#checkbleedingBoolean Also known as: bleeding?

Checks if the character is bleeding.

Returns:

  • (Boolean)

    true if bleeding



432
433
434
# File 'documented/global_defs.rb', line 432

def checkbleeding
  XMLData.indicator['IconBLEEDING'] == 'y'
end

#checkboundBoolean

Checks if the character is bound.

Returns:

  • (Boolean)

    true if bound



1763
1764
1765
1766
# File 'documented/global_defs.rb', line 1763

def checkbound
  return Status.bound? if XMLData.game =~ /GS/
  fail "Error: toplevel checkbound command not enabled in #{XMLData.game}"
end

#checkbountyString? Also known as: bounty?

Checks if there is a bounty task assigned.

Returns:

  • (String, nil)

    the bounty task or nil if none



1739
1740
1741
1742
1743
1744
1745
# File 'documented/global_defs.rb', line 1739

def checkbounty
  if XMLData.bounty_task
    return XMLData.bounty_task
  else
    return nil
  end
end

#checkcalmedBoolean

Checks if the character is calmed.

Returns:

  • (Boolean)

    true if calmed



1791
1792
1793
1794
# File 'documented/global_defs.rb', line 1791

def checkcalmed
  return Status.calmed? if XMLData.game =~ /GS/
  fail "Error: toplevel checkcalmed command not enabled in #{XMLData.game}"
end

#checkcastrtInteger

Checks the current casting roundtime.

Returns:

  • (Integer)

    current casting roundtime value



375
376
377
# File 'documented/global_defs.rb', line 375

def checkcastrt
  [0, XMLData.cast_roundtime_end.to_f - Time.now.to_f + XMLData.server_time_offset.to_f].max
end

#checkcutthroatBoolean

Checks if the character is cutthroat.

Returns:

  • (Boolean)

    true if cutthroat



1805
1806
1807
1808
# File 'documented/global_defs.rb', line 1805

def checkcutthroat
  return Status.cutthroat? if XMLData.game =~ /GS/
  fail "Error: toplevel checkcutthroat command not enabled in #{XMLData.game}"
end

#checkdeadBoolean Also known as: dead?

Checks if the character is dead.

Returns:

  • (Boolean)

    true if dead



444
445
446
# File 'documented/global_defs.rb', line 444

def checkdead
  XMLData.indicator['IconDEAD'] == 'y'
end

#checkdiseaseBoolean Also known as: diseased?

Checks if the character is diseased.

Returns:

  • (Boolean)

    true if diseased



408
409
410
# File 'documented/global_defs.rb', line 408

def checkdisease
  XMLData.indicator['IconDISEASED'] == 'y'
end

#checkencumbrance(string = nil) ⇒ Boolean Also known as: encumbrance?

Checks the character's encumbrance against a specified string or value.

Parameters:

  • string (String, nil) (defaults to: nil)

    optional string to check against

Returns:

  • (Boolean)

    true if encumbrance matches string



1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
# File 'documented/global_defs.rb', line 1446

def checkencumbrance(string = nil)
  Lich.deprecated('checkencumbrance', 'Char.encumbrance')
  if string.nil?
    XMLData.encumbrance_text
  elsif (string.is_a?(Integer)) or (string =~ /^[0-9]+$/ and (string = string.to_i))
    string <= XMLData.encumbrance_value
  else
    # fixme
    if string =~ /#{XMLData.encumbrance_text}/i
      true
    else
      false
    end
  end
end

#checkfamarea(*strings) ⇒ Boolean, String

Checks the familiar area against specified strings.

Parameters:

  • strings (Array<String>)

    familiar area names to check against

Returns:

  • (Boolean, String)

    true if a match is found, or the familiar area title if no parameters are provided



1515
1516
1517
1518
1519
1520
# File 'documented/global_defs.rb', line 1515

def checkfamarea(*strings)
  strings.flatten!
  if strings.empty? then return XMLData.familiar_room_title.split(',').first.sub('[', '') end

  XMLData.familiar_room_title.split(',').first =~ /#{strings.join('|')}/i
end

#checkfamnpcs(*strings) ⇒ Boolean, Array<String>

Checks the familiar NPCs against specified strings.

Parameters:

  • strings (Array<String>)

    NPC names to check against

Returns:

  • (Boolean, Array<String>)

    true if a match is found, or an array of familiar NPC names



1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
# File 'documented/global_defs.rb', line 1552

def checkfamnpcs(*strings)
  parsed = Array.new
  XMLData.familiar_npcs.each { |val| parsed.push(val.split.last) }
  if strings.empty?
    if parsed.empty?
      return false
    else
      return parsed
    end
  else
    if (mtch = strings.find { |lookfor| parsed.find { |critter| critter =~ /#{lookfor}/ } })
      return mtch
    else
      return false
    end
  end
end

#checkfampaths(dir = "none") ⇒ Array<String>, Boolean

Checks the familiar room exits against a specified direction.

Parameters:

  • dir (String) (defaults to: "none")

    direction to check

Returns:

  • (Array<String>, Boolean)

    list of familiar paths or false if none



1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
# File 'documented/global_defs.rb', line 1526

def checkfampaths(dir = "none")
  if dir == "none"
    if XMLData.familiar_room_exits.empty?
      return false
    else
      return XMLData.familiar_room_exits
    end
  else
    XMLData.familiar_room_exits.include?(dir)
  end
end

#checkfampcs(*strings) ⇒ Boolean, Array<String>

Checks the familiar PCs against specified strings.

Parameters:

  • strings (Array<String>)

    PC names to check against

Returns:

  • (Boolean, Array<String>)

    true if a match is found, or an array of familiar PC names



1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
# File 'documented/global_defs.rb', line 1574

def checkfampcs(*strings)
  familiar_pcs = Array.new
  XMLData.familiar_pcs.to_s.gsub(/Lord |Lady |Great |High |Renowned |Grand |Apprentice |Novice |Journeyman /, '').split(',').each { |line| familiar_pcs.push(line.slice(/[A-Z][a-z]+/)) }
  if familiar_pcs.empty?
    return false
  elsif strings.empty?
    return familiar_pcs
  else
    regexpstr = strings.join('|\b')
    peeps = familiar_pcs.find_all { |val| val =~ /\b#{regexpstr}/i }
    if peeps.empty?
      return false
    else
      return peeps
    end
  end
end

#checkfamroom(*strings) ⇒ Boolean, String

Checks the familiar room against specified strings.

Parameters:

  • strings (Array<String>)

    familiar room names to check against

Returns:

  • (Boolean, String)

    true if a match is found, or the familiar room title if no parameters are provided



1542
1543
1544
1545
1546
# File 'documented/global_defs.rb', line 1542

def checkfamroom(*strings)
  strings.flatten!; if strings.empty? then return XMLData.familiar_room_title.chomp end

  XMLData.familiar_room_title =~ /#{strings.join('|')}/i
end

#checkfamroomdescrip(*val) ⇒ Boolean, String

Checks the familiar room description against specified strings.

Parameters:

  • val (Array<String>)

    strings to check against

Returns:

  • (Boolean, String)

    true if a match is found, or the familiar room description if no parameters are provided



1685
1686
1687
1688
1689
1690
1691
1692
# File 'documented/global_defs.rb', line 1685

def checkfamroomdescrip(*val)
  val.flatten!
  if val.empty?
    return XMLData.familiar_room_description
  else
    return XMLData.familiar_room_description =~ /#{val.join('|')}/i
  end
end

#checkfriedBoolean Also known as: fried?

Checks if the character is fried mentally.

Returns:

  • (Boolean)

    true if fried



1213
1214
1215
1216
1217
1218
1219
# File 'documented/global_defs.rb', line 1213

def checkfried
  if XMLData.mind_text =~ /must rest|saturated/
    true
  else
    false
  end
end

#checkgroupedBoolean Also known as: joined?, checkjoined, group?

Checks if the character is grouped.

Returns:

  • (Boolean)

    true if grouped



438
439
440
# File 'documented/global_defs.rb', line 438

def checkgrouped
  XMLData.indicator['IconJOINED'] == 'y'
end

#checkhealth(num = nil) ⇒ Boolean Also known as: health, health?

Checks the character's health against a specified number.

Parameters:

  • num (Integer, nil) (defaults to: nil)

    optional number to compare against

Returns:

  • (Boolean)

    true if health is greater than or equal to num



1273
1274
1275
1276
1277
1278
1279
1280
# File 'documented/global_defs.rb', line 1273

def checkhealth(num = nil)
  Lich.deprecated('checkhealth', 'Char.health')
  if num.nil?
    XMLData.health
  else
    XMLData.health >= num.to_i
  end
end

#checkhiddenBoolean Also known as: hiding?, hidden?, hidden, checkhiding

Checks if the character is hidden.

Returns:

  • (Boolean)

    true if hidden



467
468
469
# File 'documented/global_defs.rb', line 467

def checkhidden
  XMLData.indicator['IconHIDDEN'] == 'y'
end

#checkinvisibleBoolean Also known as: invisible?

Checks if the character is invisible.

Returns:

  • (Boolean)

    true if invisible



473
474
475
# File 'documented/global_defs.rb', line 473

def checkinvisible
  XMLData.indicator['IconINVISIBLE'] == 'y'
end

#checkkneelingBoolean Also known as: kneeling?

Checks if the character is kneeling.

Returns:

  • (Boolean)

    true if kneeling



420
421
422
# File 'documented/global_defs.rb', line 420

def checkkneeling
  XMLData.indicator['IconKNEELING'] == 'y'
end

#checkleft(*hand) ⇒ String? Also known as: lefthand?, lefthand

Checks the left hand for specified items.

Parameters:

  • hand (Array<String>)

    optional items to check for

Returns:

  • (String, nil)

    item found or nil if empty



1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
# File 'documented/global_defs.rb', line 1655

def checkleft(*hand)
  if GameObj.left_hand.nil? then return nil end

  hand.flatten!
  if GameObj.left_hand.name == "Empty" or GameObj.left_hand.name.empty?
    nil
  elsif hand.empty?
    GameObj.left_hand.noun
  else
    hand.find { |instance| GameObj.left_hand.name =~ /#{instance}/i }
  end
end

#checklootArray<String>

Checks the loot available to the character.

Returns:

  • (Array<String>)

    list of loot items



516
517
518
# File 'documented/global_defs.rb', line 516

def checkloot
  GameObj.loot.collect { |item| item.noun }
end

#checkmana(num = nil) ⇒ Boolean Also known as: mana, mana?

Checks the character's mana against a specified number.

Parameters:

  • num (Integer, nil) (defaults to: nil)

    optional number to compare against

Returns:

  • (Boolean)

    true if mana is greater than or equal to num



1235
1236
1237
1238
1239
1240
1241
1242
# File 'documented/global_defs.rb', line 1235

def checkmana(num = nil)
  Lich.deprecated('checkmana', 'Char.mana')
  if num.nil?
    XMLData.mana
  else
    XMLData.mana >= num.to_i
  end
end

#checkmind(string = nil) ⇒ Boolean, String Also known as: mind?

Checks the character's mental state based on a string or value.

Parameters:

  • string (String, nil) (defaults to: nil)

    optional string to check against

Returns:

  • (Boolean, String)

    true if a match is found, or the character's mind text if no parameters are provided



1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
# File 'documented/global_defs.rb', line 1175

def checkmind(string = nil)
  if string.nil?
    return XMLData.mind_text
  elsif string.is_a?(String) and string.to_i == 0
    if string =~ /#{XMLData.mind_text}/i
      return true
    else
      return false
    end
  elsif string.to_i.between?(1, 8)
    mind_state = ['clear as a bell', 'fresh and clear', 'clear', 'muddled', 'becoming numbed', 'numbed', 'must rest', 'saturated']
    if mind_state.index(XMLData.mind_text)
      mind = mind_state.index(XMLData.mind_text) + 1
      return string.to_i <= mind
    else
      echo "Bad string in checkmind: mind_state"
      nil
    end
  else
    echo("Checkmind error! You must provide an integer ranging from 1-8 (7 is fried, 8 is 100% fried), the common abbreviation of how full your head is, or provide no input to have checkmind return an abbreviation of how filled your head is."); sleep 1
    return false
  end
end

#checkname(*strings) ⇒ Boolean, String Also known as: myname?

Checks if the character's name matches any of the provided strings.

Parameters:

  • strings (Array<String>)

    names to check against

Returns:

  • (Boolean, String)

    true if a match is found, or the character's name if no parameters are provided



505
506
507
508
509
510
511
512
# File 'documented/global_defs.rb', line 505

def checkname(*strings)
  strings.flatten!
  if strings.empty?
    XMLData.name
  else
    XMLData.name =~ /^(?:#{strings.join('|')})/i
  end
end

#checknotstandingBoolean

Checks if the character is not standing.

Returns:

  • (Boolean)

    true if not standing



491
492
493
# File 'documented/global_defs.rb', line 491

def checknotstanding
  XMLData.indicator['IconSTANDING'] == 'n'
end

#checknpcs(*strings) ⇒ Boolean, Array<String>

Checks the NPCs in the game against specified strings.

Parameters:

  • strings (Array<String>)

    NPC names to check against

Returns:

  • (Boolean, Array<String>)

    true if a match is found, or an array of NPC names



1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
# File 'documented/global_defs.rb', line 1614

def checknpcs(*strings)
  npcs = GameObj.npcs.collect { |npc| npc.noun }
  if npcs.empty?
    if strings.empty? then return nil else return false end
  end
  strings.flatten!
  if strings.empty?
    npcs
  else
    regexpstr = strings.join(' ')
    npcs.find { |npc| regexpstr =~ /\b#{npc}/i }
  end
end

#checkpaths(dir = "none") ⇒ Array<String>, Boolean

Checks available paths in the current room.

Parameters:

  • dir (String) (defaults to: "none")

    direction to check

Returns:

  • (Array<String>, Boolean)

    list of available paths or false if none



1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
# File 'documented/global_defs.rb', line 1071

def checkpaths(dir = "none")
  if dir == "none"
    if XMLData.room_exits.empty?
      return false
    else
      return XMLData.room_exits.collect { |room_exits| SHORTDIR[room_exits] }
    end
  else
    XMLData.room_exits.include?(dir) || XMLData.room_exits.include?(SHORTDIR[dir])
  end
end

#checkpcs(*strings) ⇒ Boolean, Array<String>

Checks the PCs in the game against specified strings.

Parameters:

  • strings (Array<String>)

    PC names to check against

Returns:

  • (Boolean, Array<String>)

    true if a match is found, or an array of PC names



1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
# File 'documented/global_defs.rb', line 1596

def checkpcs(*strings)
  pcs = GameObj.pcs.collect { |pc| pc.noun }
  if pcs.empty?
    if strings.empty? then return nil else return false end
  end
  strings.flatten!
  if strings.empty?
    pcs
  else
    regexpstr = strings.join(' ')
    pcs.find { |pc| regexpstr =~ /\b#{pc}/i }
  end
end

#checkpoisonBoolean Also known as: poisoned?

Checks if the character is poisoned.

Returns:

  • (Boolean)

    true if poisoned



402
403
404
# File 'documented/global_defs.rb', line 402

def checkpoison
  XMLData.indicator['IconPOISONED'] == 'y'
end

#checkprep(spell = nil) ⇒ Boolean Also known as: prepped?, checkprepared

Checks if a spell is prepared.

Parameters:

  • spell (String, nil) (defaults to: nil)

    optional spell name to check

Returns:

  • (Boolean)

    true if the spell is prepared



1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
# File 'documented/global_defs.rb', line 1710

def checkprep(spell = nil)
  if spell.nil?
    XMLData.prepared_spell
  elsif !spell.is_a?(String)
    echo("Checkprep error, spell # not implemented!  You must use the spell name")
    false
  else
    XMLData.prepared_spell =~ /^#{spell}/i
  end
end

#checkproneBoolean

Checks if the character is prone.

Returns:

  • (Boolean)

    true if prone



485
486
487
# File 'documented/global_defs.rb', line 485

def checkprone
  XMLData.indicator['IconPRONE'] == 'y'
end

#checkreallybleedingBoolean

Checks if the character is really bleeding (not affected by certain spells).

Returns:

  • (Boolean)

    true if really bleeding



450
451
452
# File 'documented/global_defs.rb', line 450

def checkreallybleeding
  checkbleeding and !(Spell[9909].active? or Spell[9905].active?)
end

#checkright(*hand) ⇒ String? Also known as: righthand?, righthand

Checks the right hand for specified items.

Parameters:

  • hand (Array<String>)

    optional items to check for

Returns:

  • (String, nil)

    item found or nil if empty



1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
# File 'documented/global_defs.rb', line 1638

def checkright(*hand)
  if GameObj.right_hand.nil? then return nil end

  hand.flatten!
  if GameObj.right_hand.name == "Empty" or GameObj.right_hand.name.empty?
    nil
  elsif hand.empty?
    GameObj.right_hand.noun
  else
    hand.find { |instance| GameObj.right_hand.name =~ /#{instance}/i }
  end
end

#checkroom(*strings) ⇒ Boolean, String

Checks the current room against specified strings.

Parameters:

  • strings (Array<String>)

    room names to check against

Returns:

  • (Boolean, String)

    true if a match is found, or the room title if no parameters are provided



1492
1493
1494
1495
1496
1497
1498
1499
# File 'documented/global_defs.rb', line 1492

def checkroom(*strings)
  strings.flatten!
  if strings.empty?
    XMLData.room_title.chomp
  else
    XMLData.room_title =~ /#{strings.join('|')}/i
  end
end

#checkroomdescrip(*val) ⇒ Boolean, String Also known as: roomdescription?

Checks the room description against specified strings.

Parameters:

  • val (Array<String>)

    strings to check against

Returns:

  • (Boolean, String)

    true if a match is found, or the room description if no parameters are provided



1672
1673
1674
1675
1676
1677
1678
1679
# File 'documented/global_defs.rb', line 1672

def checkroomdescrip(*val)
  val.flatten!
  if val.empty?
    return XMLData.room_description
  else
    return XMLData.room_description =~ /#{val.join('|')}/i
  end
end

#checkrtInteger

Checks the current roundtime.

Returns:

  • (Integer)

    current roundtime value



369
370
371
# File 'documented/global_defs.rb', line 369

def checkrt
  [0, XMLData.roundtime_end.to_f - Time.now.to_f + XMLData.server_time_offset.to_f].max
end

#checksaturatedBoolean Also known as: saturated?

Checks if the character is saturated mentally.

Returns:

  • (Boolean)

    true if saturated



1223
1224
1225
1226
1227
1228
1229
# File 'documented/global_defs.rb', line 1223

def checksaturated
  if XMLData.mind_text =~ /saturated/
    true
  else
    false
  end
end

#checksilencedBoolean

Checks if the character is silenced.

Returns:

  • (Boolean)

    true if silenced



1777
1778
1779
1780
# File 'documented/global_defs.rb', line 1777

def checksilenced
  return Status.silenced? if XMLData.game =~ /GS/
  fail "Error: toplevel checksilenced command not enabled in #{XMLData.game}"
end

#checksittingBoolean Also known as: sitting?

Checks if the character is sitting.

Returns:

  • (Boolean)

    true if sitting



414
415
416
# File 'documented/global_defs.rb', line 414

def checksitting
  XMLData.indicator['IconSITTING'] == 'y'
end

#checksleepingBoolean

Checks if the character is sleeping.

Returns:

  • (Boolean)

    true if sleeping



1749
1750
1751
1752
# File 'documented/global_defs.rb', line 1749

def checksleeping
  return Status.sleeping? if XMLData.game =~ /GS/
  fail "Error: toplevel checksleeping command not enabled in #{XMLData.game}"
end

#checkspell(*spells) ⇒ Boolean Also known as: active?, checkactive

Checks if specified spells are active.

Parameters:

  • spells (Array<String>)

    spell names to check

Returns:

  • (Boolean)

    true if all specified spells are active



1698
1699
1700
1701
1702
1703
1704
# File 'documented/global_defs.rb', line 1698

def checkspell(*spells)
  spells.flatten!
  return false if Spell.active.empty?

  spells.each { |spell| return false unless Spell[spell].active? }
  true
end

#checkspirit(num = nil) ⇒ Boolean Also known as: spirit, spirit?

Checks the character's spirit against a specified number.

Parameters:

  • num (Integer, nil) (defaults to: nil)

    optional number to compare against

Returns:

  • (Boolean)

    true if spirit is greater than or equal to num



1306
1307
1308
1309
1310
1311
1312
1313
# File 'documented/global_defs.rb', line 1306

def checkspirit(num = nil)
  Lich.deprecated('checkspirit', 'Char.spirit')
  if num.nil?
    XMLData.spirit
  else
    XMLData.spirit >= num.to_i
  end
end

#checkstamina(num = nil) ⇒ Boolean Also known as: stamina, stamina?

Checks the character's stamina against a specified number.

Parameters:

  • num (Integer, nil) (defaults to: nil)

    optional number to compare against

Returns:

  • (Boolean)

    true if stamina is greater than or equal to num



1339
1340
1341
1342
1343
1344
1345
1346
# File 'documented/global_defs.rb', line 1339

def checkstamina(num = nil)
  Lich.deprecated('checkstamina', 'Char.stamina')
  if num.nil?
    XMLData.stamina
  else
    XMLData.stamina >= num.to_i
  end
end

#checkstance(num = nil) ⇒ Boolean Also known as: stance?, stance

Checks the character's stance against a specified number.

Parameters:

  • num (Integer, nil) (defaults to: nil)

    optional number to compare against

Returns:

  • (Boolean)

    true if stance value matches num



1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
# File 'documented/global_defs.rb', line 1400

def checkstance(num = nil)
  Lich.deprecated('checkstance', 'Char.stance')
  if num.nil?
    XMLData.stance_text
  elsif (num.is_a?(String)) and (num.to_i == 0)
    if num =~ /off/i
      XMLData.stance_value == 0
    elsif num =~ /adv/i
      XMLData.stance_value.between?(01, 20)
    elsif num =~ /for/i
      XMLData.stance_value.between?(21, 40)
    elsif num =~ /neu/i
      XMLData.stance_value.between?(41, 60)
    elsif num =~ /gua/i
      XMLData.stance_value.between?(61, 80)
    elsif num =~ /def/i
      XMLData.stance_value == 100
    else
      echo "checkstance: invalid argument (#{num}).  Must be off/adv/for/neu/gua/def or 0-100"
      nil
    end
  elsif (num.is_a?(Integer)) or (num =~ /^[0-9]+$/ and (num = num.to_i))
    XMLData.stance_value == num.to_i
  else
    echo "checkstance: invalid argument (#{num}).  Must be off/adv/for/neu/gua/def or 0-100"
    nil
  end
end

#checkstandingBoolean Also known as: standing?

Checks if the character is standing.

Returns:

  • (Boolean)

    true if standing



497
498
499
# File 'documented/global_defs.rb', line 497

def checkstanding
  XMLData.indicator['IconSTANDING'] == 'y'
end

#checkstunnedBoolean Also known as: stunned?

Checks if the character is stunned.

Returns:

  • (Boolean)

    true if stunned



426
427
428
# File 'documented/global_defs.rb', line 426

def checkstunned
  XMLData.indicator['IconSTUNNED'] == 'y'
end

#checkwebbedBoolean Also known as: webbed?

Checks if the character is webbed.

Returns:

  • (Boolean)

    true if webbed



479
480
481
# File 'documented/global_defs.rb', line 479

def checkwebbed
  XMLData.indicator['IconWEBBED'] == 'y'
end

#clear(_opt = 0) ⇒ Array<String>

Clears the output buffer for the current script.

Returns:

  • (Array<String>)

    cleared output



1861
1862
1863
1864
1865
1866
# File 'documented/global_defs.rb', line 1861

def clear(_opt = 0)
  unless (script = Script.current) then respond('--- clear: Unable to identify calling script.'); return false; end
  to_return = script.downstream_buffer.dup
  script.downstream_buffer.clear
  to_return
end

#count_npcsInteger

Counts the number of NPCs in the game.

Returns:

  • (Integer)

    number of NPCs



1630
1631
1632
# File 'documented/global_defs.rb', line 1630

def count_npcs
  checknpcs.length
end

#cutthroat?Boolean

Checks if the character is cutthroat.

Returns:

  • (Boolean)

    true if cutthroat



1812
1813
1814
1815
# File 'documented/global_defs.rb', line 1812

def cutthroat?
  return Status.cutthroat? if XMLData.game =~ /GS/
  fail "Error: toplevel cutthroat? command not enabled in #{XMLData.game}"
end

#dString

Returns the string representation of the direction 'down'.

Returns:



769
# File 'documented/global_defs.rb', line 769

def d;    'down';      end

#debug(*args) ⇒ void

This method returns an undefined value.

Outputs debug information if debugging is enabled.

Parameters:

  • args (Array)

    arguments to output



532
533
534
535
536
537
538
539
540
# File 'documented/global_defs.rb', line 532

def debug(*args)
  if $LICH_DEBUG
    if block_given?
      yield(*args)
    else
      echo(*args)
    end
  end
end

#dec2bin(n) ⇒ String

Converts a decimal number to binary string representation.

Parameters:

  • n (Integer)

    the decimal number to convert

Returns:

  • (String)

    binary representation of the number



554
555
556
# File 'documented/global_defs.rb', line 554

def dec2bin(n)
  "0" + [n].pack("N").unpack("B32")[0].sub(/^0+(?=\d)/, '')
end

#die_with_me(*vals) ⇒ void

This method returns an undefined value.

Registers scripts to die when the current script dies.

Parameters:

  • vals (Array<String>)

    names of scripts to register



626
627
628
629
630
631
# File 'documented/global_defs.rb', line 626

def die_with_me(*vals)
  unless (script = Script.current) then echo 'die_with_me: cannot identify calling script.'; return nil; end
  script.die_with.push vals
  script.die_with.flatten!
  echo("The following script(s) will now die when I do: #{script.die_with.join(', ')}") unless script.die_with.empty?
end

#display_args(defn) ⇒ void

This method returns an undefined value.

Displays the arguments based on a definition.

Parameters:

  • defn (String)

    the argument definition



103
104
105
# File 'documented/global_defs.rb', line 103

def display_args(defn)
  Lich::Common::ArgParser.new.display_args(defn)
end

#do_client(client_string) ⇒ void

This method returns an undefined value.

Processes a client command string and executes the appropriate action.

Parameters:

  • client_string (String)

    command string from the client



2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
# File 'documented/global_defs.rb', line 2795

def do_client(client_string)
  client_string.strip!
  #   Buffer.update(client_string, Buffer::UPSTREAM)
  client_string = UpstreamHook.run(client_string)
  #   Buffer.update(client_string, Buffer::UPSTREAM_MOD)
  return nil if client_string.nil?

  if client_string =~ /^(?:<c>)?#{$lich_char_regex}(.+)$/
    cmd = $1
    if cmd =~ /^k$|^kill$|^stop$/
      if Script.running.empty?
        respond '--- Lich: no scripts to kill'
      else
        Script.running.last.kill
      end
    elsif cmd =~ /^p$|^pause$/
      if (s = Script.running.reverse.find { |s_check| not s_check.paused? })
        s.pause
      else
        respond '--- Lich: no scripts to pause'
      end
      nil
    elsif cmd =~ /^u$|^unpause$/
      if (s = Script.running.reverse.find { |s_check| s_check.paused? })
        s.unpause
      else
        respond '--- Lich: no scripts to unpause'
      end
      nil
    elsif cmd =~ /^ka$|^kill\s?all$|^stop\s?all$/
      did_something = false
      Script.running.find_all { |s_check| not s_check.no_kill_all }.each { |s_check| s_check.kill; did_something = true }
      respond('--- Lich: no scripts to kill') unless did_something
    elsif cmd =~ /^pa$|^pause\s?all$/
      did_something = false
      Script.running.find_all { |s_check| not s_check.paused? and not s_check.no_pause_all }.each { |s_check| s_check.pause; did_something = true }
      respond('--- Lich: no scripts to pause') unless did_something
    elsif cmd =~ /^ua$|^unpause\s?all$/
      did_something = false
      Script.running.find_all { |s_check| s_check.paused? and not s_check.no_pause_all }.each { |s_check| s_check.unpause; did_something = true }
      respond('--- Lich: no scripts to unpause') unless did_something
    elsif cmd =~ /^(k|kill|stop|p|pause|u|unpause)\s(.+)/
      action = $1
      target = $2
      script = Script.running.find { |s_running| s_running.name == target } || Script.hidden.find { |s_hidden| s_hidden.name == target } || Script.running.find { |s_running| s_running.name =~ /^#{target}/i } || Script.hidden.find { |s_hidden| s_hidden.name =~ /^#{target}/i }
      if script.nil?
        respond "--- Lich: #{target} does not appear to be running! Use '#{$clean_lich_char}list' or '#{$clean_lich_char}listall' to see what's active."
      elsif action =~ /^(?:k|kill|stop)$/
        script.kill
      elsif action =~ /^(?:p|pause)$/
        script.pause
      elsif action =~ /^(?:u|unpause)$/
        script.unpause
      end
      target = nil
    elsif cmd =~ /^list\s?(?:all)?$|^l(?:a)?$/i
      if cmd =~ /a(?:ll)?/i
        list = Script.running + Script.hidden
      else
        list = Script.running
      end
      if list.empty?
        respond '--- Lich: no active scripts'
      else
        respond "--- Lich: #{list.collect { |active| active.paused? ? "#{active.name} (paused)" : active.name }.join(", ")}"
      end
      nil
    elsif cmd =~ /^force\s+[^\s]+/
      if cmd =~ /^force\s+([^\s]+)\s+(.+)$/
        Script.start($1, $2, :force => true)
      elsif cmd =~ /^force\s+([^\s]+)/
        Script.start($1, :force => true)
      end
    elsif cmd =~ /^send |^s /
      if cmd.split[1] == "to"
        script = (Script.running + Script.hidden).find { |scr| scr.name == cmd.split[2].chomp.strip } || script = (Script.running + Script.hidden).find { |scr| scr.name =~ /^#{cmd.split[2].chomp.strip}/i }
        if script
          msg = cmd.split[3..-1].join(' ').chomp
          if script.want_downstream
            script.downstream_buffer.push(msg)
          else
            script.unique_buffer.push(msg)
          end
          respond "--- sent to '#{script.name}': #{msg}"
        else
          respond "--- Lich: '#{cmd.split[2].chomp.strip}' does not match any active script!"
        end
        nil
      else
        if Script.running.empty? and Script.hidden.empty?
          respond('--- Lich: no active scripts to send to.')
        else
          msg = cmd.split[1..-1].join(' ').chomp
          respond("--- sent: #{msg}")
          Script.new_downstream(msg)
        end
      end
    elsif cmd =~ /^(?:exec|e)(q)? (.+)$/
      cmd_data = $2
      ExecScript.start(cmd_data, { :quiet => $1 })
    elsif cmd =~ /^(?:execname|en) ([\w\d-]+) (.+)$/
      execname = $1
      cmd_data = $2
      ExecScript.start(cmd_data, { :name => execname })
    elsif cmd =~ /^trust\s+(.*)/i
      script_name = $1
      if RUBY_VERSION =~ /^2\.[012]\./
        if File.exist?("#{SCRIPT_DIR}/#{script_name}.lic")
          if Script.trust(script_name)
            respond "--- Lich: '#{script_name}' is now a trusted script."
          else
            respond "--- Lich: '#{script_name}' is already trusted."
          end
        else
          respond "--- Lich: could not find script: #{script_name}"
        end
      else
        respond "--- Lich: this feature isn't available in this version of Ruby "
      end
    elsif cmd =~ /^(?:dis|un)trust\s+(.*)/i
      script_name = $1
      if RUBY_VERSION =~ /^2\.[012]\./
        if Script.distrust(script_name)
          respond "--- Lich: '#{script_name}' is no longer a trusted script."
        else
          respond "--- Lich: '#{script_name}' was not found in the trusted script list."
        end
      else
        respond "--- Lich: this feature isn't available in this version of Ruby "
      end
    elsif cmd =~ /^list\s?(?:un)?trust(?:ed)?$|^lt$/i
      if RUBY_VERSION =~ /^2\.[012]\./
        list = Script.list_trusted
        if list.empty?
          respond "--- Lich: no scripts are trusted"
        else
          respond "--- Lich: trusted scripts: #{list.join(', ')}"
        end
        nil
      else
        respond "--- Lich: this feature isn't available in this version of Ruby "
      end
    elsif cmd =~ /^set\s(.+)\s(on|off)/
      toggle_var = $1
      set_state = $2
      did_something = false
      begin
        Lich.db.execute("INSERT OR REPLACE INTO lich_settings(name,value) values(?,?);", [toggle_var.to_s.encode('UTF-8'), set_state.to_s.encode('UTF-8')])
        did_something = true
      rescue SQLite3::BusyException
        sleep 0.1
        retry
      end
      respond("--- Lich: toggle #{toggle_var} set #{set_state}") if did_something
      did_something = false
      nil
    elsif cmd =~ /^hmr\s+(?<pattern>.*)/i
      begin
        HMR.reload %r{#{Regexp.last_match[:pattern]}}
      rescue ArgumentError
        if $!.to_s == 'invalid Unicode escape'
          respond "--- Lich: error: invalid Unicode escape"
          respond "--- Lich:   cmd: #{cmd}"
          respond "--- Lich: \\u is unicode escape, did you mean to use a / instead?"
        else
          respond "--- Lich: error: #{$!}\n\t#{$!.backtrace[0..1].join("\n\t")}"
          Lich.log "error: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
        end
      end
    elsif XMLData.game =~ /^GS/ && cmd =~ /^infomon sync/i
      ExecScript.start("Infomon.sync", { :quiet => true })
    elsif XMLData.game =~ /^GS/ && cmd =~ /^infomon (?:reset|redo)!?/i
      ExecScript.start("Infomon.redo!", { :quiet => true })
    elsif XMLData.game =~ /^GS/ && cmd =~ /^infomon show( full)?/i
      case Regexp.last_match(1)
      when 'full'
        Infomon.show(true)
      else
        Infomon.show(false)
      end
    elsif XMLData.game =~ /^GS/ && cmd =~ /^infomon effects?(?: (true|false))?/i
      new_value = !(Infomon.get_bool("infomon.show_durations"))
      case Regexp.last_match(1)
      when 'true'
        new_value = true
      when 'false'
        new_value = false
      end
      respond "Changing Infomon's effect duration showing to #{new_value}"
      Infomon.set('infomon.show_durations', new_value)
    elsif XMLData.game =~ /^GS/ && cmd =~ /^sk\b(?: (add|rm|list|help)(?: ([\d\s]+))?)?/i
      SK.main(Regexp.last_match(1), Regexp.last_match(2))
    elsif XMLData.game =~ /^DR/ && cmd =~ /^display flaguid(?: (true|false))?/i
      new_value = !(Lich.hide_uid_flag)
      case Regexp.last_match(1)
      when 'true'
        new_value = true
      when 'false'
        new_value = false
      end
      respond "Changing Lich to NOT display Room Title RealIDs while FLAG ShowRoomID ON to #{new_value}"
      Lich.hide_uid_flag = new_value
    elsif cmd =~ /^display lichid(?: (true|false))?/i
      new_value = !(Lich.display_lichid)
      case Regexp.last_match(1)
      when 'true'
        new_value = true
      when 'false'
        new_value = false
      end
      respond "Changing Lich to display Lich ID#s to #{new_value}"
      Lich.display_lichid = new_value
    elsif cmd =~ /^display uid(?: (true|false))?/i
      new_value = !(Lich.display_uid)
      case Regexp.last_match(1)
      when 'true'
        new_value = true
      when 'false'
        new_value = false
      end
      respond "Changing Lich to display RealID#s to #{new_value}"
      Lich.display_uid = new_value
    elsif cmd =~ /^display exits?(?: (true|false))?/i
      new_value = !(Lich.display_exits)
      case Regexp.last_match(1)
      when 'true'
        new_value = true
      when 'false'
        new_value = false
      end
      respond "Changing Lich to display Room Exits of non-StringProc/Obvious exits to #{new_value}"
      Lich.display_exits = new_value
    elsif cmd =~ /^display stringprocs?(?: (true|false))?/i
      new_value = !(Lich.display_stringprocs)
      case Regexp.last_match(1)
      when 'true'
        new_value = true
      when 'false'
        new_value = false
      end
      respond "Changing Lich to display Room Exits of StringProcs to #{new_value}"
      Lich.display_stringprocs = new_value
    elsif XMLData.game =~ /^DR/ && (expgains_match = cmd.match(/^display expgains?(?: (?<toggle>true|false|on|off))?$/i))
      if running?('exp-monitor')
        respond "Error: exp-monitor.lic script is currently running"
        respond "Stop it first with: #{$clean_lich_char}kill exp-monitor"
      else
        new_value = !Lich.display_expgains
        case expgains_match[:toggle]
        when 'true', 'on'
          new_value = true
        when 'false', 'off'
          new_value = false
        end
        Lich.display_expgains = new_value
        if new_value
          respond "Enabling real-time experience gain reporting"
          DRExpMonitor.start
        else
          respond "Disabling real-time experience gain reporting"
          DRExpMonitor.stop
        end
      end
    elsif XMLData.game =~ /^DR/ && (inlineexp_match = cmd.match(/^display inlineexp(?: (?<toggle>true|false|on|off))?$/i))
      new_value = !DRExpMonitor.inline_display?
      case inlineexp_match[:toggle]
      when 'true', 'on'
        new_value = true
      when 'false', 'off'
        new_value = false
      end
      DRExpMonitor.inline_display = new_value
      if new_value
        respond "Enabling inline experience display (gained ranks shown in exp window)"
      else
        respond "Disabling inline experience display"
      end
    elsif XMLData.game =~ /^DR/ && cmd =~ /^display exp-status$/i
      respond
      respond "DragonRealms Experience Monitor Status:"
      respond "  expgains:   #{Lich.display_expgains ? 'ON' : 'OFF'}  (real-time gain messages)"
      respond "  inlineexp:  #{DRExpMonitor.inline_display? ? 'ON' : 'OFF'}  (cumulative gains in EXP window)"
      respond "  reporter:   #{DRExpMonitor.active? ? 'RUNNING' : 'STOPPED'}"
      respond
      respond "Commands:"
      respond "  #{$clean_lich_char}display expgains [on|off]    toggle gain messages"
      respond "  #{$clean_lich_char}display inlineexp [on|off]   toggle inline display"
      respond
    elsif (debuglogs_match = cmd.match(/^debuglogs?\s+(?<val>\d+)$/i))
      new_limit = debuglogs_match[:val].to_i
      Lich.max_debug_logs = new_limit
      respond "--- Lich: debug log retention set to #{Lich.max_debug_logs} files"
    elsif cmd =~ /^debuglogs?$/i
      respond
      respond "--- Lich: Debug Log Retention ---"
      respond "  Current limit:  #{Lich.max_debug_logs} files"
      respond "  Default:        #{Lich::MAX_DEBUG_LOGS_DEFAULT} files"
      respond
      respond "Usage:"
      respond "  #{$clean_lich_char}debuglogs            show current setting"
      respond "  #{$clean_lich_char}debuglogs <number>   set retention limit"
      respond
    elsif cmd =~ /^debuglogs?\b/i
      respond "--- Lich: invalid argument. Usage: #{$clean_lich_char}debuglogs [number]"
    elsif cmd =~ /^(?:lich5-update|l5u)\s+(.*)/i
      update_parameter = $1.dup
      Lich::Util::Update.request("#{update_parameter}")
    elsif cmd =~ /^(?:lich5-update|l5u)/i
      Lich::Util::Update.request("--help")
    elsif cmd =~ /^banks$/ && XMLData.game =~ /^GS/
      Game._puts "<c>bank account"
      $_CLIENTBUFFER_.push "<c>bank account"
    elsif XMLData.game =~ /^DR/ && (banks_match = cmd.match(/^banks(?: (all|reset|reset all))?$/i))
      case banks_match[1]&.downcase
      when 'all'
        Lich::DragonRealms::DRBanking.display_banks_all
      when 'reset'
        Lich::DragonRealms::DRBanking.reset_character!
      when 'reset all'
        Lich::DragonRealms::DRBanking.reset_all!
      else
        Lich::DragonRealms::DRBanking.display_banks
      end
    elsif cmd =~ /^magic$/ && XMLData.game =~ /^GS/
      Effects.display
    elsif cmd =~ /^help$/i
      respond
      respond "Lich v#{LICH_VERSION}"
      respond
      respond 'built-in commands:'
      respond "   #{$clean_lich_char}<script name>             start a script"
      respond "   #{$clean_lich_char}force <script name>       start a script even if it's already running"
      respond "   #{$clean_lich_char}pause <script name>       pause a script"
      respond "   #{$clean_lich_char}p <script name>           ''"
      respond "   #{$clean_lich_char}unpause <script name>     unpause a script"
      respond "   #{$clean_lich_char}u <script name>           ''"
      respond "   #{$clean_lich_char}kill <script name>        kill a script"
      respond "   #{$clean_lich_char}k <script name>           ''"
      respond "   #{$clean_lich_char}pause                     pause the most recently started script that isn't aready paused"
      respond "   #{$clean_lich_char}p                         ''"
      respond "   #{$clean_lich_char}unpause                   unpause the most recently started script that is paused"
      respond "   #{$clean_lich_char}u                         ''"
      respond "   #{$clean_lich_char}kill                      kill the most recently started script"
      respond "   #{$clean_lich_char}k                         ''"
      respond "   #{$clean_lich_char}list                      show running scripts (except hidden ones)"
      respond "   #{$clean_lich_char}l                         ''"
      respond "   #{$clean_lich_char}pause all                 pause all scripts"
      respond "   #{$clean_lich_char}pa                        ''"
      respond "   #{$clean_lich_char}unpause all               unpause all scripts"
      respond "   #{$clean_lich_char}ua                        ''"
      respond "   #{$clean_lich_char}kill all                  kill all scripts"
      respond "   #{$clean_lich_char}ka                        ''"
      respond "   #{$clean_lich_char}list all                  show all running scripts"
      respond "   #{$clean_lich_char}la                        ''"
      respond
      respond "   #{$clean_lich_char}exec <code>               executes the code as if it was in a script"
      respond "   #{$clean_lich_char}e <code>                  ''"
      respond "   #{$clean_lich_char}execq <code>              same as #{$clean_lich_char}exec but without the script active and exited messages"
      respond "   #{$clean_lich_char}eq <code>                 ''"
      respond "   #{$clean_lich_char}execname <name> <code>    creates named exec (name#) and then executes the code as if it was in a script"
      respond
      if (RUBY_VERSION =~ /^2\.[012]\./)
        respond "   #{$clean_lich_char}trust <script name>       let the script do whatever it wants"
        respond "   #{$clean_lich_char}distrust <script name>    restrict the script from doing things that might harm your computer"
        respond "   #{$clean_lich_char}list trusted              show what scripts are trusted"
        respond "   #{$clean_lich_char}lt                        ''"
        respond
      end
      respond "   #{$clean_lich_char}send <line>               send a line to all scripts as if it came from the game"
      respond "   #{$clean_lich_char}send to <script> <line>   send a line to a specific script"
      respond
      respond "   #{$clean_lich_char}set <variable> [on|off]   set a global toggle variable on or off"
      respond "   #{$clean_lich_char}debuglogs                 show debug log retention setting"
      respond "   #{$clean_lich_char}debuglogs <number>        set how many debug logs to keep (default: #{Lich::MAX_DEBUG_LOGS_DEFAULT})"
      respond
      respond "   #{$clean_lich_char}lich5-update --<command>  Lich5 ecosystem management "
      respond "                              see #{$clean_lich_char}lich5-update --help"
      respond "   #{$clean_lich_char}hmr <regex filepath>      Hot module reload a Ruby or Lich5 file without relogging, uses Regular Expression matching"
      if XMLData.game =~ /^GS/
        respond
        respond "   #{$clean_lich_char}infomon sync              sends all the various commands to resync character data for infomon (fixskill)"
        respond "   #{$clean_lich_char}infomon reset             resets entire character infomon db table and then syncs data (fixprof)"
        respond "   #{$clean_lich_char}infomon effects           toggle display of effect durations"
        respond "   #{$clean_lich_char}infomon show              shows all current Infomon values for character"
        respond "   #{$clean_lich_char}sk help                   show information on modifying self-knowledge spells to be known"
      elsif XMLData.game =~ /^DR/
        respond "   #{$clean_lich_char}display flaguid           toggle display of RealID in Room Title with FLAG ShowRoomID (required for Lich5 to be ON)"
      end
      respond "   #{$clean_lich_char}display lichid            toggle display of Lich Map# when displaying room information"
      respond "   #{$clean_lich_char}display uid               toggle display of RealID Map# when displaying room information"
      respond "   #{$clean_lich_char}display exits             toggle display of non-StringProc/Obvious exits known for room in mapdb"
      respond "   #{$clean_lich_char}display stringprocs       toggle display of StringProc exits known for room in mapdb if timeto is valid"
      if XMLData.game =~ /^DR/
        respond "   #{$clean_lich_char}display expgains          toggle real-time experience gain reporting (DragonRealms only)"
        respond "   #{$clean_lich_char}display inlineexp         toggle inline exp display in EXP window (DragonRealms only)"
        respond "   #{$clean_lich_char}display exp-status        show experience monitor status (DragonRealms only)"
        respond "   #{$clean_lich_char}banks                     show your bank balances (DragonRealms only)"
        respond "   #{$clean_lich_char}banks all                 show bank balances for all characters (DragonRealms only)"
        respond "   #{$clean_lich_char}banks reset               clear your bank data (DragonRealms only)"
        respond "   #{$clean_lich_char}banks reset all           clear all characters' bank data (DragonRealms only)"
      end
      respond
      respond 'If you liked this help message, you might also enjoy:'
      respond "   #{$clean_lich_char}lnet help" if defined?(LNet)
      respond "   #{$clean_lich_char}go2 help"
      respond "   #{$clean_lich_char}repository help"
      respond "   #{$clean_lich_char}alias help"
      respond "   #{$clean_lich_char}vars help"
      respond "   #{$clean_lich_char}autostart help"
      respond
    else
      if cmd =~ /^([^\s]+)\s+(.+)/
        Script.start($1, $2)
      else
        Script.start(cmd)
      end
    end
  else
    if $offline_mode
      respond "--- Lich: offline mode: ignoring #{client_string}"
    else
      client_string = "#{$cmd_prefix}bbs" if Frontend.supports_gsl? and (client_string == "#{$cmd_prefix}\egbbk\n") # launch forum
      Game._puts client_string
    end
    $_CLIENTBUFFER_.push client_string
  end
  Script.new_upstream(client_string)
end

#dothis(action, success_line) ⇒ String

Executes an action and waits for a success line.

Parameters:

  • action (String)

    action to perform

  • success_line (String)

    line indicating success

Returns:

  • (String)

    success line received



2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
# File 'documented/global_defs.rb', line 2500

def dothis(action, success_line)
  loop {
    Script.current.clear
    put action
    loop {
      line = get
      if line =~ success_line
        return line
      elsif line =~ /^(\.\.\.w|W)ait ([0-9]+) sec(onds)?\.$/
        if $2.to_i > 1
          sleep($2.to_i - "0.5".to_f)
        else
          sleep 0.3
        end
        break
      elsif line == 'Sorry, you may only type ahead 1 command.'
        sleep 1
        break
      elsif line == 'You are still stunned.'
        wait_while { stunned? }
        break
      elsif line == 'That is impossible to do while unconscious!'
        100.times {
          unless (line = get?)
            sleep 0.1
          else
            break if line =~ /Your thoughts slowly come back to you as you find yourself lying on the ground\.  You must have been sleeping\.$|^You wake up from your slumber\.$/
          end
        }
        break
      elsif line == "You don't seem to be able to move to do that."
        100.times {
          unless (line = get?)
            sleep 0.1
          else
            break if line == 'The restricting force that envelops you dissolves away.'
          end
        }
        break
      elsif line == "You can't do that while entangled in a web."
        wait_while { checkwebbed }
        break
      elsif line == 'You find that impossible under the effects of the lullabye.'
        100.times {
          unless (line = get?)
            sleep 0.1
          else
            # fixme
            break if line == 'You shake off the effects of the lullabye.'
          end
        }
        break
      end
    }
  }
end

#dothistimeout(action, timeout, success_line) ⇒ String?

Executes an action with a timeout and waits for a success line.

Parameters:

  • action (String)

    action to perform

  • timeout (Integer)

    timeout duration in seconds

  • success_line (String)

    line indicating success

Returns:

  • (String, nil)

    success line received or nil on timeout



2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
# File 'documented/global_defs.rb', line 2563

def dothistimeout(action, timeout, success_line)
  end_time = Time.now.to_f + timeout
  line = nil
  loop {
    Script.current.clear
    put action unless action.nil?
    loop {
      line = get?
      if line.nil?
        sleep 0.1
      elsif line =~ success_line
        return line
      elsif line =~ /^(\.\.\.w|W)ait ([0-9]+) sec(onds)?\.$/
        if $2.to_i > 1
          sleep($2.to_i - "0.5".to_f)
        else
          sleep 0.3
        end
        end_time = Time.now.to_f + timeout
        break
      elsif line == 'Sorry, you may only type ahead 1 command.'
        sleep 1
        end_time = Time.now.to_f + timeout
        break
      elsif line == 'You are still stunned.'
        wait_while { stunned? }
        end_time = Time.now.to_f + timeout
        break
      elsif line == 'That is impossible to do while unconscious!'
        100.times {
          unless (line = get?)
            sleep 0.1
          else
            break if line =~ /Your thoughts slowly come back to you as you find yourself lying on the ground\.  You must have been sleeping\.$|^You wake up from your slumber\.$/
          end
        }
        break
      elsif line == "You don't seem to be able to move to do that."
        100.times {
          unless (line = get?)
            sleep 0.1
          else
            break if line == 'The restricting force that envelops you dissolves away.'
          end
        }
        break
      elsif line == "You can't do that while entangled in a web."
        wait_while { checkwebbed }
        break
      elsif line == 'You find that impossible under the effects of the lullabye.'
        100.times {
          unless (line = get?)
            sleep 0.1
          else
            # fixme
            break if line == 'You shake off the effects of the lullabye.'
          end
        }
        break
      end
      if Time.now.to_f >= end_time
        return nil
      end
    }
  }
end

#downString

Returns the string representation of the direction 'down'.

Returns:



765
# File 'documented/global_defs.rb', line 765

def down; 'down';      end

#eString

Returns the string representation of the direction 'east'.

Returns:



733
# File 'documented/global_defs.rb', line 733

def e;    'east';      end

#echo(*messages) ⇒ void

This method returns an undefined value.

Sends a message to the script's output.

Parameters:

  • messages (Array<String>)

    messages to send



257
258
259
260
261
262
263
264
265
266
267
# File 'documented/global_defs.rb', line 257

def echo(*messages)
  respond if messages.empty?
  if (script = Script.current)
    unless script.no_echo
      messages.each { |message| respond("[#{script.custom? ? 'custom/' : ''}#{script.name}: #{message.to_s.chomp}]") }
    end
  else
    messages.each { |message| respond("[(unknown script): #{message.to_s.chomp}]") }
  end
  nil
end

#echo_offvoid

This method returns an undefined value.

Turns off the echo setting for the current script.



225
226
227
228
# File 'documented/global_defs.rb', line 225

def echo_off
  unless (script = Script.current) then respond('--- echo_off: Unable to identify calling script.'); return nil; end
  script.no_echo = true
end

#echo_onvoid

This method returns an undefined value.

Turns on the echo setting for the current script.



218
219
220
221
# File 'documented/global_defs.rb', line 218

def echo_on
  unless (script = Script.current) then respond('--- echo_on: Unable to identify calling script.'); return nil; end
  script.no_echo = false
end

#empty_handObject



2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
# File 'documented/global_defs.rb', line 2442

def empty_hand
  right_hand = GameObj.right_hand
  left_hand = GameObj.left_hand

  unless (right_hand.id.nil? and ([Wounds.rightArm, Wounds.rightHand, Scars.rightArm, Scars.rightHand].max < 3)) or (left_hand.id.nil? and ([Wounds.leftArm, Wounds.leftHand, Scars.leftArm, Scars.leftHand].max < 3))
    if right_hand.id and ([Wounds.rightArm, Wounds.rightHand, Scars.rightArm, Scars.rightHand].max < 3 or [Wounds.leftArm, Wounds.leftHand, Scars.leftArm, Scars.leftHand].max == 3)
      waitrt?
      Lich::Stash::stash_hands(right: true)
    else
      waitrt?
      Lich::Stash::stash_hands(left: true)
    end
  end
end

#empty_handsvoid

This method returns an undefined value.

Empties the character's hand based on conditions.



2437
2438
2439
2440
# File 'documented/global_defs.rb', line 2437

def empty_hands
  waitrt?
  Lich::Stash::stash_hands(both: true)
end

#empty_left_handvoid

This method returns an undefined value.

Empties the character's left hand.



2464
2465
2466
2467
# File 'documented/global_defs.rb', line 2464

def empty_left_hand
  waitrt?
  Lich::Stash::stash_hands(left: true)
end

#empty_right_handObject



2457
2458
2459
2460
# File 'documented/global_defs.rb', line 2457

def empty_right_hand
  waitrt?
  Lich::Stash::stash_hands(right: true)
end

#fb_to_sf(line) ⇒ String?

Converts a line from the front buffer to a string format.

Parameters:

  • line (String)

    line to convert

Returns:

  • (String, nil)

    converted line or nil if empty



2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
# File 'documented/global_defs.rb', line 2639

def fb_to_sf(line)
  begin
    return line if line == "\r\n"

    line = line.gsub(/<c>/, "")
    return nil if line.gsub("\r\n", '').length < 1

    return line
  rescue
    $_CLIENT_.puts "--- Error: fb_to_sf: #{$!}"
    $_CLIENT_.puts "$_SERVERSTRING_: #{$_SERVERSTRING_}"
    Lich.log("--- Error: fb_to_sf: #{$!}\n\t#{$!.backtrace.join("\n\t")}")
    Lich.log("$_SERVERSTRING_: #{$_SERVERSTRING_}")
    Lich.log("Line: #{line}")
  end
end

#fetchloot(userbagchoice = UserVars.lootsack) ⇒ Boolean

Fetches loot from the game object and places it in the user's bag.

Parameters:

  • userbagchoice (String) (defaults to: UserVars.lootsack)

    the name of the bag to store loot in (default is UserVars.lootsack).

Returns:

  • (Boolean)

    returns false if there is no loot to fetch, otherwise returns true.



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
# File 'documented/deprecated.rb', line 31

def fetchloot(userbagchoice = UserVars.lootsack)
  if GameObj.loot.empty?
    return false
  end

  if UserVars.excludeloot.empty?
    regexpstr = nil
  else
    regexpstr = UserVars.excludeloot.split(', ').join('|')
  end
  if checkright and checkleft
    stowed = GameObj.right_hand.noun
    fput "put my #{stowed} in my #{UserVars.lootsack}"
  else
    stowed = nil
  end
  GameObj.loot.each { |loot|
    unless not regexpstr.nil? and loot.name =~ /#{regexpstr}/
      fput "get #{loot.noun}"
      fput("put my #{loot.noun} in my #{userbagchoice}") if (checkright || checkleft)
    end
  }
  if stowed
    fput "take my #{stowed} from my #{UserVars.lootsack}"
  end
end

#fill_handObject



2476
2477
2478
2479
# File 'documented/global_defs.rb', line 2476

def fill_hand
  waitrt?
  Lich::Stash::equip_hands()
end

#fill_handsvoid

This method returns an undefined value.

Fills the character's hand with items based on conditions.



2471
2472
2473
2474
# File 'documented/global_defs.rb', line 2471

def fill_hands
  waitrt?
  Lich::Stash::equip_hands(both: true)
end

#fill_left_handvoid

This method returns an undefined value.

Fills the character's left hand with items.



2490
2491
2492
2493
# File 'documented/global_defs.rb', line 2490

def fill_left_hand
  waitrt?
  Lich::Stash::equip_hands(left: true)
end

#fill_right_handvoid

This method returns an undefined value.

Fills the character's right hand with items.



2483
2484
2485
2486
# File 'documented/global_defs.rb', line 2483

def fill_right_hand
  waitrt?
  Lich::Stash::equip_hands(right: true)
end

#fix_injury_modevoid

This method returns an undefined value.

Ensures the injury mode is set correctly.



325
326
327
328
329
330
# File 'documented/global_defs.rb', line 325

def fix_injury_mode
  unless XMLData.injury_mode == 2
    Game._puts '_injury 2'
    150.times { sleep 0.05; break if XMLData.injury_mode == 2 }
  end
end

#force_start_script(script_name, cli_vars = [], flags = {}) ⇒ void

This method returns an undefined value.

Forces the start of a script, even if it is already running.

Parameters:

  • script_name (String)

    the name of the script to force start

  • cli_vars (Array<String>) (defaults to: [])

    command line variables to pass to the script

  • flags (Hash) (defaults to: {})

    additional flags for script execution



45
46
47
48
49
# File 'documented/global_defs.rb', line 45

def force_start_script(script_name, cli_vars = [], flags = {})
  flags = Hash.new unless flags.is_a?(Hash)
  flags[:force] = true
  start_script(script_name, cli_vars, flags)
end

#fput(message, *waitingfor) ⇒ String? Also known as: forceput

Sends a command to the game and waits for a response matching success or failure patterns.

Parameters:

  • message (String)

    command to send

  • waitingfor (Array<String>)

    patterns for responses

Returns:

  • (String, nil)

    response from the game or nil on timeout



2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
# File 'documented/global_defs.rb', line 2101

def fput(message, *waitingfor)
  unless (script = Script.current) then respond('--- waitfor: Unable to identify calling script.'); return false; end
  waitingfor.flatten!

  # Optional timeout via trailing Hash argument: fput('cmd', 'pattern', timeout: 30)
  # Default 60s prevents infinite hangs when the game stops responding.
  # Use timeout: 0 to disable (original behavior).
  options = (waitingfor.pop if waitingfor.last.is_a?(Hash)) || {}
  timeout = options[:timeout] || options['timeout'] || 60

  clear
  put(message)

  timer = Time.now
  loop do
    string = get?

    if string.nil?
      if timeout > 0 && (Time.now - timer > timeout)
        echo "fput: No game response for #{timeout}s to '#{message}'"
        return false
      end
      pause 0.1
      next
    end

    timer = Time.now # Reset timeout on any game response

    if string =~ /(?:\.\.\.wait |Wait )(?<wait_time>[0-9]+)/
      hold_up = Regexp.last_match[:wait_time].to_i
      sleep(hold_up) unless hold_up.nil?
      clear
      put(message)
      next
    elsif string =~ /^You.+struggle.+stand/
      clear
      fput 'stand'
      next
    elsif string =~ /stunned|can't do that while|cannot seem|^(?!You rummage).*can't seem|don't seem|Sorry, you may only type ahead/
      if dead?
        echo "You're dead...! You can't do that!"
        sleep 1
        script.downstream_buffer.unshift(string)
        return false
      elsif checkstunned
        while checkstunned
          sleep("0.25".to_f)
        end
      elsif checkwebbed
        while checkwebbed
          sleep("0.25".to_f)
        end
      elsif string =~ /Sorry, you may only type ahead/
        sleep 1
      else
        sleep 0.1
        script.downstream_buffer.unshift(string)
        return false
      end
      clear
      put(message)
      next
    else
      if waitingfor.empty?
        script.downstream_buffer.unshift(string)
        return string
      else
        if (foundit = waitingfor.find { |val| string =~ /#{val}/i })
          script.downstream_buffer.unshift(string)
          return foundit
        end
        sleep 1
        clear
        put(message)
        next
      end
    end
  end
end

#getString

Retrieves a line from the script's input.

Returns:

  • (String)

    the line received



2032
2033
2034
# File 'documented/global_defs.rb', line 2032

def get
  Script.current.gets
end

#get?Boolean

Checks if there is a line available from the script's input.

Returns:

  • (Boolean)

    true if a line is available



2038
2039
2040
# File 'documented/global_defs.rb', line 2038

def get?
  Script.current.gets?
end

#get_data(type) ⇒ OpenStruct

Retrieves data of a specified type.

Parameters:

  • type (String)

    the type of data to retrieve

Returns:

  • (OpenStruct)

    the requested data



85
86
87
88
# File 'documented/global_defs.rb', line 85

def get_data(type)
  $setupfiles ||= Lich::Common::SetupFiles.new
  $setupfiles.get_data(type)
end

#get_settings(character_suffixes = []) ⇒ OpenStruct

Retrieves settings for the character based on suffixes.

Parameters:

  • character_suffixes (Array<String>) (defaults to: [])

    suffixes to filter settings

Returns:

  • (OpenStruct)

    settings for the character



76
77
78
79
# File 'documented/global_defs.rb', line 76

def get_settings(character_suffixes = [])
  $setupfiles ||= Lich::Common::SetupFiles.new
  $setupfiles.get_settings(character_suffixes)
end

#goto(label) ⇒ void

This method returns an undefined value.

Jumps to a specified label in the current script.

Parameters:

  • label (String)

    the label to jump to

Raises:



289
290
291
292
# File 'documented/global_defs.rb', line 289

def goto(label)
  Script.current.jump_label = label.to_s
  raise Lich::Common::Script::JUMP
end

#hide_mevoid

This method returns an undefined value.

Toggles the visibility of the current script.



173
174
175
# File 'documented/global_defs.rb', line 173

def hide_me
  Script.current.hidden = !Script.current.hidden
end

#hide_script(*args) ⇒ void

This method returns an undefined value.

Toggles the visibility of specified scripts.

Parameters:

  • args (Array<String>)

    names of scripts to hide



336
337
338
339
340
341
342
343
# File 'documented/global_defs.rb', line 336

def hide_script(*args)
  args.flatten!
  args.each { |name|
    if (script = Script.running.find { |scr| scr.name == name })
      script.hidden = !script.hidden
    end
  }
end

#i_stand_aloneBoolean

Toggles the stand-alone status of the current script.

Returns:

  • (Boolean)

    true if the script stands alone



522
523
524
525
526
# File 'documented/global_defs.rb', line 522

def i_stand_alone
  unless (script = Script.current) then echo 'i_stand_alone: cannot identify calling script.'; return nil; end
  script.want_downstream = !script.want_downstream
  return !script.want_downstream
end

#idle?(time = 60) ⇒ Boolean

Checks if the character has been idle for a specified time.

Parameters:

  • time (Integer) (defaults to: 60)

    the idle time threshold

Returns:

  • (Boolean)

    true if idle



570
571
572
# File 'documented/global_defs.rb', line 570

def idle?(time = 60)
  Time.now - $_IDLETIMESTAMP_ >= time
end

#key_exists?(path) ⇒ 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.

Checks if a registry key exists at the specified path.

Parameters:

  • path (String)

    the registry path to check.

Returns:

  • (Boolean)

    true if the key exists, false otherwise.



65
66
67
68
69
70
# File 'documented/init.rb', line 65

def key_exists?(path)
  Registry.open(Registry::HKEY_LOCAL_MACHINE, path, ::Win32::Registry::KEY_READ)
  true
rescue StandardError
  false
end

#match(label, string) ⇒ String?

Matches a line from the script's input against specified patterns.

Parameters:

  • label (String)

    label to match

  • string (String)

    string to match

Returns:

  • (String, nil)

    matched string or nil if no match



1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
# File 'documented/global_defs.rb', line 1873

def match(label, string)
  strings = [label, string]
  strings.flatten!
  unless (script = Script.current) then echo("An unknown script thread tried to fetch a game line from the queue, but Lich can't process the call without knowing which script is calling! Aborting..."); Thread.current.kill; return false end
  if strings.empty? then echo("Error! 'match' was given no strings to look for!"); sleep 1; return false end
  unless strings.length == 2
    while (line_in = script.gets)
      strings.each { |string|
        if line_in =~ /#{string}/ then return $~.to_s end
      }
    end
  else
    if script.respond_to?(:match_stack_add)
      script.match_stack_add(strings.first.to_s, strings.last)
    else
      script.match_stack_labels.push(strings[0].to_s)
      script.match_stack_strings.push(strings[1])
    end
  end
end

#matchafter(*strings) ⇒ String

Matches a line from the script's input after a specified pattern.

Parameters:

  • strings (Array<String>)

    strings to match

Returns:



1942
1943
1944
1945
1946
1947
1948
# File 'documented/global_defs.rb', line 1942

def matchafter(*strings)
  strings.flatten!
  unless (script = Script.current) then echo("An unknown script thread tried to fetch a game line from the queue, but Lich can't process the call without knowing which script is calling! Aborting..."); Thread.current.kill; return false end
  if strings.empty? then echo("matchafter without any strings to wait for!"); return end
  regexpstr = strings.join('|')
  loop { if (script.gets) =~ /#{regexpstr}/ then return $'.to_s end }
end

#matchbefore(*strings) ⇒ String

Matches a line from the script's input before a specified pattern.

Parameters:

  • strings (Array<String>)

    strings to match

Returns:



1930
1931
1932
1933
1934
1935
1936
# File 'documented/global_defs.rb', line 1930

def matchbefore(*strings)
  strings.flatten!
  unless (script = Script.current) then echo("An unknown script thread tried to fetch a game line from the queue, but Lich can't process the call without knowing which script is calling! Aborting..."); Thread.current.kill; return false end
  if strings.empty? then echo("matchbefore without any strings to wait for!"); return false end
  regexpstr = strings.join('|')
  loop { if (script.gets) =~ /#{regexpstr}/ then return $`.to_s end }
end

#matchboth(*strings) ⇒ Array<String>

Matches a line from the script's input both before and after specified patterns.

Parameters:

  • strings (Array<String>)

    strings to match

Returns:

  • (Array<String>)

    matched strings



1954
1955
1956
1957
1958
1959
1960
1961
# File 'documented/global_defs.rb', line 1954

def matchboth(*strings)
  strings.flatten!
  unless (script = Script.current) then echo("An unknown script thread tried to fetch a game line from the queue, but Lich can't process the call without knowing which script is calling! Aborting..."); Thread.current.kill; return false end
  if strings.empty? then echo("matchboth without any strings to wait for!"); return end
  regexpstr = strings.join('|')
  loop { if (script.gets) =~ /#{regexpstr}/ then break end }
  return [$`.to_s, $'.to_s]
end

#matchfind(*strings) ⇒ String?

Matches a line from the script's input against specified patterns.

Parameters:

  • strings (Array<String>)

    strings to match

Returns:

  • (String, nil)

    matched string or nil if no match



2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
# File 'documented/global_defs.rb', line 2230

def matchfind(*strings)
  regex = /#{strings.flatten.join('|').gsub('?', '(.+)')}/i
  unless (script = Script.current)
    respond "Unknown script is asking to use matchfind!  Cannot process request without identifying the calling script; killing this thread."
    Thread.current.kill
  end
  while true
    if (reobj = regex.match(script.gets))
      ret = reobj.captures.compact
      if ret.length < 2
        return ret.first
      else
        return ret
      end
    end
  end
end

#matchfindexact(*strings) ⇒ String?

Matches a line from the script's input against specified patterns exactly.

Parameters:

  • strings (Array<String>)

    strings to match

Returns:

  • (String, nil)

    matched string or nil if no match



2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
# File 'documented/global_defs.rb', line 2200

def matchfindexact(*strings)
  strings.flatten!
  unless (script = Script.current) then echo("An unknown script thread tried to fetch a game line from the queue, but Lich can't process the call without knowing which script is calling! Aborting..."); Thread.current.kill; return false end
  if strings.empty? then echo("error! 'matchfind' with no strings to look for!"); sleep 1; return false end
  looking = Array.new
  strings.each { |str| looking.push(str.gsub('?', '(\b.+\b)')) }
  if looking.empty? then echo("matchfind without any strings to wait for!"); return false end
  regexpstr = looking.join('|')
  while (line_in = script.gets)
    if (gotit = line_in.slice(/#{regexpstr}/))
      matches = Array.new
      looking.each_with_index { |str, idx|
        if gotit =~ /#{str}/i
          strings[idx].count('?').times { |n| matches.push(eval("$#{n + 1}")) }
        end
      }
      break
    end
  end
  if matches.length == 1
    return matches.first
  else
    return matches.compact
  end
end

#matchfindword(*strings) ⇒ String?

Matches a word from the script's input against specified patterns.

Parameters:

  • strings (Array<String>)

    strings to match

Returns:

  • (String, nil)

    matched word or nil if no match



2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
# File 'documented/global_defs.rb', line 2252

def matchfindword(*strings)
  regex = /#{strings.flatten.join('|').gsub('?', '([\w\d]+)')}/i
  unless (script = Script.current)
    respond "Unknown script is asking to use matchfindword!  Cannot process request without identifying the calling script; killing this thread."
    Thread.current.kill
  end
  while true
    if (reobj = regex.match(script.gets))
      ret = reobj.captures.compact
      if ret.length < 2
        return ret.first
      else
        return ret
      end
    end
  end
end

#matchtimeout(secs, *strings) ⇒ String?

Matches a line from the script's input against specified patterns with a timeout.

Parameters:

  • secs (Integer)

    timeout duration in seconds

  • strings (Array<String>)

    strings to match

Returns:

  • (String, nil)

    matched string or nil if no match within timeout



1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
# File 'documented/global_defs.rb', line 1899

def matchtimeout(secs, *strings)
  unless (Script.current) then echo("An unknown script thread tried to fetch a game line from the queue, but Lich can't process the call without knowing which script is calling! Aborting..."); Thread.current.kill; return false end
  unless (secs.is_a?(Float) || secs.is_a?(Integer))
    echo('matchtimeout error! You appear to have given it a string, not a #! Syntax:  matchtimeout(30, "You stand up")')
    return false
  end
  strings.flatten!
  if strings.empty?
    echo("matchtimeout without any strings to wait for!")
    sleep 1
    return false
  end
  regexpstr = strings.join('|')
  end_time = Time.now.to_f + secs
  loop {
    line = get?
    if line.nil?
      sleep 0.1
    elsif line =~ /#{regexpstr}/i
      return line
    end
    if (Time.now.to_f > end_time)
      return false
    end
  }
end

#matchwait(*strings) ⇒ String

Waits for a line from the script's input that matches specified patterns.

Parameters:

  • strings (Array<String>)

    strings to match

Returns:



1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
# File 'documented/global_defs.rb', line 1967

def matchwait(*strings)
  unless (script = Script.current) then respond('--- matchwait: Unable to identify calling script.'); return false; end
  strings.flatten!
  unless strings.empty?
    regexpstr = strings.collect { |str| str.kind_of?(Regexp) ? str.source : str }.join('|')
    regexobj = /#{regexpstr}/
    while (line_in = script.gets)
      return line_in if line_in =~ regexobj
    end
  else
    strings = script.match_stack_strings
    labels = script.match_stack_labels
    regexpstr = /#{strings.join('|')}/i
    while (line_in = script.gets)
      if (mdata = regexpstr.match(line_in))
        jmp = labels[strings.index(mdata.to_s) || strings.index(strings.find { |str| line_in =~ /#{str}/i })]
        script.match_stack_clear
        goto jmp
      end
    end
  end
end

#maxconcentrationInteger

Retrieves the maximum concentration of the character.

Returns:

  • (Integer)

    maximum concentration value



1375
1376
1377
# File 'documented/global_defs.rb', line 1375

def maxconcentration()
  XMLData.max_concentration
end

#maxhealthInteger

Retrieves the maximum health of the character.

Returns:

  • (Integer)

    maximum health value



1284
1285
1286
1287
# File 'documented/global_defs.rb', line 1284

def maxhealth
  Lich.deprecated('maxhealth', 'Char.max_health')
  XMLData.max_health
end

#maxmanaInteger Also known as: max_mana

Retrieves the maximum mana of the character.

Returns:

  • (Integer)

    maximum mana value



1246
1247
1248
1249
# File 'documented/global_defs.rb', line 1246

def maxmana
  Lich.deprecated('maxmana', 'Char.maxmana')
  XMLData.max_mana
end

#maxspiritInteger

Retrieves the maximum spirit of the character.

Returns:

  • (Integer)

    maximum spirit value



1317
1318
1319
1320
# File 'documented/global_defs.rb', line 1317

def maxspirit
  Lich.deprecated('maxspirit', 'Char.max_spirit')
  XMLData.max_spirit
end

#maxstaminaInteger

Retrieves the maximum stamina of the character.

Returns:

  • (Integer)

    maximum stamina value



1350
1351
1352
1353
# File 'documented/global_defs.rb', line 1350

def maxstamina()
  Lich.deprecated('maxstamina', 'Char.max_stamina')
  XMLData.max_stamina
end

#monsterbold_endString

Ends bold formatting for monster text.

Returns:

  • (String)

    formatting string for bold end



2781
2782
2783
2784
2785
2786
2787
2788
2789
# File 'documented/global_defs.rb', line 2781

def monsterbold_end
  if Frontend.supports_gsl?
    "\034GSM\r\n"
  elsif Frontend.supports_xml?
    '<popBold/>'
  else
    ''
  end
end

#monsterbold_startString

Starts bold formatting for monster text.

Returns:

  • (String)

    formatting string for bold start



2769
2770
2771
2772
2773
2774
2775
2776
2777
# File 'documented/global_defs.rb', line 2769

def monsterbold_start
  if Frontend.supports_gsl?
    "\034GSL\r\n"
  elsif Frontend.supports_xml?
    '<pushBold/>'
  else
    ''
  end
end

#move(dir = 'none', giveup_seconds = 10, giveup_lines = 30) ⇒ Boolean

Moves the character in the specified direction.

Parameters:

  • dir (String) (defaults to: 'none')

    direction to move

  • giveup_seconds (Integer) (defaults to: 10)

    seconds to wait before giving up

  • giveup_lines (Integer) (defaults to: 30)

    number of lines to wait before giving up

Returns:

  • (Boolean)

    true if the move was successful, false otherwise



785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
# File 'documented/global_defs.rb', line 785

def move(dir = 'none', giveup_seconds = 10, giveup_lines = 30)
  # [LNet]-[Private]-Casis: "You begin to make your way up the steep headland pathway.  Before traveling very far, however, you lose your footing on the loose stones.  You struggle in vain to maintain your balance, then find yourself falling to the bay below!"  (20:35:36)
  # [LNet]-[Private]-Casis: "You smack into the water with a splash and sink far below the surface."  (20:35:50)
  # You approach the entrance and identify yourself to the guard.  The guard checks over a long scroll of names and says, "I'm sorry, the Guild is open to invitees only.  Please do return at a later date when we will be open to the public."
  if dir == 'none'
    echo 'move: no direction given'
    return false
  end

  need_full_hands = false
  tried_open = false
  tried_fix_drag = false
  line_count = 0
  room_count = XMLData.room_count
  giveup_time = Time.now.to_i + giveup_seconds.to_i
  save_stream = Array.new

  put_dir = proc {
    if XMLData.room_count > room_count
      fill_hands if need_full_hands
      Script.current.downstream_buffer.unshift(save_stream)
      Script.current.downstream_buffer.flatten!
      return true
    end
    waitrt?
    wait_while { stunned? }
    giveup_time = Time.now.to_i + giveup_seconds.to_i
    line_count = 0
    save_stream.push(clear)
    put dir
  }

  put_dir.call

  loop {
    line = get?
    unless line.nil?
      save_stream.push(line)
      line_count += 1
    end
    if line.nil?
      sleep 0.1
    elsif line =~ /^You realize that would be next to impossible while in combat.|^You can't do that while engaged!|^You are engaged to |^You need to retreat out of combat first!|^You try to move, but you're engaged|^While in combat\?  You'll have better luck if you first retreat/
      # DragonRealms
      fput 'retreat'
      fput 'retreat'
      put_dir.call
    elsif line =~ /^You can't enter .+ and remain hidden or invisible\.|if he can't see you!$|^You can't enter .+ when you can't be seen\.$|^You can't do that without being seen\.$|^How do you intend to get .*? attention\?  After all, no one can see you right now\.$/
      fput 'unhide'
      put_dir.call
    elsif (line =~ /^You (?:take a few steps toward|trudge up to|limp towards|march up to|sashay gracefully up to|skip happily towards|sneak up to|stumble toward) a rusty doorknob/) and (dir =~ /door/)
      which = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eight', 'ninth', 'tenth', 'eleventh', 'twelfth']
      # avoid stomping the room for the entire session due to a transient failure
      dir = dir.to_s
      if dir =~ /\b#{which.join('|')}\b/
        dir.sub!(/\b(#{which.join('|')})\b/) { "#{which[which.index($1) + 1]}" }
      else
        dir.sub!('door', 'second door')
      end
      put_dir.call
    elsif line =~ /^You can't go there|^You can't (?:go|swim) in that direction\.|^Where are you trying to go\?|^What were you referring to\?|^I could not find what you were referring to\.|^How do you plan to do that here\?|^You take a few steps towards|^You cannot do that\.|^You settle yourself on|^You shouldn't annoy|^You can't go to|^That's probably not a very good idea|^Maybe you should look|^You are already(?! as far away as you can get)|^You walk over to|^You step over to|The [\w\s]+ is too far away|You may not pass\.|become impassable\.|prevents you from entering\.|Please leave promptly\.|is too far above you to attempt that\.$|^Uh, yeah\.  Right\.$|^Definitely NOT a good idea\.$|^Your attempt fails|^There doesn't seem to be any way to do that at the moment\.$/
      echo 'move: failed'
      fill_hands if need_full_hands
      Script.current.downstream_buffer.unshift(save_stream)
      Script.current.downstream_buffer.flatten!
      return false
    elsif line =~ /^[A-z\s-] is unable to follow you\.$|^An unseen force prevents you\.$|^Sorry, you aren't allowed to enter here\.|^That looks like someplace only performers should go\.|^As you climb, your grip gives way and you fall down|^The clerk stops you from entering the partition and says, "I'll need to see your ticket!"$|^The guard stops you, saying, "Only members of registered groups may enter the Meeting Hall\.  If you'd like to visit, ask a group officer for a guest pass\."$|^An? .*? reaches over and grasps [A-Z][a-z]+ by the neck preventing (?:him|her) from being dragged anywhere\.$|^You'll have to wait, [A-Z][a-z]+ .* locker|^As you move toward the gate, you carelessly bump into the guard|^You attempt to enter the back of the shop, but a clerk stops you.  "Your reputation precedes you!|you notice that thick beams are placed across the entry with a small sign that reads, "Abandoned\."$|appears to be closed, perhaps you should try again later\?$/
      echo 'move: failed'
      fill_hands if need_full_hands
      Script.current.downstream_buffer.unshift(save_stream)
      Script.current.downstream_buffer.flatten!
      # return nil instead of false to show the direction shouldn't be removed from the map database
      return nil
    elsif line =~ /^You grab [A-Z][a-z]+ and try to drag h(?:im|er), but s?he (?:is too heavy|doesn't budge)\.$|^Tentatively, you attempt to swim through the nook\.  After only a few feet, you begin to sink!  Your lungs burn from lack of air, and you begin to panic!  You frantically paddle back to safety!$|^Guards(?:wo)?man [A-Z][a-z]+ stops you and says, "(?:Stop\.|Halt!)  You need to make sure you check in|^You step into the root, but can see no way to climb the slippery tendrils inside\.  After a moment, you step back out\.$|^As you start .*? back to safe ground\.$|^You stumble a bit as you try to enter the pool but feel that your persistence will pay off\.$|^A shimmering field of magical crimson and gold energy flows through the area\.$|^You attempt to navigate your way through the fog, but (?:quickly become entangled|get turned around)|^Trying to judge the climb, you peer over the edge\.\s*A wave of dizziness hits you, and you back away from the .*\.$|^You approach the .*, but the steepness is intimidating\.$|^You make your way (?:up|down) the .*\.\s*Partway (?:up|down), you make the mistake of looking down\. Struck by vertigo, you cling to the .* for a few moments, then slowly climb back (?:up|down)\.$|^You pick your way up the .*, but reach a point where your footing is questionable.\s*Reluctantly, you climb back down.$/
      sleep 1
      waitrt?
      put_dir.call
    elsif line =~ /^Climbing.*(?:plunge|fall)|^Tentatively, you attempt to climb.*(?:fall|slip)|^You start up the .* but slip after a few feet and fall to the ground|^You start.*but quickly realize|^You.*drop back to the ground|^You leap .* fall unceremoniously to the ground in a heap\.$|^You search for a way to make the climb .*? but without success\.$|^You start to climb .* you fall to the ground|^You attempt to climb .* wrong approach|^You run towards .*? slowly retreat back, reassessing the situation\.|^You attempt to climb down the .*, but you can't seem to find purchase\.|^You start down the .*, but you find it hard going.\s*Rather than risking a fall, you make your way back up\./
      sleep 1
      waitrt?
      fput 'stand' unless standing?
      waitrt?
      put_dir.call
    elsif line =~ /^(?:You swim .*, (?:cutting through|navigating)|You swim .*, struggling against|Your lungs burn and your muscles ache)/
      # swims in Sailor's Grief
      return true
    elsif line =~ /^You begin to climb up the silvery thread.* you tumble to the ground/
      sleep 0.5
      waitrt?
      fput 'stand' unless standing?
      waitrt?
      if checkleft or checkright
        need_full_hands = true
        empty_hands
      end
      put_dir.call
    elsif line == 'You are too injured to be doing any climbing!'
      if (resolve = Spell[9704]) and resolve.known?
        wait_until { resolve.affordable? }
        resolve.cast
        put_dir.call
      else
        return nil
      end
    elsif line =~ /^You(?:'re going to| will) have to climb that\./
      dir.gsub!('go', 'climb')
      put_dir.call
    elsif line =~ /^You can't climb that\./
      dir.gsub!('climb', 'go')
      put_dir.call
    elsif line =~ /^You can't drag/
      if tried_fix_drag
        fill_hands if need_full_hands
        Script.current.downstream_buffer.unshift(save_stream)
        Script.current.downstream_buffer.flatten!
        return false
      elsif (dir =~ /^(?:go|climb) .+$/) and (drag_line = reget.reverse.find { |l| l =~ /^You grab .*?(?:'s body)? and drag|^You are now automatically attempting to drag .*? when/ })
        tried_fix_drag = true
        name = (/^You grab (.*?)('s body)? and drag/.match(drag_line).captures.first || /^You are now automatically attempting to drag (.*?) when/.match(drag_line).captures.first)
        target = /^(?:go|climb) (.+)$/.match(dir).captures.first
        fput "drag #{name}"
        dir = "drag #{name} #{target}"
        put_dir.call
      else
        tried_fix_drag = true
        dir.sub!(/^climb /, 'go ')
        put_dir.call
      end
    elsif line =~ /^Maybe if your hands were empty|^You figure freeing up both hands might help\.|^You can't .+ with your hands full\.$|^You'll need empty hands to climb that\.$|^It's a bit too difficult to swim holding|^You will need both hands free for such a difficult task\./
      need_full_hands = true
      empty_hands
      put_dir.call
    elsif line =~ /(?:appears|seems) to be closed\.$|^You cannot quite manage to squeeze between the stone doors\.$/
      if tried_open
        fill_hands if need_full_hands
        Script.current.downstream_buffer.unshift(save_stream)
        Script.current.downstream_buffer.flatten!
        return false
      else
        tried_open = true
        fput dir.sub(/go|climb/, 'open')
        put_dir.call
      end
    elsif line =~ /^(\.\.\.w|W)ait ([0-9]+) sec(onds)?\.$/
      if $2.to_i > 1
        sleep($2.to_i - "0.2".to_f)
      else
        sleep 0.3
      end
      put_dir.call
    elsif line =~ /will have to stand up first|must be standing first|^You'll have to get up first|^But you're already sitting!|^Shouldn't you be standing first|^That would be quite a trick from that position\.  Try standing up\.|^Perhaps you should stand up|^Standing up might help|^You should really stand up first|You can't do that while sitting|You must be standing to do that|You can't do that while lying down|^You must be standing/
      fput 'stand'
      waitrt?
      put_dir.call
    elsif line =~ /^You're still recovering from your recent/
      sleep 2
      put_dir.call
    elsif line =~ /^The ground approaches you at an alarming rate/
      sleep 1
      fput 'stand' unless standing?
      put_dir.call
    elsif line =~ /You go flying down several feet, landing with a/
      sleep 1
      fput 'stand' unless standing?
      put_dir.call
    elsif line =~ /^Sorry, you may only type ahead/
      sleep 1
      put_dir.call
    elsif line == 'You are still stunned.'
      wait_while { stunned? }
      put_dir.call
    elsif line =~ /you slip (?:on a patch of ice )?and flail uselessly as you land on your rear(?:\.|!)$|You wobble and stumble only for a moment before landing flat on your face!$|^You slip in the mud and fall flat on your back\!$/
      waitrt?
      fput 'stand' unless standing?
      waitrt?
      put_dir.call
    elsif line =~ /^You flick your hand (?:up|down)wards and focus your aura on your disk, but your disk only wobbles briefly\.$/
      put_dir.call
    elsif line =~ /^You dive into the fast-moving river, but the current catches you and whips you back to shore, wet and battered\.$|^Running through the swampy terrain, you notice a wet patch in the bog|^You flounder around in the water.$|^You blunder around in the water, barely able|^You struggle against the swift current to swim|^You slap at the water in a sad failure to swim|^You work against the swift current to swim/
      waitrt?
      put_dir.call
    elsif line =~ /^(You notice .* at your feet, and do not wish to leave it behind|As you prepare to move away, you remember)/
      fput "stow feet"
      sleep 1
      put_dir.call
    elsif line =~ /The electricity courses through you in a raging torrent, its power singing in your veins!  Spent, the boltstone apparatus shatters into glinting fragments\.|The lightning strikes you in an agonizing eruption of liquid radiance!/
      sleep(0.5)
      wait_while { stunned? }
      waitrt?
      fput 'stand' unless standing?
      waitrt?
      put_dir.call
    elsif line == "You don't seem to be able to move to do that."
      30.times {
        break if clear.include?('You regain control of your senses!')

        sleep 0.1
      }
      put_dir.call
    elsif line =~ /^It's pitch dark and you can't see a thing!/
      echo "You will need a light source to continue your journey"
      return true
    end
    if XMLData.room_count > room_count
      fill_hands if need_full_hands
      Script.current.downstream_buffer.unshift(save_stream)
      Script.current.downstream_buffer.flatten!
      return true
    end
    if Time.now.to_i >= giveup_time
      echo "move: no recognized response in #{giveup_seconds} seconds.  giving up."
      fill_hands if need_full_hands
      Script.current.downstream_buffer.unshift(save_stream)
      Script.current.downstream_buffer.flatten!
      return nil
    end
    if line_count >= giveup_lines
      echo "move: no recognized response after #{line_count} lines.  giving up."
      fill_hands if need_full_hands
      Script.current.downstream_buffer.unshift(save_stream)
      Script.current.downstream_buffer.flatten!
      return nil
    end
  }
end

#muckled?Boolean

Checks if the character is muckled.

Returns:

  • (Boolean)

    true if muckled



456
457
458
459
460
461
462
463
# File 'documented/global_defs.rb', line 456

def muckled?
  # need a better DR solution
  if XMLData.game =~ /GS/
    return Status.muckled?
  else
    return checkdead || checkstunned || checkwebbed
  end
end

#multifput(*cmds) ⇒ void

This method returns an undefined value.

Sends multiple commands to the game.

Parameters:

  • cmds (Array<String>)

    commands to send



2092
2093
2094
# File 'documented/global_defs.rb', line 2092

def multifput(*cmds)
  cmds.flatten.compact.each { |cmd| fput(cmd) }
end

#multimove(*dirs) ⇒ void

This method returns an undefined value.

Moves in multiple directions sequentially.

Parameters:

  • dirs (Array<String>)

    directions to move



719
720
721
# File 'documented/global_defs.rb', line 719

def multimove(*dirs)
  dirs.flatten.each { |dir| move(dir) }
end

#nString

Returns the string representation of the direction 'north'.

Returns:



725
# File 'documented/global_defs.rb', line 725

def n;    'north';     end

#neString

Returns the string representation of the direction 'northeast'.

Returns:



729
# File 'documented/global_defs.rb', line 729

def ne;   'northeast'; end

#no_kill_allvoid

This method returns an undefined value.

Toggles the no-kill-all setting for the current script.



179
180
181
182
# File 'documented/global_defs.rb', line 179

def no_kill_all
  script = Script.current
  script.no_kill_all = !script.no_kill_all
end

#no_pause_allvoid

This method returns an undefined value.

Toggles the no-pause-all setting for the current script.



186
187
188
189
# File 'documented/global_defs.rb', line 186

def no_pause_all
  script = Script.current
  script.no_pause_all = !script.no_pause_all
end

#noded_pulseInteger

Calculates the pulse value for non-noded characters.

Returns:

  • (Integer)

    calculated pulse value



2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
# File 'documented/global_defs.rb', line 2393

def noded_pulse
  unless XMLData.game =~ /DR/
    if Stats.prof =~ /warrior|rogue|sorcerer/i
      stats = [Skills.smc.to_i, Skills.emc.to_i]
    elsif Stats.prof =~ /empath|bard/i
      stats = [Skills.smc.to_i, Skills.mmc.to_i]
    elsif Stats.prof =~ /wizard/i
      stats = [Skills.emc.to_i, 0]
    elsif Stats.prof =~ /paladin|cleric|ranger/i
      stats = [Skills.smc.to_i, 0]
    else
      stats = [0, 0]
    end
    return (XMLData.max_mana * 25 / 100) + (stats.max / 10) + (stats.min / 20)
  else
    return 0 # this method is not used by DR
  end
end

#nwString

Returns the string representation of the direction 'northwest'.

Returns:



753
# File 'documented/global_defs.rb', line 753

def nw;   'northwest'; end

#oString

Returns the string representation of the direction 'out'.

Returns:



773
# File 'documented/global_defs.rb', line 773

def o;    'out';       end

#outString

Returns the string representation of the direction 'out'.

Returns:



777
# File 'documented/global_defs.rb', line 777

def out;  'out';       end

#outside?Boolean Also known as: checkoutside

Checks if the character is outside based on room exits.

Returns:

  • (Boolean)

    true if outside



1503
1504
1505
1506
1507
1508
1509
# File 'documented/global_defs.rb', line 1503

def outside?
  if XMLData.room_exits_string =~ /Obvious paths:/
    true
  else
    false
  end
end

#parse_args(defn, flex_args = false) ⇒ Hash

Parses command line arguments based on a definition.

Parameters:

  • defn (String)

    the argument definition

  • flex_args (Boolean) (defaults to: false)

    whether to allow flexible arguments

Returns:

  • (Hash)

    parsed arguments



95
96
97
# File 'documented/global_defs.rb', line 95

def parse_args(defn, flex_args = false)
  Lich::Common::ArgParser.new.parse_args(defn, flex_args)
end

#parse_list(string) ⇒ Array<String>

Parses a string into a list format.

Parameters:

  • string (String)

    the string to parse

Returns:

  • (Array<String>)

    parsed list



349
350
351
# File 'documented/global_defs.rb', line 349

def parse_list(string)
  string.split_as_list
end

#pause(num = 1) ⇒ void

This method returns an undefined value.

Pauses execution for a specified duration.

Parameters:

  • num (String) (defaults to: 1)

    duration to pause (can include 'm' for minutes, 'h' for hours, 'd' for days)



1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
# File 'documented/global_defs.rb', line 1828

def pause(num = 1)
  if num.to_s =~ /m/
    sleep((num.sub(/m/, '').to_f * 60))
  elsif num.to_s =~ /h/
    sleep((num.sub(/h/, '').to_f * 3600))
  elsif num.to_s =~ /d/
    sleep((num.sub(/d/, '').to_f * 86400))
  else
    sleep(num.to_f)
  end
end

#pause_script(*names) ⇒ void Also known as: pause_scripts

This method returns an undefined value.

Pauses the specified scripts.

Parameters:

  • names (Array<String>)

    names of scripts to pause



298
299
300
301
302
303
304
305
306
307
308
309
# File 'documented/global_defs.rb', line 298

def pause_script(*names)
  names.flatten!
  if names.empty?
    Script.current.pause
    Script.current
  else
    names.each { |scr|
      fnd = Script.list.find { |nm| nm.name =~ /^#{scr}/i }
      fnd.pause unless (fnd.paused || fnd.nil?)
    }
  end
end

#percentconcentration(num = nil) ⇒ Boolean

Checks the character's concentration percentage against a specified number.

Parameters:

  • num (Integer, nil) (defaults to: nil)

    optional number to compare against

Returns:

  • (Boolean)

    true if concentration percentage is greater than or equal to num



1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
# File 'documented/global_defs.rb', line 1383

def percentconcentration(num = nil)
  if XMLData.max_concentration == 0
    percent = 100
  else
    percent = ((XMLData.concentration.to_f / XMLData.max_concentration.to_f) * 100).to_i
  end
  if num.nil?
    percent
  else
    percent >= num.to_i
  end
end

#percentencumbrance(num = nil) ⇒ Boolean

Checks the character's encumbrance percentage against a specified number.

Parameters:

  • num (Integer, nil) (defaults to: nil)

    optional number to compare against

Returns:

  • (Boolean)

    true if encumbrance percentage is greater than or equal to num



1466
1467
1468
1469
1470
1471
1472
1473
# File 'documented/global_defs.rb', line 1466

def percentencumbrance(num = nil)
  Lich.deprecated('percentencumbrance', 'Char.percent_encumbrance')
  if num.nil?
    XMLData.encumbrance_value
  else
    num.to_i <= XMLData.encumbrance_value
  end
end

#percenthealth(num = nil) ⇒ Boolean

Checks the character's health percentage against a specified number.

Parameters:

  • num (Integer, nil) (defaults to: nil)

    optional number to compare against

Returns:

  • (Boolean)

    true if health percentage is greater than or equal to num



1293
1294
1295
1296
1297
1298
1299
1300
# File 'documented/global_defs.rb', line 1293

def percenthealth(num = nil)
  Lich.deprecated('percenthealth', 'Char.percent_health')
  if num.nil?
    ((XMLData.health.to_f / XMLData.max_health.to_f) * 100).to_i
  else
    ((XMLData.health.to_f / XMLData.max_health.to_f) * 100).to_i >= num.to_i
  end
end

#percentmana(num = nil) ⇒ Boolean

Checks the character's mana percentage against a specified number.

Parameters:

  • num (Integer, nil) (defaults to: nil)

    optional number to compare against

Returns:

  • (Boolean)

    true if mana percentage is greater than or equal to num



1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
# File 'documented/global_defs.rb', line 1255

def percentmana(num = nil)
  Lich.deprecated('percentmana', 'Char.percent_mana')
  if XMLData.max_mana == 0
    percent = 100
  else
    percent = ((XMLData.mana.to_f / XMLData.max_mana.to_f) * 100).to_i
  end
  if num.nil?
    percent
  else
    percent >= num.to_i
  end
end

#percentmind(num = nil) ⇒ Boolean

Checks the character's mind value against a specified number.

Parameters:

  • num (Integer, nil) (defaults to: nil)

    optional number to compare against

Returns:

  • (Boolean)

    true if mind value is greater than or equal to num



1203
1204
1205
1206
1207
1208
1209
# File 'documented/global_defs.rb', line 1203

def percentmind(num = nil)
  if num.nil?
    XMLData.mind_value
  else
    XMLData.mind_value >= num.to_i
  end
end

#percentspirit(num = nil) ⇒ Boolean

Checks the character's spirit percentage against a specified number.

Parameters:

  • num (Integer, nil) (defaults to: nil)

    optional number to compare against

Returns:

  • (Boolean)

    true if spirit percentage is greater than or equal to num



1326
1327
1328
1329
1330
1331
1332
1333
# File 'documented/global_defs.rb', line 1326

def percentspirit(num = nil)
  Lich.deprecated('percentspirit', 'Char.percent_spirit')
  if num.nil?
    ((XMLData.spirit.to_f / XMLData.max_spirit.to_f) * 100).to_i
  else
    ((XMLData.spirit.to_f / XMLData.max_spirit.to_f) * 100).to_i >= num.to_i
  end
end

#percentstamina(num = nil) ⇒ Boolean

Checks the character's stamina percentage against a specified number.

Parameters:

  • num (Integer, nil) (defaults to: nil)

    optional number to compare against

Returns:

  • (Boolean)

    true if stamina percentage is greater than or equal to num



1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
# File 'documented/global_defs.rb', line 1359

def percentstamina(num = nil)
  Lich.deprecated('percentstamina', 'Char.percent_stamina')
  if XMLData.max_stamina == 0
    percent = 100
  else
    percent = ((XMLData.stamina.to_f / XMLData.max_stamina.to_f) * 100).to_i
  end
  if num.nil?
    percent
  else
    percent >= num.to_i
  end
end

#percentstance(num = nil) ⇒ Boolean

Checks the character's stance percentage against a specified number.

Parameters:

  • num (Integer, nil) (defaults to: nil)

    optional number to compare against

Returns:

  • (Boolean)

    true if stance percentage is greater than or equal to num



1433
1434
1435
1436
1437
1438
1439
1440
# File 'documented/global_defs.rb', line 1433

def percentstance(num = nil)
  Lich.deprecated('percentstance', 'Char.percent_stance')
  if num.nil?
    XMLData.stance_value
  else
    XMLData.stance_value >= num.to_i
  end
end

#put(*messages) ⇒ void

This method returns an undefined value.

Sends messages to the game.

Parameters:

  • messages (Array<String>)

    messages to send



2185
2186
2187
# File 'documented/global_defs.rb', line 2185

def put(*messages)
  messages.each { |message| Game.puts(message) }
end

#quiet_exitvoid

This method returns an undefined value.

Toggles the quiet exit setting for the current script.



2191
2192
2193
2194
# File 'documented/global_defs.rb', line 2191

def quiet_exit
  script = Script.current
  script.quiet = !(script.quiet)
end

#reget(*lines, core: false) ⇒ Array<String>?

Retrieves lines from the server buffer based on specified criteria.

Parameters:

  • lines (Array<String>)

    optional lines to filter

  • core (Boolean) (defaults to: false)

    whether to allow core access

Returns:

  • (Array<String>, nil)

    filtered lines or nil if none



2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
# File 'documented/global_defs.rb', line 2047

def reget(*lines, core: false)
  unless (script = Script.current) || core.eql?(true)
    respond('--- reget: Unable to identify calling script.')
    return false
  end
  lines.flatten!
  if caller.find { |c| c =~ /regetall/ }
    history = ($_SERVERBUFFER_.history + $_SERVERBUFFER_).join("\n")
  else
    history = $_SERVERBUFFER_.dup.join("\n")
  end
  unless script&.want_downstream_xml || core.eql?(true)
    history.gsub!(/<pushStream id=["'](?:spellfront|inv|bounty|society)["'][^>]*\/>.*?<popStream[^>]*>/m, '')
    history.gsub!(/<stream id="Spells">.*?<\/stream>/m, '')
    history.gsub!(/<(compDef|inv|component|right|left|spell|prompt)[^>]*>.*?<\/\1>/m, '')
    history.gsub!(/<[^>]+>/, '')
    history.gsub!('&gt;', '>')
    history.gsub!('&lt;', '<')
  end
  history = history.split("\n").delete_if { |line| line.nil? or line.empty? or line =~ /^[\r\n\s\t]*$/ }
  if lines.first.kind_of?(Numeric) or lines.first.to_i.nonzero?
    history = history[-([lines.shift.to_i, history.length].min)..-1]
  end
  unless lines.empty? or lines.nil?
    regex = /#{lines.join('|')}/i
    history = history.find_all { |line| line =~ regex }
  end
  if history.empty?
    nil
  else
    history
  end
end

#regetall(*lines) ⇒ Array<String>?

Retrieves all lines from the server buffer based on specified criteria.

Parameters:

  • lines (Array<String>)

    optional lines to filter

Returns:

  • (Array<String>, nil)

    filtered lines or nil if none



2084
2085
2086
# File 'documented/global_defs.rb', line 2084

def regetall(*lines)
  reget(*lines)
end

#report_errors { ... } ⇒ void

This method returns an undefined value.

Reports errors that occur during execution of a block.

Yields:

  • block of code to execute



3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
# File 'documented/global_defs.rb', line 3228

def report_errors(&block)
  begin
    block.call
  rescue
    respond "--- Lich: error: #{$!}\n\t#{$!.backtrace[0..1].join("\n\t")}"
    Lich.log "error: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
  rescue SyntaxError
    respond "--- Lich: error: #{$!}\n\t#{$!.backtrace[0..1].join("\n\t")}"
    Lich.log "error: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
  rescue SystemExit
    nil
  rescue SecurityError
    respond "--- Lich: error: #{$!}\n\t#{$!.backtrace[0..1].join("\n\t")}"
    Lich.log "error: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
  rescue ThreadError
    respond "--- Lich: error: #{$!}\n\t#{$!.backtrace[0..1].join("\n\t")}"
    Lich.log "error: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
  rescue SystemStackError
    respond "--- Lich: error: #{$!}\n\t#{$!.backtrace[0..1].join("\n\t")}"
    Lich.log "error: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
  rescue StandardError
    respond "--- Lich: error: #{$!}\n\t#{$!.backtrace[0..1].join("\n\t")}"
    Lich.log "error: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
  #  rescue ScriptError
  #    respond "--- Lich: error: #{$!}\n\t#{$!.backtrace[0..1].join("\n\t")}"
  #    Lich.log "error: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
  rescue LoadError
    respond "--- Lich: error: #{$!}\n\t#{$!.backtrace[0..1].join("\n\t")}"
    Lich.log "error: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
  rescue NoMemoryError
    respond "--- Lich: error: #{$!}\n\t#{$!.backtrace[0..1].join("\n\t")}"
    Lich.log "error: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
  rescue
    respond "--- Lich: error: #{$!}\n\t#{$!.backtrace[0..1].join("\n\t")}"
    Lich.log "error: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
  end
end

#respond(first = "", *messages) ⇒ void

This method returns an undefined value.

Sends a response to the client.

Parameters:

  • first (String, Array) (defaults to: "")

    first message or array of messages to send

  • messages (Array<String>)

    additional messages to send



2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
# File 'documented/global_defs.rb', line 2310

def respond(first = "", *messages)
  str = ''
  begin
    if first.is_a?(Array)
      first.flatten.each { |ln| str += sprintf("%s\r\n", ln.to_s.chomp) }
    else
      str += sprintf("%s\r\n", first.to_s.chomp)
    end
    messages.flatten.each { |message| str += sprintf("%s\r\n", message.to_s.chomp) }
    str.split(/\r?\n/).each { |line| Script.new_script_output(line); Buffer.update(line, Buffer::SCRIPT_OUTPUT) }
    # str.gsub!(/\r?\n/, "\r\n") if $frontend == 'genie'
    if Frontend.supports_mono?
      str = "<output class=\"mono\"/>\r\n#{str.gsub('&', '&amp;').gsub('<', '&lt;').gsub('>', '&gt;')}<output class=\"\"/>\r\n"
    elsif Frontend.client.eql?('profanity')
      str = str.gsub('&', '&amp;').gsub('<', '&lt;').gsub('>', '&gt;')
    end
    # Double-checked locking to avoid interrupting a stream and crashing the client
    str_sent = false
    if $_CLIENT_
      until str_sent
        wait_while { !XMLData.safe_to_respond? }
        str_sent = $_CLIENT_.puts_if(str) { XMLData.safe_to_respond? }
      end
    end
    if $_DETACHABLE_CLIENT_
      str_sent = false
      until str_sent
        wait_while { !XMLData.safe_to_respond? }
        begin
          str_sent = $_DETACHABLE_CLIENT_.puts_if(str) { XMLData.safe_to_respond? }
        rescue
          break
        end
      end
    end
  rescue
    puts $!
    puts $!.backtrace.first
  end
end

#reverse_direction(dir) ⇒ String, false

Reverses the given direction.

Parameters:

  • dir (String)

    direction to reverse

Returns:

  • (String, false)

    reversed direction or false if unrecognized



1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
# File 'documented/global_defs.rb', line 1087

def reverse_direction(dir)
  if dir == "n" then 's'
  elsif dir == "ne" then 'sw'
  elsif dir == "e" then 'w'
  elsif dir == "se" then 'nw'
  elsif dir == "s" then 'n'
  elsif dir == "sw" then 'ne'
  elsif dir == "w" then 'e'
  elsif dir == "nw" then 'se'
  elsif dir == "up" then 'down'
  elsif dir == "down" then 'up'
  elsif dir == "out" then 'out'
  elsif dir == 'o' then out
  elsif dir == 'u' then 'down'
  elsif dir == 'd' then up
  elsif dir == n then s
  elsif dir == ne then sw
  elsif dir == e then w
  elsif dir == se then nw
  elsif dir == s then n
  elsif dir == sw then ne
  elsif dir == w then e
  elsif dir == nw then se
  elsif dir == u then d
  elsif dir == d then u
  else
    echo("Cannot recognize direction to properly reverse it!"); false
  end
end

#runvoid

This method returns an undefined value.

Runs the walk method in a loop until stopped.



1146
1147
1148
# File 'documented/global_defs.rb', line 1146

def run
  loop { break unless walk }
end

#running?(*snames) ⇒ Boolean

Checks if specified scripts are currently running.

Parameters:

  • snames (Array<String>)

    names of scripts to check

Returns:

  • (Boolean)

    true if all specified scripts are running



157
158
159
160
# File 'documented/global_defs.rb', line 157

def running?(*snames)
  snames.each { |checking| (return false) unless (Script.running.find { |lscr| lscr.name =~ /^#{checking}$/i } || Script.running.find { |lscr| lscr.name =~ /^#{checking}/i } || Script.hidden.find { |lscr| lscr.name =~ /^#{checking}$/i } || Script.hidden.find { |lscr| lscr.name =~ /^#{checking}/i }) }
  true
end

#sString

Returns the string representation of the direction 'south'.

Returns:



741
# File 'documented/global_defs.rb', line 741

def s;    'south';     end

#seString

Returns the string representation of the direction 'southeast'.

Returns:



737
# File 'documented/global_defs.rb', line 737

def se;   'southeast'; end

#selectput(string, success, failure, timeout = nil) ⇒ String?

Sends a command to the game and waits for a response matching success or failure patterns.

Parameters:

  • string (String)

    command to send

  • success (Array<String>)

    patterns for successful responses

  • failure (Array<String>)

    patterns for failure responses

  • timeout (Integer, nil) (defaults to: nil)

    optional timeout for the operation

Returns:

  • (String, nil)

    response from the game or nil on timeout



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
# File 'documented/global_defs.rb', line 581

def selectput(string, success, failure, timeout = nil)
  timeout = timeout.to_f if timeout and !timeout.kind_of?(Numeric)
  success = [success] if success.kind_of? String
  failure = [failure] if failure.kind_of? String
  if !string.kind_of?(String) or !success.kind_of?(Array) or !failure.kind_of?(Array) or timeout && !timeout.kind_of?(Numeric)
    raise ArgumentError, "usage is: selectput(game_command,success_array,failure_array[,timeout_in_secs])"
  end

  success.flatten!
  failure.flatten!
  regex = /#{(success + failure).join('|')}/i
  successre = /#{success.join('|')}/i
  thr = Thread.current

  timethr = Thread.new {
    timeout -= sleep("0.1".to_f) until timeout <= 0
    thr.raise(StandardError)
  } if timeout

  begin
    loop {
      fput(string)
      response = waitforre(regex)
      if successre.match(response.to_s)
        timethr.kill if timethr.alive?
        break(response.string)
      end
      yield(response.string) if block_given?
    }
  rescue
    nil
  end
end

#send_scripts(*messages) ⇒ void Also known as: send_script

This method returns an undefined value.

Sends messages to multiple scripts.

Parameters:

  • messages (Array<String>)

    messages to send



2274
2275
2276
2277
2278
2279
2280
# File 'documented/global_defs.rb', line 2274

def send_scripts(*messages)
  messages.flatten!
  messages.each { |message|
    Script.new_downstream(message)
  }
  true
end

#send_to_script(*values) ⇒ Boolean

Sends values to a specified script.

Parameters:

  • values (Array<String>)

    values to send

Returns:

  • (Boolean)

    true if successful, false otherwise



653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
# File 'documented/global_defs.rb', line 653

def send_to_script(*values)
  values.flatten!
  if (script = Script.list.find { |val| val.name =~ /^#{values.first}/i })
    if script.want_downstream
      values[1..-1].each { |val| script.downstream_buffer.push(val) }
    else
      values[1..-1].each { |val| script.unique_buffer.push(val) }
    end
    echo("Sent to #{script.name} -- '#{values[1..-1].join(' ; ')}'")
    return true
  else
    echo("'#{values.first}' does not match any active scripts!")
    return false
  end
end

#setpriority(val = nil) ⇒ Integer Also known as: priority?

Sets the priority of the current script.

Parameters:

  • val (Integer, nil) (defaults to: nil)

    optional priority value to set

Returns:

  • (Integer)

    current priority value



1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
# File 'documented/global_defs.rb', line 1725

def setpriority(val = nil)
  if val.nil? then return Thread.current.priority end

  if val.to_i > 3
    echo("You're trying to set a script's priority as being higher than the send/recv threads (this is telling Lich to run the script before it even gets data to give the script, and is useless); the limit is 3")
    return Thread.current.priority
  else
    Thread.current.group.list.each { |thr| thr.priority = val.to_i }
    return Thread.current.priority
  end
end

#sf_to_wiz(line, bypass_multiline: false) ⇒ String?

Converts a line from string format to wizard format.

Parameters:

  • line (String)

    line to convert

  • bypass_multiline (Boolean) (defaults to: false)

    whether to bypass multiline handling

Returns:

  • (String, nil)

    converted line or nil if empty



2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
# File 'documented/global_defs.rb', line 2661

def sf_to_wiz(line, bypass_multiline: false)
  begin
    return line if line == "\r\n"

    unless bypass_multiline
      if $sftowiz_multiline
        $sftowiz_multiline = $sftowiz_multiline + line
        line = $sftowiz_multiline
      end
      if (line.scan(/<pushStream[^>]*\/>/).length > line.scan(/<popStream[^>]*\/>/).length)
        $sftowiz_multiline = line
        return nil
      end
      if (line.scan(/<style id="\w+"[^>]*\/>/).length > line.scan(/<style id=""[^>]*\/>/).length)
        $sftowiz_multiline = line
        return nil
      end
      $sftowiz_multiline = nil
    end
    if line =~ /<LaunchURL src="(.*?)" \/>/
      $_CLIENT_.puts "\034GSw00005\r\nhttps://www.play.net#{$1}\r\n"
    end
    if line =~ /<preset id='speech'>(.*?)<\/preset>/m
      line = line.sub(/<preset id='speech'>.*?<\/preset>/m, "#{$speech_highlight_start}#{$1}#{$speech_highlight_end}")
    end
    if line =~ /<pushStream id="thoughts"[^>]*>\[([^\\]+?)\]\s*(.*?)<popStream\/>/m
      thought_channel = $1
      msg = $2
      thought_channel.gsub!(' ', '-')
      msg.gsub!('<pushBold/>', '')
      msg.gsub!('<popBold/>', '')
      line = line.sub(/<pushStream id="thoughts".*<popStream\/>/m, "You hear the faint thoughts of [#{thought_channel}]-ESP echo in your mind:\r\n#{msg}")
    end
    if line =~ /<pushStream id="voln"[^>]*>\[Voln \- (?:<a[^>]*>)?([A-Z][a-z]+)(?:<\/a>)?\]\s*(".*")[\r\n]*<popStream\/>/m
      line = line.sub(/<pushStream id="voln"[^>]*>\[Voln \- (?:<a[^>]*>)?([A-Z][a-z]+)(?:<\/a>)?\]\s*(".*")[\r\n]*<popStream\/>/m, "The Symbol of Thought begins to burn in your mind and you hear #{$1} thinking, #{$2}\r\n")
    end
    if line =~ /<stream id="thoughts"[^>]*>([^:]+): (.*?)<\/stream>/m
      line = line.sub(/<stream id="thoughts"[^>]*>.*?<\/stream>/m, "You hear the faint thoughts of #{$1} echo in your mind:\r\n#{$2}")
    end
    if line =~ /<pushStream id="familiar"[^>]*>(.*)<popStream\/>/m
      line = line.sub(/<pushStream id="familiar"[^>]*>.*<popStream\/>/m, "\034GSe\r\n#{$1}\034GSf\r\n")
    end
    if line =~ /<pushStream id="death"\/>(.*?)<popStream\/>/m
      line = line.sub(/<pushStream id="death"\/>.*?<popStream\/>/m, "\034GSw00003\r\n#{$1}\034GSw00004\r\n")
    end
    if line =~ /<style id="roomName" \/>(.*?)<style id=""\/>/m
      line = line.sub(/<style id="roomName" \/>.*?<style id=""\/>/m, "\034GSo\r\n#{$1}\034GSp\r\n")
    end
    line.gsub!(/<style id="roomDesc"\/><style id=""\/>\r?\n/, '')
    if line =~ /<style id="roomDesc"\/>(.*?)<style id=""\/>/m
      desc = $1.gsub(/<a[^>]*>/, $link_highlight_start).gsub("</a>", $link_highlight_end)
      line = line.sub(/<style id="roomDesc"\/>.*?<style id=""\/>/m, "\034GSH\r\n#{desc}\034GSI\r\n")
    end
    line = line.gsub("</prompt>\r\n", "</prompt>")
    line = line.gsub("<pushBold/>", "\034GSL\r\n")
    line = line.gsub("<popBold/>", "\034GSM\r\n")
    line = line.gsub(/<pushStream id=["'](?:spellfront|inv|bounty|society|speech|talk)["'][^>]*\/>.*?<popStream[^>]*>/m, '')
    line = line.gsub(/<stream id="Spells">.*?<\/stream>/m, '')
    line = line.gsub(/<(compDef|inv|component|right|left|spell|prompt)[^>]*>.*?<\/\1>/m, '')
    line = line.gsub(/<[^>]+>/, '')
    line = line.gsub('&gt;', '>')
    line = line.gsub('&lt;', '<')
    line = line.gsub('&amp;', '&')
    return nil if line.gsub("\r\n", '').length < 1

    return line
  rescue
    $_CLIENT_.puts "--- Error: sf_to_wiz: #{$!}"
    $_CLIENT_.puts "$_SERVERSTRING_: #{$_SERVERSTRING_}"
    Lich.log("--- Error: sf_to_wiz: #{$!}\n\t#{$!.backtrace.join("\n\t")}")
    Lich.log("$_SERVERSTRING_: #{$_SERVERSTRING_}")
    Lich.log("Line: #{line}")
  end
end

#silence_mevoid

This method returns an undefined value.

Toggles the silence setting for the current script.



200
201
202
203
204
205
206
207
# File 'documented/global_defs.rb', line 200

def silence_me
  unless (script = Script.current) then echo 'silence_me: cannot identify calling script.'; return nil; end
  if script.safe? then echo("WARNING: 'safe' script attempted to silence itself.  Ignoring the request.")
                       sleep 1
                       return true
  end
  script.silent = !script.silent
end

#silenced?Boolean

Checks if the character is silenced.

Returns:

  • (Boolean)

    true if silenced



1784
1785
1786
1787
# File 'documented/global_defs.rb', line 1784

def silenced?
  return Status.silenced? if XMLData.game =~ /GS/
  fail "Error: toplevel silenced command not enabled in #{XMLData.game}"
end

#sleeping?Boolean

Checks if the character is sleeping.

Returns:

  • (Boolean)

    true if sleeping



1756
1757
1758
1759
# File 'documented/global_defs.rb', line 1756

def sleeping?
  return Status.sleeping? if XMLData.game =~ /GS/
  fail "Error: toplevel sleeping? command not enabled in #{XMLData.game}"
end

#start_exec_script(cmd_data, options = Hash.new) ⇒ void

This method returns an undefined value.

Starts an execution script with given command data.

Parameters:

  • cmd_data (String)

    command data to execute

  • options (Hash) (defaults to: Hash.new)

    options for execution



167
168
169
# File 'documented/global_defs.rb', line 167

def start_exec_script(cmd_data, options = Hash.new)
  ExecScript.start(cmd_data, options)
end

#start_script(script_name, cli_vars = [], flags = Hash.new) ⇒ void

This method returns an undefined value.

Starts a script with the given name and optional command line variables.

Parameters:

  • script_name (String)

    the name of the script to start

  • cli_vars (Array<String>) (defaults to: [])

    command line variables to pass to the script

  • flags (Hash) (defaults to: Hash.new)

    additional flags for script execution



21
22
23
24
25
26
# File 'documented/global_defs.rb', line 21

def start_script(script_name, cli_vars = [], flags = Hash.new)
  if flags == true
    flags = { :quiet => true }
  end
  Script.start(script_name, cli_vars.join(' '), flags)
end

#start_scripts(*script_names) ⇒ void

This method returns an undefined value.

Starts multiple scripts in sequence.

Parameters:

  • script_names (Array<String>)

    names of scripts to start



32
33
34
35
36
37
# File 'documented/global_defs.rb', line 32

def start_scripts(*script_names)
  script_names.flatten.each { |script_name|
    start_script(script_name)
    sleep 0.02
  }
end

#start_scripts_if_available(script_names) ⇒ void

This method returns an undefined value.

Starts scripts only if they are available and not already running.

Parameters:

  • script_names (Array<String>)

    names of scripts to start



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'documented/global_defs.rb', line 55

def start_scripts_if_available(script_names)
  script_names = [script_names].flatten.compact
  return if script_names.empty?

  script_names.each do |script_name|
    next if Script.running?(script_name)
    next unless Script.exists?(script_name)

    start_script(script_name)
    pause 0.05
    snapshot = Time.now
    until !Script.running?(script_name) || Time.now - snapshot > 0.25
      pause 0.05
    end
  end
end

#status_tags(onoff = "none") ⇒ void Also known as: toggle_status

This method returns an undefined value.

Toggles the status tags for the current script.

Parameters:

  • onoff (String) (defaults to: "none")

    'on' or 'off' to set the status tags



2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
# File 'documented/global_defs.rb', line 2286

def status_tags(onoff = "none")
  script = Script.current
  if onoff == "on"
    script.want_downstream = false
    script.want_downstream_xml = true
    echo("Status tags will be sent to this script.")
  elsif onoff == "off"
    script.want_downstream = true
    script.want_downstream_xml = false
    echo("Status tags will no longer be sent to this script.")
  elsif script.want_downstream_xml
    script.want_downstream = true
    script.want_downstream_xml = false
  else
    script.want_downstream = false
    script.want_downstream_xml = true
  end
end

#stop_script(*target_names) ⇒ Integer, false Also known as: stop_scripts, kill_scripts, kill_script

Stops a running script by name.

Parameters:

  • target_names (Array<String>)

    names of scripts to stop

Returns:

  • (Integer, false)

    number of scripts killed or false if none were killed



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'documented/global_defs.rb', line 131

def stop_script(*target_names)
  numkilled = 0
  target_names.each { |target_name|
    condemned = Script.list.find { |s_sock| s_sock.name =~ /^#{target_name}/i }
    if condemned.nil?
      respond("--- Lich: '#{Script.current}' tried to stop '#{target_name}', but it isn't running!")
    else
      if condemned.name =~ /^#{Script.current.name}$/i
        exit
      end
      condemned.kill
      respond("--- Lich: '#{condemned}' has been stopped by #{Script.current}.")
      numkilled += 1
    end
  }
  if numkilled == 0
    return false
  else
    return numkilled
  end
end

#strip_xml(line, type: 'main') ⇒ String?

Strips XML tags from a line.

Parameters:

  • line (String)

    line to strip

  • type (String) (defaults to: 'main')

    type of stripping to perform

Returns:

  • (String, nil)

    stripped line or nil if empty



2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
# File 'documented/global_defs.rb', line 2741

def strip_xml(line, type: 'main')
  return line if line == "\r\n"

  if $strip_xml_multiline[type]
    $strip_xml_multiline[type] = $strip_xml_multiline[type] + line
    line = $strip_xml_multiline[type]
  end
  if (line.scan(/<pushStream[^>]*\/>/).length > line.scan(/<popStream[^>]*\/>/).length)
    $strip_xml_multiline ||= {}
    $strip_xml_multiline[type] = line
    return nil
  end
  $strip_xml_multiline[type] = nil

  line = line.gsub(/<pushStream id=["'](?:spellfront|inv|bounty|society|speech|talk)["'][^>]*\/>.*?<popStream[^>]*>/m, '')
  line = line.gsub(/<stream id="Spells">.*?<\/stream>/m, '')
  line = line.gsub(/<(compDef|inv|component|right|left|spell|prompt)[^>]*>.*?<\/\1>/m, '')
  line = line.gsub(/<[^>]+>/, '')
  line = line.gsub('&gt;', '>')
  line = line.gsub('&lt;', '<')

  return nil if line.gsub("\n", '').gsub("\r", '').gsub(' ', '').length < 1

  return line
end

#survivedisease?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.

Checks if the character can survive disease effects.

Returns:

  • (Boolean)

    always returns true as there is no XML for disease rate.



22
23
24
25
# File 'documented/deprecated.rb', line 22

def survivedisease?
  echo 'survivepoison? called, but there is no XML for disease rate'
  return true
end

#survivepoison?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.

Checks if the character can survive poison effects.

Returns:

  • (Boolean)

    always returns true as there is no XML for poison rate.



13
14
15
16
# File 'documented/deprecated.rb', line 13

def survivepoison?
  echo 'survivepoison? called, but there is no XML for poison rate'
  return true
end

#swString

Returns the string representation of the direction 'southwest'.

Returns:



745
# File 'documented/global_defs.rb', line 745

def sw;   'southwest'; end

#take(*items) ⇒ void

This method returns an undefined value.

Takes specified items and places them in the user's bag.

Parameters:

  • items (Array)

    the items to take.



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'documented/deprecated.rb', line 62

def take(*items)
  items.flatten!
  if (righthand? && lefthand?)
    weap = checkright
    fput "put my #{checkright} in my #{UserVars.lootsack}"
    unsh = true
  else
    unsh = false
  end
  items.each { |trinket|
    fput "take #{trinket}"
    fput("put my #{trinket} in my #{UserVars.lootsack}") if (righthand? || lefthand?)
  }
  if unsh then fput("take my #{weap} from my #{UserVars.lootsack}") end
end

#TEMP_DIRvoid

This method returns an undefined value.

Cleans up debug logs in the specified temporary directory.

Parameters:

  • temp_dir (String)

    the directory where debug logs are stored.



713
# File 'documented/init.rb', line 713

Lich.cleanup_debug_logs(TEMP_DIR)

#timetest(*contestants) ⇒ Array<Float>

Tests the execution time of provided code blocks.

Parameters:

  • contestants (Array<Proc>)

    code blocks to test

Returns:

  • (Array<Float>)

    execution times for each block



546
547
548
# File 'documented/global_defs.rb', line 546

def timetest(*contestants)
  contestants.collect { |code| start = Time.now; 5000.times { code.call }; Time.now - start }
end

#toggle_echovoid

This method returns an undefined value.

Toggles the echo setting for the current script.



211
212
213
214
# File 'documented/global_defs.rb', line 211

def toggle_echo
  unless (script = Script.current) then respond('--- toggle_echo: Unable to identify calling script.'); return nil; end
  script.no_echo = !script.no_echo
end

#toggle_uniquevoid

This method returns an undefined value.

Toggles the unique setting for the current script.



617
618
619
620
# File 'documented/global_defs.rb', line 617

def toggle_unique
  unless (script = Script.current) then echo 'toggle_unique: cannot identify calling script.'; return nil; end
  script.want_downstream = !script.want_downstream
end

#toggle_upstreamvoid

This method returns an undefined value.

Toggles the upstream listening setting for the current script.



193
194
195
196
# File 'documented/global_defs.rb', line 193

def toggle_upstream
  unless (script = Script.current) then echo 'toggle_upstream: cannot identify calling script.'; return nil; end
  script.want_upstream = !script.want_upstream
end

#uString

Returns the string representation of the direction 'up'.

Returns:



757
# File 'documented/global_defs.rb', line 757

def u;    'up';        end

#undo_before_dyingvoid

This method returns an undefined value.

Removes any previously registered exit procedures.



117
118
119
# File 'documented/global_defs.rb', line 117

def undo_before_dying
  Script.clear_exit_procs
end

#unique_getString

Retrieves a unique line from the current script.

Returns:

  • (String)

    the unique line retrieved



703
704
705
706
# File 'documented/global_defs.rb', line 703

def unique_get
  unless (script = Script.current) then echo 'unique_get: cannot identify calling script.'; return nil; end
  script.unique_gets
end

#unique_get?Boolean

Checks if there is a unique line available from the current script.

Returns:

  • (Boolean)

    true if a unique line is available



710
711
712
713
# File 'documented/global_defs.rb', line 710

def unique_get?
  unless (script = Script.current) then echo 'unique_get: cannot identify calling script.'; return nil; end
  script.unique_gets?
end

#unique_send_to_script(*values) ⇒ Boolean

Sends unique values to a specified script.

Parameters:

  • values (Array<String>)

    values to send

Returns:

  • (Boolean)

    true if successful, false otherwise



673
674
675
676
677
678
679
680
681
682
683
# File 'documented/global_defs.rb', line 673

def unique_send_to_script(*values)
  values.flatten!
  if (script = Script.list.find { |val| val.name =~ /^#{values.first}/i })
    values[1..-1].each { |val| script.unique_buffer.push(val) }
    echo("sent to #{script}: #{values[1..-1].join(' ; ')}")
    return true
  else
    echo("'#{values.first}' does not match any active scripts!")
    return false
  end
end

#unique_waitfor(*strings) ⇒ String

Waits for a unique line from the current script that matches specified strings.

Parameters:

  • strings (Array<String>)

    strings to match

Returns:



689
690
691
692
693
694
695
696
697
698
699
# File 'documented/global_defs.rb', line 689

def unique_waitfor(*strings)
  unless (script = Script.current) then echo 'unique_waitfor: cannot identify calling script.'; return nil; end
  strings.flatten!
  regexp = /#{strings.join('|')}/
  while true
    str = script.unique_gets
    if str =~ regexp
      return str
    end
  end
end

#unnoded_pulseInteger

Calculates the pulse value for unnoded characters.

Returns:

  • (Integer)

    calculated pulse value



2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
# File 'documented/global_defs.rb', line 2414

def unnoded_pulse
  unless XMLData.game =~ /DR/
    if Stats.prof =~ /warrior|rogue|sorcerer/i
      stats = [Skills.smc.to_i, Skills.emc.to_i]
    elsif Stats.prof =~ /empath|bard/i
      stats = [Skills.smc.to_i, Skills.mmc.to_i]
    elsif Stats.prof =~ /wizard/i
      stats = [Skills.emc.to_i, 0]
    elsif Stats.prof =~ /paladin|cleric|ranger/i
      stats = [Skills.smc.to_i, 0]
    else
      stats = [0, 0]
    end
    return (XMLData.max_mana * 15 / 100) + (stats.max / 10) + (stats.min / 20)
  else
    return 0 # this method is not used by DR
  end
end

#unpause_script(*names) ⇒ void Also known as: unpause_scripts

This method returns an undefined value.

Unpauses the specified scripts.

Parameters:

  • names (Array<String>)

    names of scripts to unpause



315
316
317
318
319
320
321
# File 'documented/global_defs.rb', line 315

def unpause_script(*names)
  names.flatten!
  names.each { |scr|
    fnd = Script.list.find { |nm| nm.name =~ /^#{scr}/i }
    fnd.unpause if (fnd.paused and not fnd.nil?)
  }
end

#upString

Returns the string representation of the direction 'up'.

Returns:



761
# File 'documented/global_defs.rb', line 761

def up;   'up'; end

#upstream_getString?

Retrieves data from the upstream for the current script.

Returns:

  • (String, nil)

    data received from upstream or nil if none



232
233
234
235
236
237
238
239
240
# File 'documented/global_defs.rb', line 232

def upstream_get
  unless (script = Script.current) then echo 'upstream_get: cannot identify calling script.'; return nil; end
  unless script.want_upstream
    echo("This script wants to listen to the upstream, but it isn't set as receiving the upstream! This will cause a permanent hang, aborting (ask for the upstream with 'toggle_upstream' in the script)")
    sleep 0.3
    return false
  end
  script.upstream_gets
end

#upstream_get?Boolean

Checks if there is data available from the upstream for the current script.

Returns:

  • (Boolean)

    true if data is available



244
245
246
247
248
249
250
251
# File 'documented/global_defs.rb', line 244

def upstream_get?
  unless (script = Script.current) then echo 'upstream_get: cannot identify calling script.'; return nil; end
  unless script.want_upstream
    echo("This script wants to listen to the upstream, but it isn't set as receiving the upstream! This will cause a permanent hang, aborting (ask for the upstream with 'toggle_upstream' in the script)")
    return false
  end
  script.upstream_gets?
end

#upstream_waitfor(*strings) ⇒ String?

Waits for a line from the upstream that matches specified strings.

Parameters:

  • strings (Array<String>)

    strings to match

Returns:

  • (String, nil)

    matching line or nil if none found



637
638
639
640
641
642
643
644
645
646
647
# File 'documented/global_defs.rb', line 637

def upstream_waitfor(*strings)
  strings.flatten!
  script = Script.current
  unless script.want_upstream then echo("This script wants to listen to the upstream, but it isn't set as receiving the upstream! This will cause a permanent hang, aborting (ask for the upstream with 'toggle_upstream' in the script)"); return false end
  regexpstr = strings.join('|')
  while (line = script.upstream_gets)
    if line =~ /#{regexpstr}/i
      return line
    end
  end
end

#variableHash

Retrieves the variables of the current script.

Returns:

  • (Hash)

    script variables



1819
1820
1821
1822
# File 'documented/global_defs.rb', line 1819

def variable
  unless (script = Script.current) then echo 'variable: cannot identify calling script.'; return nil; end
  script.vars
end

#wString

Returns the string representation of the direction 'west'.

Returns:



749
# File 'documented/global_defs.rb', line 749

def w;    'west';      end

#waitString

Waits for a line from the script's input.

Returns:

  • (String)

    the line received



2024
2025
2026
2027
2028
# File 'documented/global_defs.rb', line 2024

def wait
  unless (script = Script.current) then respond('--- wait: unable to identify calling script.'); return false; end
  script.clear
  return script.gets
end

#wait_until(announce = nil) { ... } ⇒ void

This method returns an undefined value.

Waits until a condition is met, optionally announcing the wait.

Parameters:

  • announce (String, nil) (defaults to: nil)

    optional message to announce

Yields:

  • condition to check



1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
# File 'documented/global_defs.rb', line 1038

def wait_until(announce = nil)
  priosave = Thread.current.priority
  Thread.current.priority = 0
  unless announce.nil? or yield
    respond(announce)
  end
  until yield
    sleep 0.25
  end
  Thread.current.priority = priosave
end

#wait_while(announce = nil) { ... } ⇒ void

This method returns an undefined value.

Waits while a condition is true, optionally announcing the wait.

Parameters:

  • announce (String, nil) (defaults to: nil)

    optional message to announce

Yields:

  • condition to check



1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
# File 'documented/global_defs.rb', line 1055

def wait_while(announce = nil)
  priosave = Thread.current.priority
  Thread.current.priority = 0
  unless announce.nil? or !yield
    respond(announce)
  end
  while yield
    sleep 0.25
  end
  Thread.current.priority = priosave
end

#waitcastrtvoid

This method returns an undefined value.

Waits for casting roundtime to complete.



362
363
364
365
# File 'documented/global_defs.rb', line 362

def waitcastrt
  wait_until { (XMLData.cast_roundtime_end.to_f - Time.now.to_f + XMLData.server_time_offset.to_f) > 0 }
  sleep checkcastrt
end

#waitcastrt?Boolean

Checks if there is casting roundtime and waits if necessary.

Returns:

  • (Boolean)

    true if waiting was necessary



389
390
391
392
393
394
395
396
397
398
# File 'documented/global_defs.rb', line 389

def waitcastrt?
  #  sleep checkcastrt
  current_castrt = checkcastrt
  if current_castrt.to_f > 0.0
    sleep(current_castrt)
    return true
  else
    return false
  end
end

#waitfor(*strings) ⇒ String

Waits for a line from the script's input that matches specified strings.

Parameters:

  • strings (Array<String>)

    strings to match

Returns:



2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
# File 'documented/global_defs.rb', line 2004

def waitfor(*strings)
  unless (script = Script.current) then respond('--- waitfor: Unable to identify calling script.'); return false; end
  strings.flatten!
  if (script.is_a?(WizardScript)) and (strings.length == 1) and (strings.first.strip == '>')
    return script.gets
  end

  if strings.empty?
    echo 'waitfor: no string to wait for'
    return false
  end
  regexpstr = strings.join('|')
  while true
    line_in = script.gets
    if (line_in =~ /#{regexpstr}/i) then return line_in end
  end
end

#waitforre(regexp) ⇒ String

Waits for a line from the script's input that matches a regular expression.

Parameters:

  • regexp (Regexp)

    regular expression to match

Returns:



1994
1995
1996
1997
1998
# File 'documented/global_defs.rb', line 1994

def waitforre(regexp)
  unless (script = Script.current) then respond('--- waitforre: Unable to identify calling script.'); return false; end
  unless regexp.is_a?(Regexp) then echo("Script error! You have given 'waitforre' something to wait for, but it isn't a Regular Expression! Use 'waitfor' if you want to wait for a string."); sleep 1; return nil end
  regobj = regexp.match(script.gets) until regobj
end

#waitrtvoid

This method returns an undefined value.

Waits for roundtime to complete.



355
356
357
358
# File 'documented/global_defs.rb', line 355

def waitrt
  wait_until { (XMLData.roundtime_end.to_f - Time.now.to_f + XMLData.server_time_offset.to_f) > 0 }
  sleep checkrt
end

#waitrt?Boolean

Checks if there is roundtime and waits if necessary.

Returns:

  • (Boolean)

    true if waiting was necessary



381
382
383
384
385
# File 'documented/global_defs.rb', line 381

def waitrt?
  sleep checkrt
  return true if checkrt > 0.0
  return false if checkrt == 0
end

#walk(*boundaries) { ... } ⇒ void

This method returns an undefined value.

Walks in a direction until a condition is met.

Parameters:

  • boundaries (Array<String>)

    optional boundaries to check

Yields:

  • condition to check



1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
# File 'documented/global_defs.rb', line 1122

def walk(*boundaries, &block)
  boundaries.flatten!
  unless block.nil?
    until (val = yield)
      walk(*boundaries)
    end
    return val
  end
  if $last_dir and !boundaries.empty? and checkroomdescrip =~ /#{boundaries.join('|')}/i
    move($last_dir)
    $last_dir = reverse_direction($last_dir)
    return checknpcs
  end
  dirs = checkpaths
  return checknpcs if dirs.is_a?(FalseClass)
  dirs.delete($last_dir) unless dirs.length < 2
  this_time = rand(dirs.length)
  $last_dir = reverse_direction(dirs[this_time])
  move(dirs[this_time])
  checknpcs
end

#watchhealth(value, theproc = nil) { ... } ⇒ void

This method returns an undefined value.

Monitors the character's health and executes a block when health drops below a threshold.

Parameters:

  • value (Integer)

    health threshold to monitor

  • theproc (Proc, nil) (defaults to: nil)

    optional procedure to execute

Yields:

  • code to execute when health drops below the threshold



1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
# File 'documented/global_defs.rb', line 1017

def watchhealth(value, theproc = nil, &block)
  value = value.to_i
  if block.nil?
    if !theproc.respond_to? :call
      respond "`watchhealth' was not given a block or a proc to execute!"
      return nil
    else
      block = theproc
    end
  end
  Thread.new {
    wait_while { health(value) }
    block.call
  }
end