Add action file loops and display the GPLv3 notice at console startup

This commit is contained in:
cantyonion committed 2026-11-24 16:44:34 +08:00
1 parent 12c7332337
commit b8799a62e7
9 files changed
+305 -47

No files matched your search

+25 -4
View File
@@ -2,7 +2,7 @@
基于 [Botcraft](https://github.com/adepierre/Botcraft) 的 Minecraft Java 机器人,默认连接 BiliCraft 服务器。使用 Microsoft 正版账号登录,通过交互终端或 `.act` 操作文件执行移动、方块与展示框交互、背包操作和聊天命令。
项目使用 C++23 和 CMake,提供离线脚本检查、合作式任务调度及终端命令编辑。机器人收到服务器发来的生命值更新时,如果生命值降至 0 或以下,会自动请求复活,无需输入命令。自主种植和自动重连尚未实现。
项目使用 C++23 和 CMake,提供离线脚本检查、合作式任务调度及终端命令编辑。机器人收到服务器发来的生命值更新时,如果生命值降至 0 或以下,会自动请求复活,无需输入命令。
## 环境要求
@@ -118,12 +118,12 @@ bilicraft-bot [--server host:port] [--account cache-key]
| `help` | 显示终端帮助 |
| `quit` / `exit` | 取消队列并断开连接 |
终端和脚本都支持[命令别名与参数定义](#命令别名与参数定义)。游戏命令与脚本共用下文语法,但 `wait` 和 `import` 仅能写在操作文件中。单条交互游戏命令提交后,终端会等它完成或失败,再接收下一条输入。
终端和脚本都支持[命令别名与参数定义](#命令别名与参数定义)。游戏命令与脚本共用下文语法,但 `wait`、`import` 和 `do` 仅能写在操作文件中。单条交互游戏命令提交后,终端会等它完成或失败,再接收下一条输入。
### 调度与退出
- 游戏操作在主线程串行执行。运行中的脚本会持续执行,直到完成、失败或遇到 `wait`;新任务不会抢占它。
- 交互游戏命令在当前脚本完成或等待时优先执行。就绪脚本按最新入队优先(LIFO)选择,持续加入新任务可能推迟旧任务。
- 游戏操作在主线程串行执行。脚本在完成、失败、遇到 `wait` 或开始下一轮循环时调度其他任务。
- 交互游戏命令在当前脚本完成、等待或开始下一轮循环时优先执行。就绪脚本按最新入队优先(LIFO)选择,持续加入新任务可能推迟旧任务。
- `wait` 挂起当前脚本,计时结束后重新入队;`import` 在当前脚本内展开,不创建独立任务。
- 等待期间其他任务可能改变位置、手持格或背包;脚本恢复时不会自动还原状态。
- 某个脚本失败会丢弃其剩余命令,其他任务和终端仍可继续使用;已完成的操作不回滚,也不自动重试。
@@ -208,6 +208,7 @@ home
| `sendcmd cmd` | 发送服务器命令,允许带一个开头 `/`,支持空格和参数 |
| `sendmsg msg` | 发送公开聊天消息 |
| `sendmsg @to msg` | 发送私信,等价于 `/msg to msg` |
| `do 次数` / `do always` | 重复一条指令或一个 `begin` / `end` 块,仅操作文件可用 |
| `import action` | 执行同目录的 `action.act`,完成后继续当前文件,仅操作文件可用 |
点击命令不会自动寻路,请先用 `goto` 移到交互距离内。机器人根据服务器同步的人物体型倍率和当前姿势计算眼高,并以此瞄准方块、物品展示框和检查交互距离。
@@ -254,6 +255,26 @@ lclick 100 64 200 entry e destory # 拆除展示框
普通左击仅在本地已知框内有物品时攻击,并等待物品变空;创造模式下拒绝普通取物,以免直接拆框。`destory` 最多攻击两次:先取物,再拆除同一个空框。其他玩家或插件同时改变框状态仍可能影响结果,取下物品也不保证会被机器人拾取。
### 循环
`do 次数` 重复执行下一条指令。次数可写为非负十进制整数(最大 `18446744073709551615`),或用 `always` 表示无限循环。`do 0` 跳过循环体,加载时仍会检查其中的语法。
```text
# action: harvest
define rounds 3
do $rounds begin
rclick 100 64 200
wait 1 s
end
do 2
import collect
do always wait 5 s
```
单条指令可写在 `do` 同一行或下一行,多条指令用 `begin` 和 `end` 包起来。循环可以嵌套,`import` 算一条指令。每轮按顺序执行,`wait` 结束后从该轮的下一条指令继续。别名和参数仍在加载时按源码顺序定义、展开。使用 `quit` 或 Ctrl+C 可退出无限循环并断开连接。
### 等待与导入
```text
+10 -2
View File
@@ -4,6 +4,7 @@
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <optional>
#include <string>
@@ -24,7 +25,9 @@ enum class ActionKind
Drop,
SendCommand,
SendMessage,
Wait
Wait,
LoopBegin,
LoopEnd
};
enum class EntityFace
@@ -53,6 +56,9 @@ struct ActionCommand
// Click entry: target an item frame; Any searches all six block faces.
bool entity = false;
EntityFace entityFace = EntityFace::Any;
// LoopBegin: nullopt repeats forever. loopEnd indexes the matching LoopEnd.
std::optional<std::uint64_t> repetitions;
std::size_t loopEnd = 0;
};
struct ActionProgram
@@ -68,6 +74,8 @@ struct ActionProgram
// must be simple names resolving to same-directory name.act files whose action
// headers match. Cycles and symlink escapes are rejected. Limits: 32 active
// files, 100000 expanded commands, 4096 file loads, 1 MiB/file and 16 MiB total.
// do COUNT executes the next statement, or a begin/end block. COUNT may be
// an unsigned decimal integer or always. Loop iterations are scheduled lazily.
// Wait syntax: wait digits[.digits] [s|ms|min|h|d], default s. The duration
// must be an exact whole number of milliseconds and may not exceed 365 days.
// Clicks optionally accept entry [t|b|s|n|w|e] (or full face names), with
@@ -76,7 +84,7 @@ struct ActionProgram
ActionProgram LoadActionFile(const std::filesystem::path &path, CommandBindings bindings = {});
// Parse one console game instruction using the .act grammar, without file I/O.
// Blank/comment lines return nullopt. Wait/import require `run file.act` instead.
// Blank/comment lines return nullopt. Wait/import/loops require `run file.act`.
// CR, LF and NUL are rejected; errors throw with <console>:1 context.
std::optional<ActionCommand> ParseInteractiveCommand(std::string_view text);
} // namespace Bilicraft
+6
View File
@@ -49,6 +49,11 @@ class ActionScheduler
std::vector<std::string> DrainEvents();
private:
struct LoopFrame
{
std::size_t body;
std::optional<std::uint64_t> remaining;
};
struct Task
{
TaskId id;
@@ -57,6 +62,7 @@ class ActionScheduler
State state = State::Ready;
Clock::time_point wakeAt{};
std::uint64_t readyOrder = 0;
std::vector<LoopFrame> loops;
};
void RemoveActive(bool success);
std::map<TaskId, Task> tasks;
+6 -1
View File
@@ -96,7 +96,12 @@ int main(int argc, char **argv)
bool eofReported = false;
bool actionFailed = false;
std::optional<Clock::time_point> drainedSince;
console->Out() << "Entered game. " << ConsoleHelp();
console->Out() << "Entered game.\n"
"bilicraft-bot Copyright (C) 2026 Jeffrey Hsu\n"
"This is free software. You may redistribute and modify it under the terms of "
"the GNU General Public License, version 3.\n"
"This program comes with ABSOLUTELY NO WARRANTY. See LICENSE for details.\n\n"
"Type 'help' to list the available commands.\n";
const auto printEvents = [&] {
for (const auto &event : scheduler.DrainEvents()) console->Out() << event << '\n';
console->Out().flush();
+107 -32
View File
@@ -284,6 +284,41 @@ struct Loader
std::size_t loads = 0;
std::size_t total_bytes = 0;
void Append(ActionCommand command)
{
if (program.commands.size() >= kMaxCommands)
Fail(command.source, command.line, "expanded command limit exceeded (100000)");
program.commands.push_back(std::move(command));
}
void LoadInstruction(std::string_view verb, std::string_view line, const std::filesystem::path &source,
std::size_t line_number)
{
if (verb == "import")
{
const auto name = TakeToken(line);
if (!IsSimpleName(name) || !Trim(line).empty())
Fail(source, line_number, "import requires exactly one simple action name");
const auto imported = source.parent_path() / (std::string(name) + ".act");
std::error_code ec;
const auto resolved = std::filesystem::canonical(imported, ec);
if (ec)
Fail(source, line_number, "cannot import '" + std::string(name) + "': " + ec.message());
if (resolved.parent_path() != source.parent_path())
Fail(source, line_number, "import escapes its action directory");
try
{
Load(resolved, name);
}
catch (const std::runtime_error &error)
{
Fail(source, line_number, "import '" + std::string(name) + "': " + error.what());
}
return;
}
Append(ParseCommand(verb, line, source, line_number));
}
void Load(const std::filesystem::path &path, std::string_view expected_name = {})
{
std::error_code ec;
@@ -329,6 +364,23 @@ struct Loader
remaining.remove_prefix(3);
bool header_seen = false;
std::size_t line_number = 0;
struct OpenLoop
{
std::size_t start;
bool block;
};
// Each file must balance its own blocks, including when imported as a single statement.
std::vector<OpenLoop> loops;
const auto closeLoop = [&] {
auto &start = program.commands[loops.back().start];
start.loopEnd = program.commands.size();
ActionCommand end{};
end.kind = ActionKind::LoopEnd;
end.source = source;
end.line = line_number;
Append(std::move(end));
loops.pop_back();
};
while (!remaining.empty())
{
++line_number;
@@ -365,47 +417,70 @@ struct Loader
continue;
if (!header_seen)
Fail(source, line_number, "missing action header before first instruction");
// A single-line body may itself begin with another do. Parse it iteratively.
std::string expanded;
try
for (;;)
{
expanded = bindings.Expand(line, kMaxFileBytes);
}
catch (const std::runtime_error &error)
{
Fail(source, line_number, error.what());
}
if (expanded.empty()) continue;
expandedBytes += expanded.size();
if (expandedBytes > kMaxTotalBytes)
Fail(source, line_number, "total expanded action text exceeds 16 MiB");
line = expanded;
const auto verb = TakeToken(line);
if (verb == "import")
{
const auto name = TakeToken(line);
if (!IsSimpleName(name) || !Trim(line).empty())
Fail(source, line_number, "import requires exactly one simple action name");
const auto imported = source.parent_path() / (std::string(name) + ".act");
const auto resolved = std::filesystem::canonical(imported, ec);
if (ec)
Fail(source, line_number, "cannot import '" + std::string(name) + "': " + ec.message());
if (resolved.parent_path() != source.parent_path())
Fail(source, line_number, "import escapes its action directory");
try
{
Load(resolved, name);
expanded = bindings.Expand(line, kMaxFileBytes);
}
catch (const std::runtime_error &error)
{
Fail(source, line_number, "import '" + std::string(name) + "': " + error.what());
Fail(source, line_number, error.what());
}
continue;
expandedBytes += expanded.size();
if (expandedBytes > kMaxTotalBytes)
Fail(source, line_number, "total expanded action text exceeds 16 MiB");
line = expanded;
const auto verb = TakeToken(line);
line = Trim(line);
if (verb == "do")
{
ActionCommand start{};
start.kind = ActionKind::LoopBegin;
start.source = source;
start.line = line_number;
const auto count = TakeToken(line);
if (count != "always")
{
std::uint64_t repetitions = 0;
const auto parsed = std::from_chars(count.data(), count.data() + count.size(), repetitions);
if (count.empty() || parsed.ec != std::errc{} || parsed.ptr != count.data() + count.size())
Fail(source, line_number, "do requires a nonnegative integer or always");
start.repetitions = repetitions;
}
loops.push_back({program.commands.size(), false});
Append(std::move(start));
line = Trim(line);
if (line.empty()) break;
continue;
}
if (verb == "begin")
{
if (loops.empty() || loops.back().block || !line.empty())
Fail(source, line_number, "expected begin only after do <count>");
loops.back().block = true;
break;
}
if (verb == "end")
{
if (loops.empty() || !loops.back().block || !line.empty())
Fail(source, line_number, "end requires a matching do block with a complete body");
closeLoop();
}
else if (!verb.empty()) // alias and define were processed while expanding.
LoadInstruction(verb, line, source, line_number);
// A complete statement also completes enclosing unbracketed loops.
while (!loops.empty() && !loops.back().block)
closeLoop();
break;
}
auto command = ParseCommand(verb, line, source, line_number);
if (program.commands.size() >= kMaxCommands)
Fail(source, line_number, "expanded command limit exceeded (100000)");
program.commands.push_back(std::move(command));
}
if (!loops.empty())
Fail(source, program.commands[loops.back().start].line,
loops.back().block ? "missing end for do block" : "missing statement after do");
if (!header_seen)
Fail(source, line_number == 0 ? 1 : line_number, "missing action header");
}
@@ -434,7 +509,7 @@ std::optional<ActionCommand> ParseInteractiveCommand(std::string_view text)
if (text.empty())
return std::nullopt;
const auto verb = TakeToken(text);
if (verb == "wait" || verb == "import")
if (verb == "wait" || verb == "import" || verb == "do" || verb == "begin" || verb == "end")
Fail(source, 1, std::string(verb) + " is only available in action files; use run file.act");
return ParseCommand(verb, text, source, 1);
}
+65 -6
View File
@@ -10,16 +10,34 @@ ActionScheduler::TaskId ActionScheduler::Enqueue(ActionProgram program, Clock::t
{
if (tasks.size() >= 128 || program.commands.size() > 1000000 - storedCommands)
throw std::runtime_error("action queue limit exceeded (128 tasks / 1000000 commands)");
for (const auto &command : program.commands)
std::vector<std::size_t> ends;
for (std::size_t pc = 0; pc < program.commands.size(); ++pc)
{
const auto &command = program.commands[pc];
if (command.kind == ActionKind::LoopBegin)
{
if (command.loopEnd <= pc || command.loopEnd >= program.commands.size() ||
(!ends.empty() && command.loopEnd >= ends.back()) ||
program.commands[command.loopEnd].kind != ActionKind::LoopEnd)
throw std::runtime_error("invalid loop end in action program");
ends.push_back(command.loopEnd);
}
if (command.kind == ActionKind::LoopEnd)
{
if (ends.empty() || pc != ends.back())
throw std::runtime_error("unmatched loop end in action program");
ends.pop_back();
}
if (command.kind == ActionKind::Wait &&
(command.waitDuration.count() < 0 || command.waitDuration > std::chrono::hours(24 * 365)))
throw std::runtime_error("wait duration must be between zero and 365 days");
}
// An already-expired wait became ready BEFORE this newly submitted task,
// even when another action was executing throughout that time.
WakeReady(now);
const auto id = nextId++;
storedCommands += program.commands.size();
tasks.emplace(id, Task{id, std::move(program), 0, State::Ready, {}, nextOrder++});
tasks.emplace(id, Task{id, std::move(program), 0, State::Ready, {}, nextOrder++, {}});
events.push_back("Action #" + std::to_string(id) + " '" + tasks.at(id).program.name + "': queued");
return id;
}
@@ -30,6 +48,8 @@ void ActionScheduler::SubmitInteractive(ActionCommand command)
throw std::runtime_error("previous interactive command has not completed");
if (command.kind == ActionKind::Wait)
throw std::runtime_error("wait is not allowed in the interactive console; use run file.act");
if (command.kind == ActionKind::LoopBegin || command.kind == ActionKind::LoopEnd)
throw std::runtime_error("do loops are only available in action files");
interactive = std::move(command);
}
@@ -55,6 +75,8 @@ std::optional<ActionScheduler::Work> ActionScheduler::Next(Clock::time_point now
if (inFlight)
throw std::logic_error("finish the outstanding command before scheduling another");
WakeReady(now);
// Empty loops and loops containing only skipped bodies must return to the console pump.
unsigned controlSteps = 0;
for (;;)
{
if (!active)
@@ -81,7 +103,39 @@ std::optional<ActionScheduler::Work> ActionScheduler::Next(Clock::time_point now
continue;
}
const auto &command = task.program.commands[task.pc];
if (command.kind == ActionKind::Wait)
if (command.kind == ActionKind::LoopBegin)
{
if (command.repetitions == 0 || (command.repetitions && task.pc + 1 == command.loopEnd))
task.pc = command.loopEnd + 1;
else
{
++task.pc;
task.loops.push_back({task.pc, command.repetitions});
}
}
else if (command.kind == ActionKind::LoopEnd)
{
auto &loop = task.loops.back();
if (loop.remaining && --*loop.remaining == 0)
{
task.loops.pop_back();
++task.pc;
}
else
{
task.pc = loop.body;
// At a repeat boundary, pending input and newer ready tasks can run.
if (interactive || std::any_of(tasks.begin(), tasks.end(), [&](const auto &entry) {
const auto &other = entry.second;
return other.state == State::Ready && other.readyOrder > task.readyOrder;
}))
{
task.state = State::Ready;
active.reset();
}
}
}
else if (command.kind == ActionKind::Wait)
{
if (now > Clock::time_point::max() - command.waitDuration)
throw std::overflow_error("wait deadline exceeds steady clock range");
@@ -94,9 +148,14 @@ std::optional<ActionScheduler::Work> ActionScheduler::Next(Clock::time_point now
// Even wait 0 yields once. It is promoted on the next Next() call.
continue;
}
inFlight = true;
interactiveInFlight = false;
return Work{command, task.id, false};
else
{
inFlight = true;
interactiveInFlight = false;
return Work{command, task.id, false};
}
if (++controlSteps == 256)
return std::nullopt;
}
}
+8
View File
@@ -101,6 +101,14 @@ std::string CommandBindings::Expand(std::string_view line, std::size_t maxLength
throw std::runtime_error("expanded command exceeds length limit");
substituted.append(token).append(spaces);
rest.remove_prefix(spaces.size());
// An inline do body is its own statement, with its own binding expansion.
if (verb == "do")
{
if (substituted.size() + rest.size() > maxLength)
throw std::runtime_error("expanded command exceeds length limit");
substituted.append(rest);
break;
}
}
return substituted;
}
+2 -2
View File
@@ -64,8 +64,8 @@ std::string ConsoleHelp()
"define [name [value...]]: store session parameters; use $name as a whole argument.\n"
"Game commands: goto, rclick, lclick, grclick, glclick, sw, swb, drop, sendcmd, sendmsg\n"
"rclick/lclick: add entry [t|b|s|n|w|e] for item frames; omit face to require a unique frame.\n"
"A game command waits until the running action finishes or reaches wait.\n"
"Only one interactive game command can be pending. wait/import are not allowed here.\n"
"A game command waits until completion, wait, or the next loop iteration.\n"
"Only one interactive game command can be pending. wait/import/do are only available in action files.\n"
"run validates and queues a file immediately; newest ready action runs first.\n"
"Native terminal: fixed input bar, Up/Down history, Left/Right/Home/End editing.\n"
"Ctrl+C/quit cancels; EOF drains queued tasks, then disconnects.\n";
+76
View File
@@ -1,4 +1,5 @@
#include "ActionFile.h"
#include "ActionScheduler.h"
#include "ConsoleCommand.h"
#include <atomic>
@@ -113,6 +114,81 @@ class ActionFileTest : public ::testing::Test
}
};
TEST_F(ActionFileTest, ExecutesNestedLoopsAndSingleStatementImportsInOrder)
{
Write("collect.act", "# action: collect\nsw 2\nsw 3\n");
auto program = Parse("# action: test\ndefine n 2\nalias pick sw\ndo $n begin\n"
" do 0 sw 9\n pick 1\n do 2\n # count the import as one statement\n"
" import collect\nend\ndo 2 do 2 pick 4\nsw 5\n");
Bilicraft::ActionScheduler queue;
queue.Enqueue(std::move(program));
for (int expected : {1,2,3,2,3,1,2,3,2,3,4,4,4,4,5})
{
const auto work = queue.Next({});
ASSERT_TRUE(work);
EXPECT_EQ(work->command.slot, expected);
queue.Finish(true);
}
EXPECT_FALSE(queue.Next({}));
EXPECT_FALSE(queue.HasWork());
}
TEST_F(ActionFileTest, AlwaysLoopResumesAfterWaitAndStopsOnCommandFailure)
{
using namespace std::chrono_literals;
auto program = Parse("# action: test\ndo always begin\nsw 3\nwait 2 s\nsw 4\nend\nsw 5");
Bilicraft::ActionScheduler queue;
Bilicraft::ActionScheduler::Clock::time_point now{};
queue.Enqueue(std::move(program), now);
for (int i = 0; i < 3; ++i)
{
const auto first = queue.Next(now);
ASSERT_TRUE(first);
EXPECT_EQ(first->command.slot, 3);
queue.Finish(true);
EXPECT_FALSE(queue.Next(now));
now += 2s;
const auto second = queue.Next(now);
ASSERT_TRUE(second);
EXPECT_EQ(second->command.slot, 4);
queue.Finish(i < 2);
}
EXPECT_FALSE(queue.HasWork());
}
TEST_F(ActionFileTest, EmptyInfiniteLoopReturnsControlAndVeryLargeCountsStayCompact)
{
Bilicraft::ActionScheduler queue;
auto program = Parse("# action: test\ndo 18446744073709551615 begin\nend\n"
"do always do 0 sw 9\nsw 5");
ASSERT_LT(program.commands.size(), 10u);
queue.Enqueue(std::move(program));
EXPECT_FALSE(queue.Next({}));
ASSERT_TRUE(queue.HasWork());
queue.SubmitInteractive(*ParseInteractiveCommand("sw 1"));
const auto work = queue.Next({});
ASSERT_TRUE(work);
EXPECT_TRUE(work->interactive);
queue.Finish(true);
EXPECT_FALSE(queue.Next({}));
}
TEST_F(ActionFileTest, ValidatesLoopStructureAndSkippedBodiesAtLoadTime)
{
for (auto count : {"-1", "1.2", "infine", "2x", "18446744073709551616"})
Reject(std::string("# action: test\ndo ") + count + " sw 1", "nonnegative integer or always");
Reject("# action: test\ndo", "nonnegative integer or always");
Reject("# action: test\ndo 1\n# no body", "missing statement");
Reject("# action: test\ndo 1 begin\nsw 1", "missing end");
Reject("# action: test\ndo 0 invalid", "unknown instruction");
Reject("# action: test\nend", "matching do");
Reject("# action: test\nbegin", "after do");
Reject("# action: test\ndo 1 begin\ndo 2\nend", "complete body", 4);
Write("child.act", "# action: child\nend");
Reject("# action: test\ndo 1 begin\nimport child\nend", "matching do", 3);
RejectInteractive("do always sw 1", "only available in action files");
}
TEST_F(ActionFileTest, ExpandsBindingsInSourceOrderAcrossImports)
{
Write("child.act", "# action: child\nhome\ndefine pos1 20 64 -8\nalias pause wait 1 s\n");