Top Level Namespace

Includes:
Win32

Defined Under Namespace

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

Constant Summary collapse

HAVE_GTK =
false
DELETE_CANDIDATES =

Regular expression to match debug log files for deletion. This is used to limit the number of debug files kept.

%r[^debug(?:-\d+)+\.log$]
LICH_VERSION =

The current version of the Lich5 project following semantic versioning.

Examples:

Accessing the version

puts LICH_VERSION
'5.12.12'
REQUIRED_RUBY =

The minimum required Ruby version for the Lich5 project.

Examples:

Checking Ruby version

if RUBY_VERSION < REQUIRED_RUBY
  puts "Upgrade Ruby to at least #{REQUIRED_RUBY}"
end
'2.6'
'3.2'
TESTING =

Indicates whether the project is in testing mode

Returns:

  • (Boolean)

    false if not in testing mode.

false
DIRMAP =

transcoding migrated 2024-06-13 A mapping of direction abbreviations to single-character codes

Returns:

  • (Hash)

    A hash mapping direction strings to their corresponding codes.

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

Returns A hash mapping full direction names to their short forms.

Returns:

  • (Hash)

    A hash mapping full direction names to their short forms.

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

Returns A hash mapping direction abbreviations to their full names.

Returns:

  • (Hash)

    A hash mapping direction abbreviations to their full names.

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

Returns A hash mapping mental state descriptions to their corresponding codes.

Returns:

  • (Hash)

    A hash mapping mental state descriptions to their corresponding codes.

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

Returns A hash mapping icon names to their corresponding codes.

Returns:

  • (Hash)

    A hash mapping icon names to their corresponding codes.

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

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

Methods included from Win32

AdminShellExecute, CreateProcess, GetCurrentProcess, GetExitCodeProcess, GetLastError, GetModuleFileName, GetTokenInformation, GetVersionEx, MessageBox, OpenProcessToken, RegCloseKey, RegDeleteValue, RegOpenKeyEx, RegQueryValueEx, RegSetValueEx, ShellExecute, ShellExecuteEx, admin?, isXP?

Instance Method Details

#_echo(*messages) ⇒ void

This method returns an undefined value.

Sends a message to the current script’s output without formatting.

Examples:

_echo("Raw message")

Parameters:

  • messages (Array<String>)

    The messages to send.



239
240
241
242
243
244
245
246
247
248
249
# File 'documented/global_defs.rb', line 239

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 raw response to the game or script output without formatting.

Examples:

_respond("Raw message")

Parameters:

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

    The first message or array of messages to send.

  • messages (Array<String>)

    Additional messages to send.



2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
# File 'documented/global_defs.rb', line 2466

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.

Examples:

abort!


60
61
62
# File 'documented/global_defs.rb', line 60

def abort!
  Script.exit!
end

#alias_deprecatedObject Also known as: reallybleeding?



3303
3304
3305
3306
# File 'documented/global_defs.rb', line 3303

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(&code) ⇒ Object



44
45
46
# File 'documented/global_defs.rb', line 44

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

#bin2dec(n) ⇒ Object



580
581
582
# File 'documented/global_defs.rb', line 580

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

#bound?Boolean

Checks if the character is bound.

Examples:

if bound?; puts "You are bound!"; end

Returns:

  • (Boolean)

    True if bound, false otherwise.



1857
1858
1859
1860
# File 'documented/global_defs.rb', line 1857

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.

Examples:

if calmed?; puts "You are calmed!"; end

Returns:

  • (Boolean)

    True if calmed, false otherwise.



1893
1894
1895
1896
# File 'documented/global_defs.rb', line 1893

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.

Examples:

cast("fireball", "enemy")

Parameters:

  • spell (String, Spell)

    The spell to cast.

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

    The target of the spell.

  • results_of_interest (nil) (defaults to: nil)

    Optional results to consider.

Returns:

  • (Boolean)

    True if the spell was cast successfully, false otherwise.



1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
# File 'documented/global_defs.rb', line 1949

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 mind state.

Examples:

if check_mind("clear"); puts "Mind is clear!"; end

Parameters:

  • string (String) (defaults to: nil)

    Optional string to check against.

Returns:

  • (Boolean, String)

    True if matches, or the mind state if no argument is provided.



1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
# File 'documented/global_defs.rb', line 1182

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) ⇒ String, Boolean

Checks the area description of the current room.

Examples:

area = checkarea

Parameters:

  • strings (Array<String>)

    The area descriptions to check against.

Returns:

  • (String, Boolean)

    The current area description or true if matches.



1537
1538
1539
1540
1541
1542
1543
1544
# File 'documented/global_defs.rb', line 1537

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.

Examples:

if checkbleeding; puts "You are bleeding!"; end

Returns:

  • (Boolean)

    True if bleeding, false otherwise.



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

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

#checkboundBoolean

Checks if the character is bound.

Examples:

if checkbound; puts "You are bound!"; end

Returns:

  • (Boolean)

    True if bound, false otherwise.



1848
1849
1850
1851
# File 'documented/global_defs.rb', line 1848

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.

Examples:

bounty = checkbounty

Returns:

  • (String, nil)

    The bounty task or nil if none.



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

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

#checkcalmedBoolean

Checks if the character is calmed.

Examples:

if checkcalmed; puts "You are calmed!"; end

Returns:

  • (Boolean)

    True if calmed, false otherwise.



1884
1885
1886
1887
# File 'documented/global_defs.rb', line 1884

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

#checkcastrtFloat

Checks the current cast roundtime.

Examples:

remaining = checkcastrt

Returns:

  • (Float)

    The remaining cast roundtime.



353
354
355
# File 'documented/global_defs.rb', line 353

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.

Examples:

if checkcutthroat; puts "You are cutthroat!"; end

Returns:

  • (Boolean)

    True if cutthroat, false otherwise.



1902
1903
1904
1905
# File 'documented/global_defs.rb', line 1902

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.

Examples:

if checkdead; puts "You are dead!"; end

Returns:

  • (Boolean)

    True if dead, false otherwise.



442
443
444
# File 'documented/global_defs.rb', line 442

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

