Module: Lich::DragonRealms::Game

Defined in:
lib/games.rb

Constant Summary collapse

@@socket =
nil
@@mutex =
Mutex.new
@@last_recv =
nil
@@thread =
nil
@@buffer =
Lich::Common::SharedBuffer.new
@@_buffer =
Lich::Common::SharedBuffer.new
@@autostarted =
false
@@cli_scripts =
false
@@infomon_loaded =
false
@@room_number_after_ready =
false
@@last_id_shown_room_window =
0

Class Method Summary collapse

Class Method Details

._bufferBuffer

Returns the internal buffer.

Returns:

  • (Buffer)

    the internal buffer.



1526
1527
1528
# File 'lib/games.rb', line 1526

def Game._buffer
  @@_buffer
end

._getsString?

Reads a line from the internal buffer.

Returns:

  • (String, nil)

    the line read from the internal buffer or nil if the buffer is empty.



1519
1520
1521
# File 'lib/games.rb', line 1519

def Game._gets
  @@_buffer.gets
end

._puts(str) ⇒ nil

Note:

This method uses a mutex to ensure thread safety.

Sends a string to the socket in a thread-safe manner.

Parameters:

  • str (String)

    the string to be sent to the socket.

Returns:

  • (nil)

    returns nothing.



1474
1475
1476
1477
1478
# File 'lib/games.rb', line 1474

def Game._puts(str)
  @@mutex.synchronize {
    @@socket.puts(str)
  }
end

.bufferBuffer

Returns the current buffer.

Returns:

  • (Buffer)

    the current buffer.



1512
1513
1514
# File 'lib/games.rb', line 1512

def Game.buffer
  @@buffer
end

.clean_dr_serverstring(server_string) ⇒ String

Note:

This method modifies the input string in place.

Cleans the DragonRealms server string by removing superfluous tags and fixing encoding issues.

Examples:

cleaned_string = DragonRealms::Game.clean_dr_serverstring("<pushStream id=\"combat\" /><popStream id=\"combat\" />")

Parameters:

  • server_string (String)

    The server string to be cleaned.

Returns:

  • (String)

    The cleaned server string.



1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
# File 'lib/games.rb', line 1073

