diff --git a/.gitignore b/.gitignore index 0256355..046bcff 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ Gemfile.lock +*.cfg scripts/tmp integration_test/*.txt integration_test/*.log diff --git a/lib/config.rb b/lib/config.rb new file mode 100644 index 0000000..41527d1 --- /dev/null +++ b/lib/config.rb @@ -0,0 +1,44 @@ +# frozen_string_literal: true + +class Config + def initialize(options = {}) + filepath = options[:file] || 'autoexec.cfg' + init_configs + load_cfg(filepath) + end + + def init_configs + @configs = { + password: { help: 'Password to the server', default: '' } + } + @commands = { + echo: { help: 'Echo the text', callback: proc { |arg| puts arg } }, + quit: { help: 'Quit', callback: proc { |_| exit } } + } + @configs.each do |cfg, data| + self.class.send(:attr_accessor, cfg) + instance_variable_set("@#{cfg}", data[:default]) + end + end + + def load_cfg(file) + return unless File.exist?(file) + + File.readlines(file).each_with_index do |line, line_num| + line.strip! + next if line.start_with? '#' + next if line.empty? + + words = line.split + cmd = words.shift.to_sym + arg = words.join(' ') + if @configs[cmd] + instance_variable_set("@#{cmd}", arg) + elsif @commands[cmd] + @commands[cmd][:callback].call(arg) + else + puts "Warning: unsupported config '#{cmd}' #{file}:#{line_num}" + end + end + end +end diff --git a/lib/teeworlds_client.rb b/lib/teeworlds_client.rb index ecddc04..c0c901d 100644 --- a/lib/teeworlds_client.rb +++ b/lib/teeworlds_client.rb @@ -13,6 +13,7 @@ require_relative 'net_base' require_relative 'packer' require_relative 'models/player' require_relative 'game_client' +require_relative 'config' class TeeworldsClient attr_reader :state, :hooks, :game_client @@ -24,6 +25,7 @@ class TeeworldsClient @ip = 'localhost' @port = 8303 @local_client_id = 0 + @config = Config.new(file: options[:config]) @hooks = { chat: [], map_change: [], @@ -227,7 +229,7 @@ class TeeworldsClient def send_info data = [] data += Packer.pack_str(GAME_NETVERSION) - data += Packer.pack_str('password') + data += Packer.pack_str(@config.password) data += Packer.pack_int(CLIENT_VERSION) msg = NetChunk.create_header(vital: true, size: data.size + 1) + [pack_msg_id(NETMSG_INFO, system: true)] +