#checkdiseaseBoolean Also known as: diseased?

Checks if the character is diseased.

Examples:

if checkdisease; puts "You are diseased!"; end

Returns:

  • (Boolean)

    True if diseased, false otherwise.



394
395
396
# File 'documented/global_defs.rb', line 394

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

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

Checks the character’s encumbrance level.

Examples:

encumbrance = checkencumbrance

Parameters:

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

    Optional encumbrance description or value to check against.

Returns:

  • (String, Boolean)

    The current encumbrance description or true if matches.



1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
# File 'documented/global_defs.rb', line 1502

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) ⇒ String, Boolean

Checks the area description of the character’s familiar room.

Examples:

fam_area = checkfamarea

Parameters:

  • strings (Array<String>)

    The area descriptions to check against.

Returns:

  • (String, Boolean)

    The current familiar area description or true if matches.



1577
1578
1579
1580
1581
1582
# File 'documented/global_defs.rb', line 1577

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) ⇒ Array<String>, Boolean

Checks the non-player characters (NPCs) in the character’s familiar room.

Examples:

npcs = checkfamnpcs

Parameters:

  • strings (Array<String>)

    The NPC names to check against.

Returns:

  • (Array<String>, Boolean)

    The list of NPCs or false if none found.



1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
# File 'documented/global_defs.rb', line 1617

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, Boolean

Checks the available paths in the character’s familiar room.

Examples:

paths = checkfampaths

Parameters:

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

    The direction to check.

Returns:

  • (Array, Boolean)

    The available paths or false if none exist.



1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
# File 'documented/global_defs.rb', line 1589

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) ⇒ Array<String>, Boolean

Checks the player characters (PCs) in the character’s familiar room.

Examples:

pcs = checkfampcs

Parameters:

  • strings (Array<String>)

    The PC names to check against.

Returns:

  • (Array<String>, Boolean)

    The list of PCs or false if none found.



1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
# File 'documented/global_defs.rb', line 1640

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) ⇒ String, Boolean

Checks the room description of the character’s familiar room.

Examples:

fam_room = checkfamroom

Parameters:

  • strings (Array<String>)

    The room descriptions to check against.

Returns:

  • (String, Boolean)

    The current familiar room description or true if matches.



1606
1607
1608
1609
1610
# File 'documented/global_defs.rb', line 1606

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) ⇒ String

Checks the description of the character’s familiar room.

Examples:

fam_description = checkfamroomdescrip

Parameters:

  • val (Array<String>)

    The descriptions to check against.

Returns:

  • (String)

    The current familiar room description.



1759
1760
1761
1762
1763
1764
1765
1766
# File 'documented/global_defs.rb', line 1759

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 (overloaded mind).

Examples:

if checkfried; puts "Mind is fried!"; end

Returns:

  • (Boolean)

    True if fried, false otherwise.



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

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.

Examples:

if checkgrouped; puts "You are grouped!"; end

Returns:

  • (Boolean)

    True if grouped, false otherwise.



434
435
436
# File 'documented/global_defs.rb', line 434

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

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

Checks the character’s health level.

Examples:

health = checkhealth

Parameters:

  • num (Integer) (defaults to: nil)

    Optional number to compare against.

Returns:

  • (Integer, Boolean)

    The current health or true if above the specified number.



1312
1313
1314
1315
1316
1317
1318
1319
# File 'documented/global_defs.rb', line 1312

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.

Examples:

if checkhidden; puts "You are hidden!"; end

Returns:

  • (Boolean)

    True if hidden, false otherwise.



471
472
473
# File 'documented/global_defs.rb', line 471

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

#checkinvisibleBoolean Also known as: invisible?

Checks if the character is invisible.

Examples:

if checkinvisible; puts "You are invisible!"; end

Returns:

  • (Boolean)

    True if invisible, false otherwise.



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

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

#checkkneelingBoolean Also known as: kneeling?

Checks if the character is kneeling.

Examples:

if checkkneeling; puts "You are kneeling!"; end

Returns:

  • (Boolean)

    True if kneeling, false otherwise.



410
411
412
# File 'documented/global_defs.rb', line 410

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

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

Checks the left hand for a specific item.

Examples:

item = checkleft("shield")

Parameters:

  • hand (Array<String>)

    The items to check against.

Returns:

  • (String, nil)

    The item in the left hand or nil if empty.



1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
# File 'documented/global_defs.rb', line 1727

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.

Examples:

loot = checkloot

Returns:

  • (Array<String>)

    The list of loot items.



533
534
535
# File 'documented/global_defs.rb', line 533

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

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

Checks the character’s mana level.

Examples:

mana = checkmana

Parameters:

  • num (Integer) (defaults to: nil)

    Optional number to compare against.

Returns:

  • (Integer, Boolean)

    The current mana or true if above the specified number.



1270
1271
1272
1273
1274
1275
1276
1277
# File 'documented/global_defs.rb', line 1270

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 mind state with a different method.

Examples:

if checkmind("clear"); puts "Mind is clear!"; end

Parameters:

  • string (String) (defaults to: nil)

    Optional string to check against.

Returns:

  • (Boolean, String)

    True if matches, or the mind state if no argument is provided.



1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
# File 'documented/global_defs.rb', line 1204

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.

Examples:

if checkname("John"); puts "Name matches!"; end

Parameters:

  • strings (Array<String>)

    The names to check against.

Returns:

  • (Boolean, String)

    True if a match is found, or the character’s name if no arguments are provided.



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

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.

Examples:

if checknotstanding; puts "You are not standing!"; end

Returns:

  • (Boolean)

    True if not standing, false otherwise.



503
504
505
# File 'documented/global_defs.rb', line 503

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

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

Checks the non-player characters (NPCs) in the game.

Examples:

npcs = checknpcs

Parameters:

  • strings (Array<String>)

    The NPC names to check against.

Returns:

  • (Array<String>, Boolean)

    The list of NPCs or false if none found.



1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
# File 'documented/global_defs.rb', line 1682

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, Boolean

Checks the available paths in the current room.

Examples:

paths = checkpaths

Parameters:

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

    The direction to check.

