Add on_client_drop()

This commit is contained in:
ChillerDragon 2022-11-05 11:59:36 +01:00
parent 8fe595b0a6
commit db106ba70e
5 changed files with 91 additions and 1 deletions

View file

@ -125,6 +125,35 @@ end
client.connect('localhost', 8303, detach: true)
```
### #on_client_drop(&block)
**Parameter: block [Block |[context](#context)|]**
Takes a block that will be called when the client receives a client drop packet.
Context:
```ruby
[
player: player_object,
chunk: raw_packet_data,
client_id: 0,
reason: '',
silent: false
]
```
**Example:**
```ruby
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
```
### connect(ip, port, options)

View file

@ -0,0 +1,23 @@
#!/usr/bin/env ruby
require_relative '../lib/teeworlds-client'
client = TeeworldsClient.new
client.on_client_info do |ctx|
unless ctx.data[:silent]
reason = ctx.data[:reason] ? " (#{ctx.data[:reason]})" : ''
puts "'#{ctx.data[:player].name}' joined the game#{reason}"
end
end
client.on_client_drop do |ctx|
puts "'#{ctx.data[:player].name}' has left the game"
end
Signal.trap('INT') do
client.disconnect
end
# connect and detach thread
client.connect('localhost', 8303, detach: false)

View file

@ -64,7 +64,29 @@ class GameClient
player = context.data[:player]
@players[player.id] = player
puts "'#{player.name}' joined the game"
end
def on_client_drop(chunk)
u = Unpacker.new(chunk.data[1..])
client_id = u.get_int()
reason = u.get_string()
silent = u.get_int()
context = Context.new(
@cliemt,
player: @players[client_id],
chunk: chunk,
client_id: client_id,
reason: reason == '' ? nil : reason,
silent: silent
)
if @client.hooks[:client_drop]
@client.hooks[:client_drop].call(context)
context.verify
return if context.cancled?
end
@players.delete(context.data[:client_id])
end
def on_ready_to_enter(chunk)

View file

@ -64,6 +64,10 @@ class TeeworldsClient
@hooks[:client_info] = block
end
def on_client_drop(&block)
@hooks[:client_drop] = block
end
def on_connected(&block)
@hooks[:connected] = block
end
@ -265,6 +269,7 @@ class TeeworldsClient
case chunk.msg
when NETMSGTYPE_SV_READYTOENTER then @game_client.on_ready_to_enter(chunk)
when NETMSGTYPE_SV_CLIENTINFO then @game_client.on_client_info(chunk)
when NETMSGTYPE_SV_CLIENTDROP then @game_client.on_client_drop(chunk)
when NETMSGTYPE_SV_EMOTICON then @game_client.on_emoticon(chunk)
when NETMSGTYPE_SV_CHAT then @game_client.on_chat(chunk)
else

View file

@ -31,6 +31,17 @@ client.on_chat do |msg|
puts "[chat] #{msg}"
end
client.on_client_info do |ctx|
puts "'#{ctx.data[:player].name}' joined the game#{reason}"
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
Signal.trap('INT') do
client.disconnect
end