From f25eec7a0ba4a8a868eb87c76ec8b88f76f3a124 Mon Sep 17 00:00:00 2001 From: littleblack111 Date: Thu, 20 Mar 2025 22:38:46 +0800 Subject: feat: inputManager and commandHandler (#7) server now have ability to send chat like any clients. can also run commands(registered in commands.cpp) --- src/commandHandler.hpp | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/commandHandler.hpp (limited to 'src/commandHandler.hpp') diff --git a/src/commandHandler.hpp b/src/commandHandler.hpp new file mode 100644 index 0000000..78ab2e5 --- /dev/null +++ b/src/commandHandler.hpp @@ -0,0 +1,67 @@ +#pragma once + +#include +#include +#include +#include +#include + +class CCommandHandler { + public: + CCommandHandler(); + ~CCommandHandler(); + + struct SResult { + std::string result; + bool good = false; + }; + + struct SParseResult { + std::any data; + bool good = false; + }; + + struct SCommand { + std::string name; + std::function parser; + std::function exe; + }; + + bool isCommand(const std::string &str) const; + bool validCommand(const std::string &command) const; + // return false if command struct is invalid + bool registerCommand(const SCommand &command); + SResult newCommand(const std::string &command, const std::string &args) const; + + template + struct SMakeCommandArgs { + std::string name; + std::function(const std::string &args)> parser; + std::function exe; + }; + + template + static SCommand makeCommand(SMakeCommandArgs args) { + return { + .name = std::move(args.name), + .parser = [parser = std::move(args.parser)](const std::string &args) -> SParseResult { + auto [data, good] = parser(args); + return {.data = std::any(std::move(data)), .good = good}; + }, + .exe = [exe = std::move(args.exe)](const std::any &parsed) -> SResult { + try { + return exe(std::any_cast(parsed)); + } catch (const std::bad_any_cast &) { + return {.result = "Invalid data type", .good = false}; + } + } + }; + } + + private: + const SCommand *getCommand(const std::string &command) const; + SResult exeCommand(const SCommand &command, const std::string &args) const; + + std::vector m_vCommands; +}; +inline std::unique_ptr g_pCommandHandler; -- cgit v1.2.3