def self.clean_dr_serverstring(server_string)
  ## Clear out superfluous tags
  server_string = server_string.gsub("<pushStream id=\"combat\" /><popStream id=\"combat\" />", "")
  server_string = server_string.gsub("<popStream id=\"combat\" /><pushStream id=\"combat\" />", "")

  # DR occasionally has poor encoding in text, which causes parsing errors.
  # One example of this is in the discern text for the spell Membrach's Greed
  # which gets sent as Membrach\x92s Greed. This fixes the bad encoding until
  # Simu fixes it.
  if server_string =~ /\\x92/
    Lich.log "Detected poorly encoded apostrophe: #{server_string.inspect}"
    server_string.gsub!("\x92", "'")
    Lich.log "Changed poorly encoded apostrophe to: #{server_string.inspect}"
  end

  ## Fix combat wrapping components - Why, DR, Why?
  server_string = server_string.gsub("<pushStream id=\"combat\" /><component id=", "<component id=")

  # Fixes xml with \r\n in the middle of it like:
  # We close the first line and in the next segment, we remove the trailing bits
  # <component id='room objs'>  You also see a granite altar with several candles and a water jug on it, and a granite font.\r\n
  # <component id='room extra'>Placed around the interior, you see: some furniture and other bits of interest.\r\n
  # <component id='room exits'>Obvious paths: clockwise, widdershins.\r\n

  # Followed by in a closing line such as one of these:
  # </component>\r\n
  # <compass></compass></component>\r\n

  # If the pattern is on the left of the =~ the named capture gets assigned as a variable
  if /^<(?<xmltag>dynaStream|component) id='.*'>[^<]*(?!<\/\k<xmltag>>)\r\n$/ =~ server_string
    Lich.log "Open-ended #{xmltag} tag: #{server_string.inspect}"
    server_string.gsub!("\r\n", "</#{xmltag}>")
    Lich.log "Open-ended #{xmltag} tag tag fixed to: #{server_string.inspect}"
  end

  # Remove the now dangling closing tag
  if server_string =~ /^(?:(\"|<compass><\/compass>))?<\/(dynaStream|component)>\r\n/
    Lich.log "Extraneous closing tag detected and deleted: #{server_string.inspect}"
    server_string = ""
  end

  ## Fix duplicate pushStrings
  while server_string.include?("<pushStream id=\"combat\" /><pushStream id=\"combat\" />")
    server_string = server_string.gsub("<pushStream id=\"combat\" /><pushStream id=\"combat\" />", "<pushStream id=\"combat\" />")
  end

  if @combat_count > 0
    @end_combat_tags.each do |tag|
      # server_string = "<!-- looking for tag: #{tag}" + server_string
      if server_string.include?(tag)
        server_string = server_string.gsub(tag, "<popStream id=\"combat\" />" + tag) unless server_string.include?("<popStream id=\"combat\" />")
        @combat_count -= 1
      end
      if server_string.include?("<pushStream id=\"combat\" />")
        server_string = server_string.gsub("<pushStream id=\"combat\" />", "")
      end
    end
  end

  @combat_count += server_string.scan("<pushStream id=\"combat\" />").length
  @combat_count -= server_string.scan("<popStream id=\"combat\" />").length
  @combat_count = 0 if @combat_count < 0

  if @atmospherics
    @atmospherics = false
    server_string.prepend('<popStream id="atmospherics" />') unless server_string =~ /<popStream id="atmospherics" \/>/
  end
  if server_string =~ /<pushStream id="familiar" \/><prompt time="[0-9]+">&gt;<\/prompt>/ # Cry For Help spell is broken...
    server_string.sub!('<pushStream id="familiar" />', '')
  elsif server_string =~ /<pushStream id="atmospherics" \/><prompt time="[0-9]+">&gt;<\/prompt>/ # pet pigs in DragonRealms are broken...
    server_string.sub!('<pushStream id="atmospherics" />', '')
  elsif (server_string =~ /<pushStream id="atmospherics" \/>/)
    @atmospherics = true
  end

  return server_string
end

.clean_gs_serverstring(server_string) ⇒ String

Cleans the game server string by replacing specific tags.

Examples:

cleaned_string = DragonRealms::Game.clean_gs_serverstring("<compDef id='room text'></compDef>")

Parameters:

  • server_string (String)

    The server string to be cleaned.

Returns:

  • (String)

    The cleaned server string.



1054
1055
1056
1057
1058
1059
1060
# File 'lib/games.rb', line 1054

def self.clean_gs_serverstring(server_string)
  # The Rift, Scatter is broken...
  if server_string =~ /<compDef id='room text'><\/compDef>/
    server_string.sub!(/(.*)\s\s<compDef id='room text'><\/compDef>/) { "<compDef id='room desc'>#{$1}</compDef>" }
  end
  return server_string
end

.closenil

Closes the socket and kills the associated thread if they exist.

Returns:

  • (nil)

    returns nothing.

Raises:

  • (StandardError)

    if there is an error while closing the socket or killing the thread.



1462
1463
1464
1465
1466
1467
# File 'lib/games.rb', line 1462

def Game.close
  if @@socket
    @@socket.close rescue nil
    @@thread.kill rescue nil
  end
end

.closed?Boolean

Checks if the socket is closed.

Returns:

  • (Boolean)

    true if the socket is nil or closed, false otherwise.



1450
1451
1452
1453
1454
1455
1456
# File 'lib/games.rb', line 1450

def Game.closed?
  if @@socket.nil?
    true
  else
    @@socket.closed?
  end
end

.getsString?

Reads a line from the buffer.

Returns:

  • (String, nil)

    the line read from the buffer or nil if the buffer is empty.



1505
1506
1507
# File 'lib/games.rb', line 1505

def Game.gets
  @@buffer.gets
end

.open(host, port) ⇒ void

This method returns an undefined value.

Opens a connection to the game server.

Examples:

Game.open('localhost', 1234)

Parameters:

  • host (String)

    the hostname or IP address of the game server.

  • port (Integer)

    the port number to connect to on the game server.

Raises:

  • (StandardError)

    if there is an error while setting socket options or during connection.



1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
# File 'lib/games.rb', line 1159

def Game.open(host, port)
  @@socket = TCPSocket.open(host, port)
  begin
    @@socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
  rescue
    Lich.log "error: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
  rescue StandardError
    Lich.log "error: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
  end
  @@socket.sync = true

  # Add check to determine if the game server hung at initial response

  @@wrap_thread = Thread.new {
    @last_recv = Time.now
    while !@@autostarted && (Time.now - @last_recv < 6)
      break if @@autostarted
      sleep 0.2
    end

    puts 'look' if !@@autostarted
  }

  @@thread = Thread.new {
    begin
      while ($_SERVERSTRING_ = @@socket.gets)
        @@last_recv = Time.now
        @@_buffer.update($_SERVERSTRING_) if TESTING
        begin
          $cmd_prefix = String.new if $_SERVERSTRING_ =~ /^\034GSw/

          unless (XMLData.game.nil? or XMLData.game.empty?)
            unless Module.const_defined?(:GameLoader)
              require_relative 'common/game-loader'
              GameLoader.load!
            end
          end

          if XMLData.game =~ /^GS/
            $_SERVERSTRING_ = self.clean_gs_serverstring($_SERVERSTRING_)
          else
            $_SERVERSTRING_ = self.clean_dr_serverstring($_SERVERSTRING_)
          end

          $_SERVERBUFFER_.push($_SERVERSTRING_)

          if !@@autostarted and $_SERVERSTRING_ =~ /<app char/
            if Gem::Version.new(LICH_VERSION) > Gem::Version.new(Lich.core_updated_with_lich_version)
              Lich::Messaging.mono(Lich::Messaging.monsterbold("New installation or updated version of Lich5 detected!"))
              Lich::Messaging.mono(Lich::Messaging.monsterbold("Installing newest core scripts available to ensure you're up-to-date!"))
              Lich::Messaging.mono("")
              Lich::Util::Update.update_core_data_and_scripts
            end
            Script.start('autostart') if Script.exists?('autostart')
            @@autostarted = true
            if Gem::Version.new(RUBY_VERSION) < Gem::Version.new(RECOMMENDED_RUBY)
              ruby_warning = Terminal::Table.new
              ruby_warning.title = "Ruby Recommended Version Warning"
              ruby_warning.add_row(["Please update your Ruby installation."])
              ruby_warning.add_row(["You're currently running Ruby v#{Gem::Version.new(RUBY_VERSION)}!"])
              ruby_warning.add_row(["It's recommended to run Ruby v#{Gem::Version.new(RECOMMENDED_RUBY)} or higher!"])
              ruby_warning.add_row(["Future Lich5 releases will soon require this newer version."])
              ruby_warning.add_row([" "])
              ruby_warning.add_row(["Visit the following link for info on updating:"])
              if XMLData.game =~ /^GS/
                ruby_warning.add_row(["https://gswiki.play.net/Lich:Software/Installation"])
              elsif XMLData.game =~ /^DR/
                ruby_warning.add_row(["https://github.com/elanthia-online/lich-5/wiki/Documentation-for-Installing-and-Upgrading-Lich"])
              else
                ruby_warning.add_row(["Unknown game type #{XMLData.game} detected."])
                ruby_warning.add_row(["Unsure of proper documentation, please seek assistance via discord!"])
              end
              ruby_warning.to_s.split("\n").each { |row|
                Lich::Messaging.mono(Lich::Messaging.monsterbold(row))
              }
            end
          end

          if !@@infomon_loaded && (defined?(Infomon) || !$DRINFOMON_VERSION.nil?) && !XMLData.name.nil? && !XMLData.name.empty? && !XMLData.dialogs.empty?
            ExecScript.start("Infomon.redo!", { :quiet => true, :name => "infomon_reset" }) if XMLData.game !~ /^DR/ && Infomon.db_refresh_needed?
            @@infomon_loaded = true
          end

          if !@@cli_scripts && @@autostarted && !XMLData.name.nil? && !XMLData.name.empty?
            if (arg = ARGV.find { |a| a =~ /^\-\-start\-scripts=/ })
              for script_name in arg.sub('--start-scripts=', '').split(',')
                Script.start(script_name)
              end
            end
            @@cli_scripts = true
            Lich.log("info: logged in as #{XMLData.game}:#{XMLData.name}")
          end
          unless $_SERVERSTRING_ =~ /^<settings /
            begin
              # Check for valid XML prior to sending to client, corrects double and single nested quotes
              REXML::Document.parse_stream("<root>#{$_SERVERSTRING_}</root>", XMLData)
            rescue
              unless $!.to_s =~ /invalid byte sequence/
                # Fixed invalid xml such as:
                # <mode id="GAME"/><settingsInfo  space not found crc='0' instance='DR'/>
                # <settingsInfo  space not found crc='0' instance='DR'/>
                if $_SERVERSTRING_ =~ /<settingsInfo .*?space not found /
                  Lich.log "Invalid settingsInfo XML tags detected: #{$_SERVERSTRING_.inspect}"
                  $_SERVERSTRING_.sub!('space not found', '')
                  Lich.log "Invalid settingsInfo XML tags fixed to: #{$_SERVERSTRING_.inspect}"
                  retry
                end
                # Illegal character "&" in raw string "  You also see a large bin labeled \"Lost & Found\", a hastily scrawled notice, a brightly painted sign, a silver bell, the Registrar's Office and "
                if $_SERVERSTRING_ =~ /\&/
                  Lich.log "Invalid \& detected: #{$_SERVERSTRING_.inspect}"
                  $_SERVERSTRING_.gsub!("&", '&amp;')
                  Lich.log "Invalid \& stripped out: #{$_SERVERSTRING_.inspect}"
                  retry
                end
                # Illegal character "\a" in raw string "\aYOU HAVE BEEN IDLE TOO LONG. PLEASE RESPOND.\a\n"
                if $_SERVERSTRING_ =~ /\a/
                  Lich.log "Invalid \a detected: #{$_SERVERSTRING_.inspect}"
                  $_SERVERSTRING_.gsub!("\a", '')
                  Lich.log "Invalid \a stripped out: #{$_SERVERSTRING_.inspect}"
                  retry
                end
                # Fixes invalid XML with nested single quotes in it such as:
                # From DR intro tips
                # <link id='2' value='Ever wondered about the time you've spent in Elanthia?  Check the PLAYED verb!' cmd='played' echo='played' />
                # From GS
                # <d cmd='forage Imaera's Lace'>Imaera's Lace</d>, <d cmd='forage stalk burdock'>stalk of burdock</d>
                unless (matches = $_SERVERSTRING_.scan(/'([^=>]*'[^=>]*)'/)).empty?
                  Lich.log "Invalid nested single quotes XML tags detected: #{$_SERVERSTRING_.inspect}"
                  matches.flatten.each do |match|
                    $_SERVERSTRING_.gsub!(match, match.gsub(/'/, '&apos;'))
                  end
                  Lich.log "Invalid nested single quotes XML tags fixed to: #{$_SERVERSTRING_.inspect}"
                  retry
                end
                # Fixes invalid XML with nested double quotes in it such as:
                # <subtitle=" - [Avlea's Bows, "The Straight and Arrow"]">
                unless (matches = $_SERVERSTRING_.scan(/"([^=]*"[^=]*)"/)).empty?
                  Lich.log "Invalid nested double quotes XML tags detected: #{$_SERVERSTRING_.inspect}"
                  matches.flatten.each do |match|
                    $_SERVERSTRING_.gsub!(match, match.gsub(/"/, '&quot;'))
                  end
                  Lich.log "Invalid nested double quotes XML tags fixed to: #{$_SERVERSTRING_.inspect}"
                  retry
                end
                $stdout.puts "error: server_thread: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
                Lich.log "Invalid XML detected - please report this: #{$_SERVERSTRING_.inspect}"
                Lich.log "error: server_thread: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
              end
              XMLData.reset
            end
            if Module.const_defined?(:GameLoader)
              infomon_serverstring = $_SERVERSTRING_.dup
              if XMLData.game =~ /^GS/
                Infomon::XMLParser.parse(infomon_serverstring)
                stripped_infomon_serverstring = strip_xml(infomon_serverstring, type: 'infomon')
                stripped_infomon_serverstring.split("\r\n").each { |line|
                  unless line.empty?
                    Infomon::Parser.parse(line)
                  end
                }
              elsif XMLData.game =~ /^DR/
                DRParser.parse(infomon_serverstring)
              end
            end
            Script.new_downstream_xml($_SERVERSTRING_)
            stripped_server = strip_xml($_SERVERSTRING_, type: 'main')
            stripped_server.split("\r\n").each { |line|
              @@buffer.update(line) if TESTING
              Script.new_downstream(line) if !line.empty?
            }
          end
          if (alt_string = DownstreamHook.run($_SERVERSTRING_))
            #                           Buffer.update(alt_string, Buffer::DOWNSTREAM_MOD)
            if alt_string =~ /^(?:<resource picture="\d+"\/>|<popBold\/>)?<style id="roomName"\s+\/>/
              if (Lich.display_lichid == true || Lich.display_uid == true)
                if XMLData.game =~ /^GS/
                  if (Lich.display_lichid == true && Lich.display_uid == true)
                    alt_string.sub!(/] \(\d+\)/) { "]" }
                    alt_string.sub!(']') { " - #{Map.current.id}] (u#{(XMLData.room_id == 0 || XMLData.room_id > 4294967296) ? "nknown" : XMLData.room_id})" }
                  elsif Lich.display_lichid == true
                    alt_string.sub!(']') { " - #{Map.current.id}]" }
                  elsif Lich.display_uid == true
                    alt_string.sub!(/] \(\d+\)/) { "]" }
                    alt_string.sub!(']') { "] (u#{(XMLData.room_id == 0 || XMLData.room_id > 4294967296) ? "nknown" : XMLData.room_id})" }
                  end
                elsif XMLData.game =~ /^DR/
                  if Lich.display_uid == true
                    alt_string.sub!(/] \((?:\d+|\*\*)\)/) { "]" }
                  elsif Lich.hide_uid_flag == true
                    alt_string.sub!(/] \((?:\d+|\*\*)\)/) { "]" }
                  end
                end
              end
              @@room_number_after_ready = true
            end
            if $frontend =~ /genie/i && alt_string =~ /^<streamWindow id='room' title='Room' subtitle=" - \[.*\] \((?:\d+|\*\*)\)"/
              alt_string.sub!(/] \((?:\d+|\*\*)\)/) { "]" }
            end
            if @@room_number_after_ready && alt_string =~ /<prompt /
              if Lich.display_stringprocs == true
                room_exits = []
                Map.current.wayto.each do |key, value|
                  # Don't include cardinals / up/down/out (usually just climb/go)
                  if value.class == Proc
                    if Map.current.timeto[key].is_a?(Numeric) || (Map.current.timeto[key].is_a?(StringProc) && Map.current.timeto[key].call.is_a?(Numeric))
                      room_exits << "<d cmd=';go2 #{key}'>#{Map[key].title.first.gsub(/\[|\]/, '')}#{Lich.display_lichid ? ('(' + Map[key].id.to_s + ')') : ''}</d>"
                    end
                  end
                end
                alt_string = "StringProcs: #{room_exits.join(', ')}\r\n#{alt_string}" unless room_exits.empty?
              end
              if Lich.display_exits == true
                room_exits = []
                Map.current.wayto.each do |_key, value|
                  # Don't include cardinals / up/down/out (usually just climb/go)
                  next if value.to_s =~ /^(?:o|d|u|n|ne|e|se|s|sw|w|nw|out|down|up|north|northeast|east|southeast|south|southwest|west|northwest)$/
                  if value.class != Proc
                    room_exits << "<d cmd='#{value.dump[1..-2]}'>#{value.dump[1..-2]}</d>"
                  end
                end
                unless room_exits.empty?
                  alt_string = "Room Exits: #{room_exits.join(', ')}\r\n#{alt_string}"
                  if XMLData.game =~ /^GS/ && ['wrayth', 'stormfront'].include?($frontend) && Map.current.id != @@last_id_shown_room_window
                    alt_string = "#{alt_string}<pushStream id='room' ifClosedStyle='watching'/>Room Exits: #{room_exits.join(', ')}\r\n<popStream/>\r\n"
                    @@last_id_shown_room_window = Map.current.id
                  end
                end
              end
              if XMLData.game =~ /^DR/
                room_number = ""
                room_number += "#{Map.current.id}" if Lich.display_lichid
                room_number += " - " if Lich.display_lichid && Lich.display_uid
                room_number += "(#{XMLData.room_id == 0 ? "**" : "u#{XMLData.room_id}"})" if Lich.display_uid
                unless room_number.empty?
                  alt_string = "Room Number: #{room_number}\r\n#{alt_string}"
                  if ['wrayth', 'stormfront'].include?($frontend)
                    alt_string = "<streamWindow id='main' title='Story' subtitle=\" - [#{XMLData.room_title[2..-3]} - #{room_number}]\" location='center' target='drop'/>\r\n#{alt_string}"
                    alt_string = "<streamWindow id='room' title='Room' subtitle=\" - [#{XMLData.room_title[2..-3]} - #{room_number}]\" location='center' target='drop' ifClosed='' resident='true'/>#{alt_string}"
                  end
                end
              end
              @@room_number_after_ready = false
            end
            if $frontend =~ /^(?:wizard|avalon)$/
              alt_string = sf_to_wiz(alt_string)
            end
            if $_DETACHABLE_CLIENT_
              begin
                $_DETACHABLE_CLIENT_.write(alt_string)
              rescue
                $_DETACHABLE_CLIENT_.close rescue nil
                $_DETACHABLE_CLIENT_ = nil
                respond "--- Lich: error: client_thread: #{$!}"
                respond $!.backtrace.first
                Lich.log "error: client_thread: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
              end
            else
              $_CLIENT_.write(alt_string)
            end
          end
        rescue
          $stdout.puts "error: server_thread: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
          Lich.log "error: server_thread: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
        end
      end
    rescue StandardError
      Lich.log "error: server_thread: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
      $stdout.puts "error: server_thread: #{$!}\n\t#{$!.backtrace.slice(0..10).join("\n\t")}"
      sleep 0.2
      retry unless $_CLIENT_.closed? or @@socket.closed? or ($!.to_s =~ /invalid argument|A connection attempt failed|An existing connection was forcibly closed|An established connection was aborted by the software in your host machine./i)
    rescue
      Lich.log "error: server_thread: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
      $stdout.puts "error: server_thread: #{$!}\n\t#{$!.backtrace..slice(0..10).join("\n\t")}"
      sleep 0.2
      retry unless $_CLIENT_.closed? or @@socket.closed? or ($!.to_s =~ /invalid argument|A connection attempt failed|An existing connection was forcibly closed|An established connection was aborted by the software in your host machine./i)
    end
  }
  @@thread.priority = 4
  $_SERVER_ = @@socket # deprecated
end

.puts(str) ⇒ nil

Note:

This method also updates the last upstream message.

Sends a formatted string to the client and logs it.

Examples:

Game.puts("Hello, World!")

Parameters:

  • str (String)

    the string to be sent to the client.

Returns:

  • (nil)

    returns nothing.



1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
# File 'lib/games.rb', line 1487

def Game.puts(str)
  $_SCRIPTIDLETIMESTAMP_ = Time.now
  if (script = Script.current)
    script_name = script.name
  else
    script_name = '(unknown script)'
  end
  $_CLIENTBUFFER_.push "[#{script_name}]#{$SEND_CHARACTER}#{$cmd_prefix}#{str}\r\n"
  if script.nil? or not script.silent
    respond "[#{script_name}]#{$SEND_CHARACTER}#{str}\r\n"
  end
  Game._puts "#{$cmd_prefix}#{str}"
  $_LASTUPSTREAM_ = "[#{script_name}]#{$SEND_CHARACTER}#{str}"
end

.threadThread

Returns the current thread associated with the Game.

Returns:

  • (Thread)

    the current thread.



1443
1444
1445
# File 'lib/games.rb', line 1443

def Game.thread
  @@thread
end