Returns:

  • (Array, Boolean)

    The available paths or false if none exist.



1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
# File 'documented/global_defs.rb', line 1094

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) ⇒ Array<String>, Boolean

Checks the player characters (PCs) in the game.

Examples:

pcs = checkpcs

Parameters:

  • strings (Array<String>)

    The PC names to check against.

Returns:

  • (Array<String>, Boolean)

    The list of PCs or false if none found.



1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
# File 'documented/global_defs.rb', line 1663

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.

Examples:

if checkpoison; puts "You are poisoned!"; end

Returns:

  • (Boolean)

    True if poisoned, false otherwise.



386
387
388
# File 'documented/global_defs.rb', line 386

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

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

Checks if a spell is prepared.

Examples:

if checkprep("fireball"); puts "Fireball is prepared!"; end

Parameters:

  • spell (String) (defaults to: nil)

    The name of the spell to check.

Returns:

  • (Boolean, String)

    True if prepared, or the prepared spell if no argument is provided.



1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
# File 'documented/global_defs.rb', line 1786

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.

Examples:

if checkprone; puts "You are prone!"; end

Returns:

  • (Boolean)

    True if prone, false otherwise.



495
496
497
# File 'documented/global_defs.rb', line 495

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

#checkreallybleedingBoolean

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

Examples:

if checkreallybleeding; puts "You are really bleeding!"; end

Returns:

  • (Boolean)

    True if really bleeding, false otherwise.



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 a specific item.

Examples:

item = checkright("sword")

Parameters:

  • hand (Array<String>)

    The items to check against.

Returns:

  • (String, nil)

    The item in the right hand or nil if empty.



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

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) ⇒ String, Boolean

Checks the room description of the current room.

Examples:

room = checkroom

Parameters:

  • strings (Array<String>)

    The room descriptions to check against.

Returns:

  • (String, Boolean)

    The current room description or true if matches.



1551
1552
1553
1554
1555
1556
1557
1558
# File 'documented/global_defs.rb', line 1551

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

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

Checks the description of the current room.

Examples:

description = checkroomdescrip

Parameters:

  • val (Array<String>)

    The descriptions to check against.

Returns:

  • (String)

    The current room description.



1745
1746
1747
1748
1749
1750
1751
1752
# File 'documented/global_defs.rb', line 1745

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

#checkrtFloat

Checks the current roundtime.

Examples:

remaining = checkrt

Returns:

  • (Float)

    The remaining roundtime.



345
346
347
# File 'documented/global_defs.rb', line 345

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 (overloaded mind).

Examples:

if checksaturated; puts "Mind is saturated!"; end

Returns:

  • (Boolean)

    True if saturated, false otherwise.



1257
1258
1259
1260
1261
1262
1263
# File 'documented/global_defs.rb', line 1257

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

#checksilencedBoolean

Checks if the character is silenced.

Examples:

if checksilenced; puts "You are silenced!"; end

Returns:

  • (Boolean)

    True if silenced, false otherwise.



1866
1867
1868
1869
# File 'documented/global_defs.rb', line 1866

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.

Examples:

if checksitting; puts "You are sitting!"; end

Returns:

  • (Boolean)

    True if sitting, false otherwise.



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

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

#checksleepingBoolean

Checks if the character is sleeping.

Examples:

if checksleeping; puts "You are sleeping!"; end

Returns:

  • (Boolean)

    True if sleeping, false otherwise.



1830
1831
1832
1833
# File 'documented/global_defs.rb', line 1830

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 the specified spells are active.

Examples:

if checkspell("fireball"); puts "Fireball is active!"; end

Parameters:

  • spells (Array<String>)

    The spell names to check.

Returns:

  • (Boolean)

    True if all specified spells are active, false otherwise.



1773
1774
1775
1776
1777
1778
1779
# File 'documented/global_defs.rb', line 1773

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) ⇒ Integer, Boolean Also known as: spirit, spirit?

Checks the character’s spirit level.

Examples:

spirit = checkspirit

Parameters:

  • num (Integer) (defaults to: nil)

    Optional number to compare against.

Returns:

  • (Integer, Boolean)

    The current spirit or true if above the specified number.



1349
1350
1351
1352
1353
1354
1355
1356
# File 'documented/global_defs.rb', line 1349

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) ⇒ Integer, Boolean Also known as: stamina, stamina?

Checks the character’s stamina level.

Examples:

stamina = checkstamina

Parameters:

  • num (Integer) (defaults to: nil)

    Optional number to compare against.

Returns:

  • (Integer, Boolean)

    The current stamina or true if above the specified number.



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

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) ⇒ String, Boolean Also known as: stance?, stance

Checks the character’s stance.

Examples:

stance = checkstance

Parameters:

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

    Optional stance value or description to check against.

Returns:

  • (String, Boolean)

    The current stance description or true if matches.



1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
# File 'documented/global_defs.rb', line 1454

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.

Examples:

if checkstanding; puts "You are standing!"; end

Returns:

  • (Boolean)

    True if standing, false otherwise.



511
512
513
# File 'documented/global_defs.rb', line 511

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

#checkstunnedBoolean Also known as: stunned?

Checks if the character is stunned.

Examples:

if checkstunned; puts "You are stunned!"; end

Returns:

  • (Boolean)

    True if stunned, false otherwise.



418
419
420
# File 'documented/global_defs.rb', line 418

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

#checkwebbedBoolean Also known as: webbed?

Checks if the character is webbed.

Examples:

if checkwebbed; puts "You are webbed!"; end

Returns:

  • (Boolean)

    True if webbed, false otherwise.



487
488
489
# File 'documented/global_defs.rb', line 487

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

#clear(_opt = 0) ⇒ Array

Clears the downstream buffer of the current script.

Examples:

buffer = clear

Parameters:

  • _opt (Integer) (defaults to: 0)

    Optional parameter for clearing.

Returns:

  • (Array)

    The cleared buffer.



1967
1968
1969
1970
1971
1972
# File 'documented/global_defs.rb', line 1967

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.

Examples:

count = count_npcs

Returns:

  • (Integer)

    The count of NPCs.



