diff --git a/lib/game_server.rb b/lib/game_server.rb index e97978e..1a302c7 100644 --- a/lib/game_server.rb +++ b/lib/game_server.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require_relative'context' require_relative 'models/map' require_relative 'models/chat_message' require_relative 'messages/game_info' @@ -24,6 +25,21 @@ class GameServer ) end + ## + # call_hook + # + # @param: hook_sym [Symbol] name of the symbol to call + # @param: context [Context] context object to pass on data + # @param: optional [Any] optional 2nd parameter passed to the callback + def call_hook(hook_sym, context, optional = nil) + @server.hooks[hook_sym].each do |hook| + hook.call(context, optional) + context.verify + return nil if context.canceld? + end + context + end + def on_emoticon(chunk, _packet) message = ClEmoticon.new(chunk.data[1..]) p message @@ -69,6 +85,9 @@ class GameServer say = ClSay.new(chunk.data[1..]) author = packet.client.player msg = ChatMesage.new(say.to_h.merge(client_id: author.id, author:)) + context = Context.new(say, chunk:) + return if call_hook(:chat, context, msg).nil? + puts msg.to_s end diff --git a/lib/teeworlds_server.rb b/lib/teeworlds_server.rb index aa4fab6..7f09941 100644 --- a/lib/teeworlds_server.rb +++ b/lib/teeworlds_server.rb @@ -59,6 +59,7 @@ end class TeeworldsServer attr_accessor :clients + attr_reader :hooks def initialize(options = {}) @verbose = options[:verbose] || false @@ -68,6 +69,13 @@ class TeeworldsServer @clients = {} @current_game_tick = 0 @last_snap_time = Time.now + @hooks = { + chat: [] + } + end + + def on_chat(&block) + @hooks[:chat].push(block) end def run(ip, port) diff --git a/server_sample.rb b/server_sample.rb index 1abe7f2..609b2b7 100755 --- a/server_sample.rb +++ b/server_sample.rb @@ -4,4 +4,11 @@ require_relative 'lib/teeworlds_server' srv = TeeworldsServer.new(verbose: false) + +srv.on_chat do |context, msg| + context.cancel + + puts "[chat] #{msg.author.name}: #{msg.message}" +end + srv.run('127.0.0.1', 8303)