#include "Client.h" #include "blitz/misc/Format.h" #include "blitz/misc/Log.h" #include "blitz/protocol/packets/ChatPacket.h" #include "blitz/protocol/packets/ConnexionInfoPacket.h" #include "blitz/protocol/packets/KeepAlivePacket.h" #include "blitz/protocol/packets/PlayerLoginPacket.h" #include "blitz/protocol/packets/PlayerShootPacket.h" static void PrintColoredText(const protocol::ColoredText& text) { std::string msg; for (auto& part : text) { msg += utils::Format("\033[38;2;%i;%i;%im%s", static_cast(part.color.r * 255), static_cast(part.color.g * 255), static_cast(part.color.b * 255), part.text.c_str()); } msg += "\033[0m"; utils::LOG(msg); } Client::Client() : network::Connexion(&m_Dispatcher) { RegisterHandlers(); } Client::~Client() { GetDispatcher()->UnregisterHandler(this); } void Client::RegisterHandlers() { GetDispatcher()->RegisterHandler(protocol::PacketType::KeepAlive, this); GetDispatcher()->RegisterHandler(protocol::PacketType::Disconnect, this); GetDispatcher()->RegisterHandler(protocol::PacketType::Chat, this); GetDispatcher()->RegisterHandler(protocol::PacketType::ConnexionInfo, this); } bool Client::Connect(const std::string& pseudo, const std::string& address, std::uint16_t port) { if (!Connexion::Connect(address, port)) return false; m_PlayerName = pseudo; return true; } void Client::HandlePacket(const protocol::ChatPacket* packet) { PrintColoredText(packet->GetMessage()); } void Client::HandlePacket(const protocol::DisconnectPacket* packet) { utils::LOG("Disconnected !"); } void Client::HandlePacket(const protocol::KeepAlivePacket* packet) { protocol::KeepAlivePacket response(packet->GetAliveID()); SendPacket(&response); } void Client::HandlePacket(const protocol::ConnexionInfoPacket* packet) { m_PlayerID = packet->GetConnectionID(); Login(m_PlayerName); } void Client::Login(const std::string& pseudo) { protocol::PlayerLoginPacket packet(pseudo); SendPacket(&packet); } void Client::SendTextChat(const std::string& msg) { protocol::ChatPacket packet(protocol::ChatPacket::ColorizeText(msg)); SendPacket(&packet); } void Client::Shoot() { protocol::PlayerShootPacket packet({}, 0, 0); SendPacket(&packet); }