1700
1701
1702
# File 'documented/global_defs.rb', line 1700

def count_npcs
  checknpcs.length
end

#cutthroat?Boolean

Checks if the character is cutthroat.

Examples:

if cutthroat?; puts "You are cutthroat!"; end

Returns:

  • (Boolean)

    True if cutthroat, false otherwise.



1911
1912
1913
1914
# File 'documented/global_defs.rb', line 1911

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

#dString

Represents the down direction.

Examples:

direction = d

Returns:



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

def d;    'down';      end

#debug(*args) ⇒ void

This method returns an undefined value.

Outputs debug information if debugging is enabled.

Examples:

debug("Debugging info")

Parameters:

  • args (Array)

    The arguments to output.



552
553
554
555
556
557
558
559
560
# File 'documented/global_defs.rb', line 552

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.

Examples:

binary = dec2bin(10)

Parameters:

  • n (Integer)

    The decimal number to convert.

Returns:

  • (String)

    The binary representation of the number.



576
577
578
# File 'documented/global_defs.rb', line 576

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 with the current script.

Examples:

die_with_me("script1", "script2")

Parameters:

  • vals (Array<String>)

    The names of the scripts to register.



654
655
656
657
658
659
# File 'documented/global_defs.rb', line 654

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

#do_client(client_string) ⇒ Object



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
3223
3224
3225
3226
3227
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
# File 'documented/global_defs.rb', line 2911

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 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 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}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"
      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 =~ /^(?:wizard|avalon)$/) 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.

Examples:

result = dothis("action", "success line")

Parameters:

  • action (String)

    The action to perform.

  • success_line (String)

    The line indicating success.

Returns:

  • (String)

    The line received upon success.



2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
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
# File 'documented/global_defs.rb', line 2637

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.

Examples:

result = dothistimeout("action", 5, "success line")

Parameters:

  • action (String)

    The action to perform.

  • timeout (Numeric)

    The timeout duration in seconds.

  • success_line (String)

    The line indicating success.

Returns:

  • (String, nil)

    The line received upon success or nil if timeout occurs.



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
2735
2736
2737
2738
2739
2740
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
2766
# File 'documented/global_defs.rb', line 2701

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

#downObject



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

def down; 'down';      end

#eObject



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

def e;    'east';      end

#echo(*messages) ⇒ Object



222
223
224
225
226
227
228
229
230
231
232
# File 'documented/global_defs.rb', line 222

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 echo for the current script.

Examples:

echo_off


190
191
192
193
# File 'documented/global_defs.rb', line 190

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_onString, void

Represents the east direction. Turns on echo for the current script.

Examples:

direction = e
echo_on

Returns:

  • (String)

    “east”

  • (void)


181
182
183
184
# File 'documented/global_defs.rb', line 181

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_handvoid

This method returns an undefined value.

Empties the character’s hand based on conditions.

Examples:

empty_hand


2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
# File 'documented/global_defs.rb', line 2562

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 both hands of the character.

Examples:

empty_hands


2553
2554
2555
2556
# File 'documented/global_defs.rb', line 2553

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.

Examples:

empty_left_hand


2590
2591
2592
2593
# File 'documented/global_defs.rb', line 2590

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

#empty_right_handvoid

This method returns an undefined value.

Empties the character’s right hand.

Examples:

empty_right_hand


2581
2582
2583
2584
# File 'documented/global_defs.rb', line 2581

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

#fb_to_sf(line) ⇒ Object



2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
# File 'documented/global_defs.rb', line 2773

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 stores it in the user’s bag.

Examples:

