teeworlds_network/client_sample.rb

85 lines
1.9 KiB
Ruby
Raw Normal View History

2022-11-01 13:25:56 +00:00
#!/usr/bin/env ruby
2022-11-05 16:48:47 +00:00
# frozen_string_literal: true
2022-11-01 13:25:56 +00:00
require_relative 'lib/teeworlds_client'
2022-11-01 13:25:56 +00:00
2023-10-22 06:19:50 +00:00
args = {
verbose: false,
verbose_snap: false,
ip: nil,
port: nil
}
2022-11-01 13:25:56 +00:00
2023-10-22 06:19:50 +00:00
verbose_level = 0
def show_help
2023-10-22 16:19:07 +00:00
puts 'usage: client_sample.rb [OPTIONS..] [host] [port]'
puts 'options:'
puts ' --help|-h show this help'
puts ' --verbose|-v verbose output'
puts ' --verbose-snap|-s verbose snap item output'
puts 'example:'
puts ' client_sample.rb --verbose localhost 8303'
puts ' client_sample.rb -s'
puts ' client_sample.rb -vv ger.ddnet.org 8307'
exit(0)
2023-10-22 06:19:50 +00:00
end
ARGV.each do |arg|
if ['--help', '-h'].include?(arg)
show_help
2022-11-05 16:19:05 +00:00
elsif ['--verbose', '-v'].include?(arg)
2022-11-01 13:25:56 +00:00
args[:verbose] = true
2023-10-22 06:19:50 +00:00
elsif ['--verbose-snap', '-s'].include?(arg)
args[:verbose_snap] = true
elsif arg[0] == '-' && arg[1] != '-'
# flags
arg[1..].chars.each do |flag|
case flag
when 'v'
verbose_level += 1
args[:verbose] = true
args[:verbose_snap] = true if verbose_level > 1
when 'h'
show_help
when 's'
args[:verbose_snap] = true
else
puts "Error: unknown flag '#{flag}'"
exit(1)
end
end
2022-11-01 13:25:56 +00:00
elsif args[:ip].nil?
args[:ip] = arg
elsif args[:port].nil?
args[:port] = arg.to_i
end
end
args[:ip] = args[:ip] || '127.0.0.1'
args[:port] = args[:port] || 8303
2023-10-22 06:19:50 +00:00
client = TeeworldsClient.new(args)
2022-11-01 13:25:56 +00:00
client.on_chat do |_, msg|
2022-11-04 15:26:24 +00:00
puts "[chat] #{msg}"
2022-11-01 13:25:56 +00:00
end
2022-11-05 10:59:36 +00:00
client.on_client_info do |ctx|
puts "'#{ctx.data[:player].name}' joined the game"
2022-11-05 10:59:36 +00:00
end
client.on_client_drop do |ctx|
unless ctx.data[:silent]
reason = ctx.data[:reason] ? " (#{ctx.data[:reason]})" : ''
puts "'#{ctx.data[:player].name}' left the game#{reason}"
end
end
2022-11-04 12:07:34 +00:00
Signal.trap('INT') do
client.disconnect
end
2022-11-04 12:04:51 +00:00
# connect and detach thread
2022-11-04 11:55:01 +00:00
client.connect(args[:ip], args[:port], detach: false)