Skip to content

Commit

Permalink
Add ability to use Bot#on(&block) for callbacks
Browse files Browse the repository at this point in the history
The start of handling chat and such
  • Loading branch information
grepsedawk committed Jul 27, 2022
1 parent 42d6d7b commit 469fb47
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
13 changes: 13 additions & 0 deletions src/rosegold/bot.cr
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,15 @@ class Rosegold::Bot
player.look.pitch = angle
end

# Used to retrieve the pitch the player is looking
delegate pitch, to: player.look

# Used to set the yaw the player is looking
def yaw=(angle)
player.look.yaw = angle
end

# Used to retrieve the yaw the player is looking
delegate yaw, to: player.look

# Use to move the player to a location, does not take into account y (height)
Expand All @@ -39,5 +41,16 @@ class Rosegold::Bot
move_to x, player.position.y, z
end

# Use to add a callback processed upon specified incoming packet
#
# ```
# client.on_packet Rosegold::Clientbound::Chat do |chat|
# puts "Received chat: #{chat.message}"
# end
# ```
def on(packet_type : T.class, &block : T ->) forall T
client.on packet_type, &block
end

forward_missing_to client
end
17 changes: 14 additions & 3 deletions src/rosegold/client.cr
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ class Rosegold::Client
state : State::Status | State::Login | State::Play | State::Disconnected = State::Status.new,
compression_threshold : UInt32 = 0,
read_mutex : Mutex = Mutex.new,
write_mutex : Mutex = Mutex.new
write_mutex : Mutex = Mutex.new,
callbacks : Hash(Clientbound::Packet.class, Array(Proc(Clientbound::Packet, Nil))) = Hash(Clientbound::Packet.class, Array(Proc(Clientbound::Packet, Nil))).new

def initialize(@io : Minecraft::TCPSocket, @host : String, @port : UInt32)
@physics = uninitialized Physics
Expand Down Expand Up @@ -80,8 +81,13 @@ class Rosegold::Client
Bot.new self
end

def start_physics
@physics ||= Physics.new self
def on(packet : T.class, &block : T ->) forall T
callbacks[packet] ||= [] of Proc(Clientbound::Packet, Nil)
callbacks[packet] << Proc(Clientbound::Packet, Nil).new do |parent_type_packet|
Proc(T, Nil).new do |child_type_packet|
block.call child_type_packet
end.call(parent_type_packet.as T)
end
end

def status
Expand Down Expand Up @@ -177,7 +183,12 @@ class Rosegold::Client
packet = pkt_type.read(pkt_io)
Log.trace { "RECV " + packet.pretty_inspect(999, " ", 0) \
.gsub("Rosegold::", "").gsub("Clientbound::", "").sub(/:0x\S+/, "") }

packet.callback(self)

callbacks[packet.class]?.try do |callback|
callback.each &.call packet
end
else
nil # packet not parsed
end
Expand Down

0 comments on commit 469fb47

Please sign in to comment.