fetchloot
fetchloot("my_custom_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.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'documented/deprecated.rb', line 36

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_handvoid

This method returns an undefined value.

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

Examples:

fill_hand


2608
2609
2610
2611
# File 'documented/global_defs.rb', line 2608

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

#fill_handsvoid

This method returns an undefined value.

Fills both hands of the character with items.

Examples:

fill_hands


2599
2600
2601
2602
# File 'documented/global_defs.rb', line 2599

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.

Examples:

fill_left_hand


2626
2627
2628
2629
# File 'documented/global_defs.rb', line 2626

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.

Examples:

fill_right_hand


2617
2618
2619
2620
# File 'documented/global_defs.rb', line 2617

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

#fix_injury_modeObject



293
294
295
296
297
298
# File 'documented/global_defs.rb', line 293

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.

Examples:

force_start_script("my_script", ["--option1", "value1"])

Parameters:

  • script_name (String)

    The name of the script to force start.

  • cli_vars (Array) (defaults to: [])

    The command line variables to pass to the script.

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

    Optional flags for script execution.



38
39
40
41
42
# File 'documented/global_defs.rb', line 38

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 script’s input and waits for a response.

Examples:

response = fput("command", ["success", "failure"])

Parameters:

  • message (String)

    The command to send.

  • waitingfor (Array<String>)

    The responses to wait for.

Returns:

  • (String, nil)

    The response received or nil if no response.



2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
# File 'documented/global_defs.rb', line 2222

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

  while (string = get)
    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.

Examples:

line = get

Returns:

  • (String)

    The line received.



2150
2151
2152
# File 'documented/global_defs.rb', line 2150

def get
  Script.current.gets
end

#get?Boolean

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

Examples:

if get?; puts "Line available!"; end

Returns:

  • (Boolean)

    True if a line is available, false otherwise.



2158
2159
2160
# File 'documented/global_defs.rb', line 2158

def get?
  Script.current.gets?
end

#goto(label) ⇒ void

This method returns an undefined value.

Jumps to a specified label in the current script.

Examples:

goto("my_label")

Parameters:

  • label (String)

    The label to jump to.

Raises:



257
258
259
260
# File 'documented/global_defs.rb', line 257

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

#hide_mevoid

This method returns an undefined value.

prior to 2024 Toggles the visibility of the current script.

Examples:

hide_me


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

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

#hide_script(*args) ⇒ void

This method returns an undefined value.

Toggles the hidden state of the specified scripts.

Examples:

hide_script("script1", "script2")

Parameters:

  • args (Array<String>)

    The names of the scripts to hide.



305
306
307
308
309
310
311
312
# File 'documented/global_defs.rb', line 305

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 state for the current script.

Examples:

if i_stand_alone; puts "I stand alone!"; end

Returns:

  • (Boolean)

    True if the script stands alone, false otherwise.



541
542
543
544
545
# File 'documented/global_defs.rb', line 541

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 is idle for a specified time.

Examples:

if idle?(60); puts "Idle for 60 seconds!"; end

Parameters:

  • time (Integer) (defaults to: 60)

    The idle time in seconds.

Returns:

  • (Boolean)

    True if idle, false otherwise.



589
590
591
# File 'documented/global_defs.rb', line 589

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

#key_exists?(path) ⇒ Boolean

Checks if a registry key exists.

Parameters:

  • path (String)

    The registry path to check.

Returns:

  • (Boolean)

    true if the key exists, false otherwise.

Raises:

  • (StandardError)

    if there is an error accessing the registry.



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 strings.

Examples:

matched_line = match("label", "input")

Parameters:

  • label (String)

    The label to match against.

  • string (String)

    The string to match.

Returns:

  • (String, nil)

    The matched line or nil if no match.



1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
# File 'documented/global_defs.rb', line 1980

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 string.

Examples:

matched_line = matchafter("input")

Parameters:

  • strings (Array<String>)

    The strings to match against.

Returns:

  • (String)

    The matched line.



2052
2053
2054
2055
2056
2057
2058
# File 'documented/global_defs.rb', line 2052

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 string.

Examples:

matched_line = matchbefore("input")

Parameters:

  • strings (Array<String>)

    The strings to match against.

Returns:

  • (String)

    The matched line.



2039
2040
2041
2042
2043
2044
2045
# File 'documented/global_defs.rb', line 2039

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 strings.

Examples:

matched_lines = matchboth("input1", "input2")

Parameters:

  • strings (Array<String>)

    The strings to match against.

Returns:

  • (Array<String>)

    The matched lines.



2065
2066
2067
2068
2069
2070
2071
2072
# File 'documented/global_defs.rb', line 2065

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 strings.

Examples:

matched_line = matchfind("input1", "input2")

Parameters:

  • strings (Array<String>)

    The strings to match against.

Returns:

  • (String, nil)

    The matched line or nil if no match.



2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
# File 'documented/global_defs.rb', line 2335

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 strings exactly.

Examples:

matched_line = matchfindexact("input1", "input2")

Parameters:

  • strings (Array<String>)

    The strings to match against.

Returns:

  • (String, nil)

    The matched line or nil if no match.



2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
# File 'documented/global_defs.rb', line 2304

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 line from the script’s input against specified words.

Examples:

matched_word = matchfindword("word1", "word2")

Parameters:

  • strings (Array<String>)

    The words to match against.

Returns:

  • (String, nil)

    The matched word or nil if no match.



2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
# File 'documented/global_defs.rb', line 2358

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 strings with a timeout.

Examples:

matched_line = matchtimeout(5, "input")

Parameters:

  • secs (Numeric)

    The timeout duration in seconds.

  • strings (Array<String>)

    The strings to match against.

Returns:

  • (String, nil)

    The matched line or nil if timeout occurs.



2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
# File 'documented/global_defs.rb', line 2007

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 matching specified strings.

Examples:

matched_line = matchwait("input")

Parameters:

  • strings (Array<String>)

    The strings to match against.

Returns:

  • (String)

    The matched line.



2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
# File 'documented/global_defs.rb', line 2079

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.

Examples:

max_concentration = maxconcentration

Returns:

  • (Integer)

    The maximum concentration.



1427
1428
1429
# File 'documented/global_defs.rb', line 1427

def maxconcentration()
  XMLData.max_concentration
end

#maxhealthInteger

Retrieves the maximum health of the character.

Examples:

max_health = maxhealth

Returns:

  • (Integer)

    The maximum health.



1325
1326
1327
1328
# File 'documented/global_defs.rb', line 1325

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.

Examples:

max_mana = maxmana

Returns:

  • (Integer)

    The maximum mana.



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

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

#maxspiritInteger

Retrieves the maximum spirit of the character.

Examples:

max_spirit = maxspirit

Returns:

  • (Integer)

    The maximum spirit.



1362
1363
1364
1365
# File 'documented/global_defs.rb', line 1362

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

#maxstaminaInteger

Retrieves the maximum stamina of the character.

Examples:

max_stamina = maxstamina

Returns:

  • (Integer)

    The maximum stamina.



1399
1400
1401
1402
# File 'documented/global_defs.rb', line 1399

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

#monsterbold_endObject



2901
2902
2903
2904
2905
2906
2907
2908
2909
# File 'documented/global_defs.rb', line 2901

def monsterbold_end
  if $frontend =~ /^(?:wizard|avalon)$/
    "\034GSM\r\n"
  elsif $frontend =~ /^(?:stormfront|frostbite|wrayth|profanity|genie)$/
    '<popBold/>'
  else
    ''
  end
end

#monsterbold_startObject



2891
2892
2893
2894
2895
2896
2897
2898
2899
# File 'documented/global_defs.rb', line 2891

def monsterbold_start
  if $frontend =~ /^(?:wizard|avalon)$/
    "\034GSL\r\n"
  elsif $frontend =~ /^(?:stormfront|frostbite|wrayth|profanity|genie)$/
    '<pushBold/>'
  else
    ''
  end
end

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

Moves the character in the specified direction.

Examples:

move("north")

Parameters:

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

    The direction to move in.

  • giveup_seconds (Integer) (defaults to: 10)

    The time to wait before giving up.

  • giveup_lines (Integer) (defaults to: 30)

    The number of lines to wait before giving up.

Returns:

  • (Boolean, nil)

    True if the move was successful, false if failed, nil if the direction shouldn’t be removed from the map database.



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
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
# File 'documented/global_defs.rb', line 806

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/
      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.

Examples:

if muckled?; puts "You are muckled!"; end

Returns:

  • (Boolean)

    True if muckled, false otherwise.



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

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 script’s input.

Examples:

multifput("command1", "command2")

Parameters:

  • cmds (Array<String>)

    The commands to send.



2212
2213
2214
# File 'documented/global_defs.rb', line 2212

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

#multimove(*dirs) ⇒ Object



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

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

#nObject



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

def n;    'north';     end

#neObject



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

def ne;   'northeast'; end

#no_kill_allString, void

Represents the north direction. Toggles the no-kill-all state for the current script.

Examples:

direction = n
no_kill_all

Returns:

  • (String)

    “north”

  • (void)


128
129
130
131
# File 'documented/global_defs.rb', line 128

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 state for the current script.

Examples:

no_pause_all


137
138
139
140
# File 'documented/global_defs.rb', line 137

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

#noded_pulseInteger

Calculates the node pulse for the character based on their stats.

Examples:

pulse = noded_pulse

Returns:

  • (Integer)

    The calculated node pulse value.



2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
# File 'documented/global_defs.rb', line 2505

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

Represents the northwest direction.

Examples:

direction = nw

Returns:

  • (String)

    “northwest”



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

def nw;   'northwest'; end

#oString

Represents the out direction.

Examples:

direction = o

Returns:



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

def o;    'out';       end

#outString

Represents the out direction.

Examples:

direction = out

Returns:



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

def out;  'out';       end

#outside?Boolean Also known as: checkoutside

Checks if the character is outside.

Examples:

if outside?; puts "You are outside!"; end

Returns:

  • (Boolean)

    True if outside, false otherwise.



1564
1565
1566
1567
1568
1569
1570
# File 'documented/global_defs.rb', line 1564

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

#parse_list(string) ⇒ Array

Parses a string into a list format.

Examples:

list = parse_list("item1, item2, item3")

Parameters:

  • string (String)

    The string to parse.

Returns:

  • (Array)

    The parsed list.



319
320
321
# File 'documented/global_defs.rb', line 319

def parse_list(string)
  string.split_as_list
end

#pause(num = 1) ⇒ void

This method returns an undefined value.

Pauses the execution for a specified duration.

Examples:

pause("1m")

Parameters:

  • num (String) (defaults to: 1)

    The duration to pause, can include ‘m’ for minutes, ‘h’ for hours, ‘d’ for days.



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

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.

Examples:

pause_script("script1", "script2")

Parameters:

  • names (Array<String>)

    The names of the scripts to pause.



267
268
269
270
271
272
273
274
275
276
277
278
# File 'documented/global_defs.rb', line 267

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) ⇒ Integer, Boolean

