Skip to content

Commit

Permalink
refactor: improve the fibonacci command
Browse files Browse the repository at this point in the history
  • Loading branch information
wu-vincent committed Mar 6, 2024
1 parent 6e5c9c8 commit d1823d5
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 16 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@ aiming to craft C++ plugins for the Bedrock Dedicated Servers using Endstone.
```
cpp-plugin-template/
├── include/ # Header files for the plugin
│ └── endstone_cpp_plugin.h # Header for the EndstoneCppPlugin class
│ ├── example_plugin.h # Header for the ExamplePlugin class
│ └── fibonacci_command.h # Header for the FibonacciCommand class
├── src/ # Source files for the plugin
│ └── endstone_cpp_plugin.cpp # Implementation for the EndstoneCppPlugin class
│ └── example_plugin.cpp # Implementation for the ExamplePlugin class
├── .clang-format # Configuration for Clang format rules
├── .gitignore # Git ignore rules
├── CMakeLists.txt # CMake configuration for building the plugin
Expand Down
29 changes: 15 additions & 14 deletions include/fibonacci_command.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
#include "endstone/command/command.h"
#include "endstone/command/command_executor.h"

#include <sstream> // for std::ostringstream
#include <string>

class FibonacciCommand : public endstone::Command {
public:
FibonacciCommand() : Command("fibonacci")
{
setDescription("A simple command that prints out the fibonacci series for n <= 20");
setDescription("A simple command that writes the Fibonacci series up to n.");
setAliases("fib");
setUsages("/fibonacci <n: int>");
}
Expand All @@ -23,23 +23,24 @@ class FibonacciCommandExecutor : public endstone::CommandExecutor {
const std::vector<std::string> &args) override
{
int n = std::stoi(args[0]);
if (n > 0 && n <= 20) {
int t1 = 1, t2 = 1, next;
std::ostringstream os;
for (int i = 1; i <= n; ++i) {
if (i > 1) {
os << ", ";
if (n > 0) {
int a = 0, b = 1;
std::string result;
while (a < n) {
if (!result.empty()) {
result += ", ";
}
os << t1;
next = t1 + t2;
t1 = t2;
t2 = next;

result += std::to_string(a);
int temp = b;
b = a + b;
a = temp;
}
sender.sendMessage("Fibonacci Series (n = {}): {}", n, os.str());
sender.sendMessage("Fibonacci series up to {}: {}", n, result);
return true;
}
else {
sender.sendErrorMessage("'n' must be greater than 0 and less than or equal to 20.");
sender.sendErrorMessage("'n' must be an integer greater than 0.");
return false;
}
}
Expand Down

0 comments on commit d1823d5

Please sign in to comment.