Checks the percentage of concentration fullness.

Examples:

percent = percentconcentration

Parameters:

  • num (Integer) (defaults to: nil)

    Optional number to compare against.

Returns:

  • (Integer, Boolean)

    The current concentration percentage or true if above the specified number.



1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
# File 'documented/global_defs.rb', line 1436

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) ⇒ Integer, Boolean

Checks the percentage of encumbrance fullness.

Examples:

percent = percentencumbrance

Parameters:

  • num (Integer) (defaults to: nil)

    Optional number to compare against.

Returns:

  • (Integer, Boolean)

    The current encumbrance percentage or true if above the specified number.



1523
1524
1525
1526
1527
1528
1529
1530
# File 'documented/global_defs.rb', line 1523

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) ⇒ Integer, Boolean

Checks the percentage of health fullness.

Examples:

percent = percenthealth

Parameters:

  • num (Integer) (defaults to: nil)

    Optional number to compare against.

Returns:

  • (Integer, Boolean)

    The current health percentage or true if above the specified number.



1335
1336
1337
1338
1339
1340
1341
1342
# File 'documented/global_defs.rb', line 1335

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) ⇒ Integer, Boolean

Checks the percentage of mana fullness.

Examples:

percent = percentmana

Parameters:

  • num (Integer) (defaults to: nil)

    Optional number to compare against.

Returns:

  • (Integer, Boolean)

    The current mana percentage or true if above the specified number.



1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
# File 'documented/global_defs.rb', line 1293

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) ⇒ Integer, Boolean

Checks the percentage of mind fullness.

Examples:

percent = percentmind

Parameters:

  • num (Integer) (defaults to: nil)

    Optional number to compare against.

Returns:

  • (Integer, Boolean)

    The current mind percentage or true if above the specified number.



1233
1234
1235
1236
1237
1238
1239
# File 'documented/global_defs.rb', line 1233

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

#percentspirit(num = nil) ⇒ Integer, Boolean

Checks the percentage of spirit fullness.

Examples:

percent = percentspirit

Parameters:

  • num (Integer) (defaults to: nil)

    Optional number to compare against.

Returns:

  • (Integer, Boolean)

    The current spirit percentage or true if above the specified number.



1372
1373
1374
1375
1376
1377
1378
1379
# File 'documented/global_defs.rb', line 1372

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) ⇒ Integer, Boolean

Checks the percentage of stamina fullness.

Examples:

percent = percentstamina

Parameters:

  • num (Integer) (defaults to: nil)

    Optional number to compare against.

Returns:

  • (Integer, Boolean)

    The current stamina percentage or true if above the specified number.



1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
# File 'documented/global_defs.rb', line 1409

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) ⇒ Integer, Boolean

Checks the percentage of stance fullness.

Examples:

percent = percentstance

Parameters:

  • num (Integer) (defaults to: nil)

    Optional number to compare against.

Returns:

  • (Integer, Boolean)

    The current stance percentage or true if above the specified number.



1488
1489
1490
1491
1492
1493
1494
1495
# File 'documented/global_defs.rb', line 1488

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 a message to the game.

Examples:

put("Hello, world!")

Parameters:

  • messages (Array<String>)

    The messages to send.



2286
2287
2288
# File 'documented/global_defs.rb', line 2286

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

#quiet_exitvoid

This method returns an undefined value.

Toggles the quiet exit state for the current script.

Examples:

quiet_exit


2294
2295
2296
2297
# File 'documented/global_defs.rb', line 2294

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

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

Retrieves lines from the script’s input based on specified criteria.

Examples:

lines = reget("input1", "input2")

Parameters:

  • lines (Array<String>)

    The lines to retrieve.

Returns:

  • (Array<String>, nil)

    The retrieved lines or nil if none found.



2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
# File 'documented/global_defs.rb', line 2167

def reget(*lines)
  unless (script = Script.current) then 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
    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 script’s input based on specified criteria.

Examples:

lines = regetall("input1", "input2")

Parameters:

  • lines (Array<String>)

    The lines to retrieve.

Returns:

  • (Array<String>, nil)

    The retrieved lines or nil if none found.



2203
2204
2205
# File 'documented/global_defs.rb', line 2203

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

#report_errors(&block) ⇒ void

This method returns an undefined value.

Executes a block of code with comprehensive error handling and logging.

Catches and reports various types of errors including StandardError, SyntaxError, SecurityError, ThreadError, and SystemStackError. Errors are both logged to the Lich log and displayed to the user via respond.

Examples:

report_errors { risky_operation() }

Parameters:

  • block (Proc)

    The block of code to execute with error handling



3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
# File 'documented/global_defs.rb', line 3265

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 game or script output.

Examples:

respond("Hello, world!")

Parameters:

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

    The first message or array of messages to send.

  • messages (Array<String>)

    Additional messages to send.



2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
# File 'documented/global_defs.rb', line 2419

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 == 'stormfront' || $frontend == 'genie'
      str = "<output class=\"mono\"/>\r\n#{str.gsub('&', '&amp;').gsub('<', '&lt;').gsub('>', '&gt;')}<output class=\"\"/>\r\n"
    elsif $frontend == '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.

Examples:

reversed = reverse_direction("north")

Parameters:

  • dir (String)

    The direction to reverse.

Returns:

  • (String, false)

    The reversed direction or false if unrecognized.



1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
# File 'documented/global_defs.rb', line 1111

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 walking loop until stopped.

Examples:

run


1173
1174
1175
# File 'documented/global_defs.rb', line 1173

def run
  loop { break unless walk }
end

#running?(*snames) ⇒ Boolean

Checks if the specified scripts are currently running.

Examples:

running?("script1", "script2")

Parameters:

  • snames (Array<String>)

    The names of the scripts to check.

Returns:

  • (Boolean)

    True if all specified scripts are running, false otherwise.



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

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

#sObject



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

def s;    'south';     end

#seObject



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

def se;   'southeast'; end

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

Represents the southeast direction. Sends a command and waits for a response matching success or failure criteria.

Examples:

direction = se
response = selectput("command", ["success"], ["failure"], 5)

Parameters:

  • string (String)

    The command to send.

  • success (Array<String>)

    The success responses to match.

  • failure (Array<String>)

    The failure responses to match.

  • timeout (Numeric) (defaults to: nil)

    Optional timeout in seconds.

Returns:

  • (String)

    “southeast”

  • (String, nil)

    The response received or nil on timeout.

Raises:

  • (ArgumentError)

    If parameters are invalid.



606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
# File 'documented/global_defs.rb', line 606

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) ⇒ Boolean Also known as: send_script

Sends messages to multiple scripts.

Examples:

send_scripts("message1", "message2")

Parameters:

  • messages (Array<String>)

    The messages to send.

Returns:

  • (Boolean)

    True if sent successfully, false otherwise.



2381
2382
2383
2384
2385
2386
2387
# File 'documented/global_defs.rb', line 2381

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.

Examples:

send_to_script("script1", "value1", "value2")

Parameters:

  • values (Array)

    The values to send, with the first being the script name.

Returns:

  • (Boolean)

    True if sent successfully, false otherwise.



683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
# File 'documented/global_defs.rb', line 683

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.

Examples:

current_priority = setpriority(2)

Parameters:

  • val (Integer) (defaults to: nil)

    The priority value to set.

Returns:

  • (Integer)

    The current priority after setting.



1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
# File 'documented/global_defs.rb', line 1802

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) ⇒ Object



2790
2791
2792
2793
2794
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
# File 'documented/global_defs.rb', line 2790

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 silent state for the current script.

Examples:

silence_me


155
156
157
158
159
160
161
162
# File 'documented/global_defs.rb', line 155

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.

Examples:

if silenced?; puts "You are silenced!"; end

Returns:

  • (Boolean)

    True if silenced, false otherwise.



1875
1876
1877
1878
# File 'documented/global_defs.rb', line 1875

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.

Examples:

if sleeping?; puts "You are sleeping!"; end

Returns:

  • (Boolean)

    True if sleeping, false otherwise.



1839
1840
1841
1842
# File 'documented/global_defs.rb', line 1839

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 the given command data.

Examples:

start_exec_script("some_command", { option: true })

Parameters:

  • cmd_data (String)

    The command data to execute.

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

    Optional execution options.



107
108
109
# File 'documented/global_defs.rb', line 107

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

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

Represents the south direction.

Examples:

direction = s

Returns:



12
13
14
15
16
17
# File 'documented/global_defs.rb', line 12

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.

Examples:

start_scripts("script1", "script2")

Parameters:

  • script_names (Array<String>)

    The names of the scripts to start.



24
25
26
27
28
29
# File 'documented/global_defs.rb', line 24

def start_scripts(*script_names)
  script_names.flatten.each { |script_name|
    start_script(script_name)
    sleep 0.02
  }
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.

Examples:

status_tags("on")

Parameters:

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

    The state to set, can be “on” or “off”.



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

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.

Examples:

stop_script("my_script")

Parameters:

  • target_names (Array<String>)

    The names of the scripts to stop.

Returns:

  • (Integer, false)

    The number of scripts killed or false if none were found.



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'documented/global_defs.rb', line 69

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') ⇒ Object



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

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

Checks if the character can survive disease.

Examples:

result = survivedisease?
puts result # => true

Returns:

  • (Boolean)

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



25
26
27
28
# File 'documented/deprecated.rb', line 25

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

#survivepoison?Boolean

Checks if the character can survive poison.

Examples:

result = survivepoison?
puts result # => true

Returns:

  • (Boolean)

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



15
16
17
18
# File 'documented/deprecated.rb', line 15

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

#swObject



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

def sw;   'southwest'; end

#take(*items) ⇒ void

This method returns an undefined value.

Takes items and stores them in the user’s bag.

Examples:

take("item1", "item2")

Parameters:

  • items (Array<String>)

    The items to take.



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'documented/deprecated.rb', line 68

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

#timetest(*contestants) ⇒ Array<Float>

Tests the execution time of provided code blocks.

Examples:

times = timetest(-> { sleep(1) }, -> { sleep(2) })

Parameters:

  • contestants (Array<Proc>)

    The code blocks to test.

Returns:

  • (Array<Float>)

    The execution times for each block.



567
568
569
# File 'documented/global_defs.rb', line 567

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 state for the current script.

Examples:

toggle_echo


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

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 state for the current script.

Examples:

toggle_unique


644
645
646
647
# File 'documented/global_defs.rb', line 644

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 state for the current script.

Examples:

toggle_upstream


146
147
148
149
# File 'documented/global_defs.rb', line 146

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

#uObject



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

def u;    'up';        end

#undo_before_dyingString

Represents the up direction.

Examples:

direction = u

Returns:



52
53
54
# File 'documented/global_defs.rb', line 52

def undo_before_dying
  Script.clear_exit_procs
end

#unique_getObject



733
734
735
736
# File 'documented/global_defs.rb', line 733

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, String

Checks if there is unique data available from the current script. Retrieves unique data from the current script.

Examples:

if unique_get?; puts "Unique data available!"; end
data = unique_get

Returns:

  • (Boolean)

    True if data is available, false otherwise.

  • (String)

    The unique data received.



746
747
748
749
# File 'documented/global_defs.rb', line 746

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

Uniquely sends values to a specified script.

Examples:

unique_send_to_script("script1", "value1", "value2")

Parameters:

  • values (Array)

    The values to send, with the first being the script name.

Returns:

  • (Boolean)

    True if sent successfully, false otherwise.



704
705
706
707
708
709
710
711
712
713
714
# File 'documented/global_defs.rb', line 704

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 unique data from the current script.

Examples:

line = unique_waitfor("data1", "data2")

Parameters:

  • strings (Array<String>)

    The strings to match against.

Returns:

  • (String)

    The matching line.



721
722
723
724
725
726
727
728
729
730
731
# File 'documented/global_defs.rb', line 721

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 unnoded pulse for the character based on their stats.

Examples:

pulse = unnoded_pulse

Returns:

  • (Integer)

    The calculated unnoded pulse value.



2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
# File 'documented/global_defs.rb', line 2528

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.

Examples:

unpause_script("script1", "script2")

Parameters:

  • names (Array<String>)

    The names of the scripts to unpause.



285
286
287
288
289
290
291
# File 'documented/global_defs.rb', line 285

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

#upObject



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

def up;   'up'; end

#upstream_getString

Represents the up direction.

Examples:

direction = up

Returns:



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

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 the current script is set to listen to upstream data.

Examples:

is_listening = upstream_get?

Returns:

  • (Boolean)

    True if listening, false otherwise.



213
214
215
216
217
218
219
220
# File 'documented/global_defs.rb', line 213

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 upstream data matching the specified strings.

Examples:

line = upstream_waitfor("data1", "data2")

Parameters:

  • strings (Array<String>)

    The strings to match against.

Returns:

  • (String, nil)

    The matching line or nil if not found.



666
667
668
669
670
671
672
673
674
675
676
# File 'documented/global_defs.rb', line 666

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.

Examples:

vars = variable

Returns:

  • (Hash)

    The script’s variables.



1920
1921
1922
1923
# File 'documented/global_defs.rb', line 1920

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

#wObject



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

def w;    'west';      end

#waitString

Waits for a line from the script’s input.

Examples:

line = wait

Returns:

  • (String)

    The line received.



2140
2141
2142
2143
2144
# File 'documented/global_defs.rb', line 2140

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.

Examples:

wait_until { condition_met? }

Parameters:

  • announce (String) (defaults to: nil)

    Optional message to announce.



1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
# File 'documented/global_defs.rb', line 1060

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.

Examples:

wait_while { condition_met? }

Parameters:

  • announce (String) (defaults to: nil)

    Optional message to announce.



1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
# File 'documented/global_defs.rb', line 1077

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 cast roundtime to finish.

Examples:

waitcastrt


336
337
338
339
# File 'documented/global_defs.rb', line 336

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 any cast roundtime remaining and waits if necessary.

Examples:

if waitcastrt?; puts "Waiting for cast roundtime..."; end

Returns:

  • (Boolean)

    True if there was cast roundtime, false otherwise.



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

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 matching specified strings.

Examples:

matched_line = waitfor("input")

Parameters:

  • strings (Array<String>)

    The strings to match against.

Returns:

  • (String)

    The matched line.



2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
# File 'documented/global_defs.rb', line 2118

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) ⇒ void

This method returns an undefined value.

Waits for a line from the script’s input matching a regular expression.

Examples:

waitforre(/input/)

Parameters:

  • regexp (Regexp)

    The regular expression to match against.



2107
2108
2109
2110
2111
# File 'documented/global_defs.rb', line 2107

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

#waitrtString

Represents the west direction.

Examples:

direction = w

Returns:



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

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 any roundtime remaining and waits if necessary.

Examples:

if waitrt?; puts "Waiting for roundtime..."; end

Returns:

  • (Boolean)

    True if there was roundtime, false otherwise.



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

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

#walk(*boundaries, &block) ⇒ void

This method returns an undefined value.

Walks in a direction until a condition is met.

Examples:

walk("boundary") { check_condition }

Parameters:

  • boundaries (Array<String>)

    The boundaries to check against.

  • block (Proc)

    The block to execute while walking.



1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
# File 'documented/global_defs.rb', line 1147

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, &block) ⇒ void

This method returns an undefined value.

Monitors the character’s health and executes a block when it falls below a certain value.

Examples:

watchhealth(50) { puts "Health is low!" }

Parameters:

  • value (Integer)

    The health value to monitor.

  • theproc (Proc) (defaults to: nil)

    Optional procedure to execute.

  • block (Proc)

    The block to execute when health falls below the specified value.



1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
# File 'documented/global_defs.rb', line 1039

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