16#include "absl/strings/str_join.h"
17#include "asio/buffer.hpp"
18#include "asio/connect.hpp"
19#include "asio/error.hpp"
20#include "asio/ssl/stream_base.hpp"
21#include "asio/write.hpp"
24#include "protocol/nanommo.pb.h"
32constexpr std::array<const char*, 6> kLines = {
34 "anyone up for the Ashlands?",
35 "careful, skeletons over here",
36 "nice view from up here",
37 "where is everyone going?",
43constexpr std::array<const char*, 12> kWords = {
44 "sword",
"gate",
"skeleton",
"meadow",
"ash",
"knight",
45 "dragon",
"castle",
"forest",
"river",
"island",
"gold",
48constexpr double kAskForAStory = 0.125;
52constexpr double kUseASkill = 0.25;
55constexpr std::chrono::seconds kDrinkEvery{10};
61constexpr float kSwing = 6.0f;
62constexpr float kTalk = 3.0f;
64constexpr auto kMuster = std::chrono::seconds(90);
68constexpr std::chrono::milliseconds kRethink{100};
70std::string RandomWords(std::mt19937& random) {
71 std::vector<const char*> words;
72 std::ranges::sample(kWords, std::back_inserter(words), 3, random);
73 return absl::StrJoin(words,
" ");
78Bot::Bot(asio::io_context& io, asio::ssl::context& tls, uint32_t seed,
bool udp,
79 const Content& content, std::optional<Side> side)
88 side_(std::
move(side)),
91void Bot::Start(
const asio::ip::tcp::resolver::results_type& server,
92 const std::string& token) {
94 const std::string host = server.begin()->host_name();
97 stream_.lowest_layer(), server,
98 [
this, token, host](std::error_code error,
const auto&) {
100 std::cerr <<
"nanommo bot: couldn't connect: " << error.message()
104 std::error_code ignored;
105 stream_.lowest_layer().set_option(asio::ip::tcp::no_delay(
true),
107 stream_.async_handshake(asio::ssl::stream_base::client,
108 [
this, token, host](std::error_code error) {
109 Greet(token, host, error);
114void Bot::Greet(
const std::string& token,
const std::string& host,
115 std::error_code error) {
117 std::cerr <<
"nanommo bot: couldn't shake hands: "
118 << HandshakeError(stream_, host, error) <<
'\n';
122 protocol::Hello hello;
123 hello.set_token(token);
124 asio::write(stream_, asio::buffer(
Frame(hello)), error);
133 const asio::ip::tcp::endpoint server =
134 stream_.lowest_layer().remote_endpoint(error);
136 udp_socket_.connect({server.address(), server.port()}, error);
148 stream_.async_read_some(asio::buffer(buffer_),
149 [
this](std::error_code error, std::size_t size) {
154 reader_.Append({buffer_.data(), size});
155 while (
const auto message = reader_.Next()) {
158 if (!reader_.status().ok()) {
166void Bot::HelloOverUdp() {
167 if (!connected_ || udp_worlds_) {
170 protocol::Hello hello;
171 hello.set_token(token_);
172 std::error_code ignored;
173 udp_socket_.send(asio::buffer(hello.SerializeAsString()), 0, ignored);
174 hello_timer_.expires_after(std::chrono::milliseconds(250));
175 hello_timer_.async_wait([
this](std::error_code error) {
182void Bot::ReceiveOverUdp() {
183 udp_socket_.async_receive(
184 asio::buffer(datagram_), [
this](std::error_code error, std::size_t size) {
185 if (!connected_ || error == asio::error::operation_aborted) {
190 Receive({datagram_.data(), size});
196void Bot::Receive(std::string_view bytes) {
197 protocol::World world;
200 if (!world.ParseFromArray(bytes.data(),
static_cast<int>(bytes.size())) ||
201 !world.chat().empty() || !world.events().empty()) {
204 if (world.has_move()) {
205 move_ = world.move();
209 if (world.has_inventory()) {
210 bag_ = world.inventory();
213 if (world.has_quests()) {
214 quests_ = world.quests();
220 if (world.has_guild()) {
221 guild_ = world.guild();
224 if (world.has_invite()) {
225 asked_in_ = side_ && world.invite().guild() == side_->guild;
228 if (world.has_duel()) {
234 if (hunting_ != 0 &&
Dead(world, hunting_)) {
240 std::ranges::any_of(world.players(),
241 [
this](
const protocol::Player& player) {
242 return player.id() == enemy_ &&
243 player.motion() == protocol::MOTION_DEAD;
248 const uint32_t parts = std::max(world.parts(), 1u);
249 newest_.resize(parts);
250 if (world.part() < parts) {
251 newest_[world.part()] = std::max(newest_[world.part()], world.sent());
253 for (
const protocol::Player& player : world.players()) {
254 if (player.id() == world.you()) {
257 dead_ = player.motion() == protocol::MOTION_DEAD;
258 can_respawn_ = dead_ && world.respawn() == 0;
259 health_ =
static_cast<int>(player.health());
261 if (player.max_health() != 0) {
262 max_health_ =
static_cast<int>(player.max_health());
266 skills_ = {world.skills().begin(), world.skills().end()};
271 if (
const std::optional<protocol::Input> out =
273 :
StepOut(content_.monsters, parts_.world(), x_, z_)) {
274 if (!stepping_out_) {
280 stepping_out_ =
true;
283 stepping_out_ =
false;
286 if (world.land() != land_ && world.land() <
kLands.size()) {
287 land_ = world.land();
289 storyteller_.reset();
293 for (
const protocol::Npc& npc : world.npcs()) {
294 const auto kind = content_.npcs.kinds.find(npc.kind());
295 if (kind != content_.npcs.kinds.end() && kind->second.talks()) {
308 std::optional<protocol::GuildAction> action;
311 action.emplace().set_accept(
true);
313 action =
Enlist(*side_, guild_, recruit_);
316 protocol::Input keys = keys_;
317 *keys.mutable_guild() = *action;
324 protocol::Input respawn;
325 respawn.set_respawn(
true);
328 WanderIn(std::chrono::seconds(1));
335 if (side_ && !charged_) {
336 const auto now = std::chrono::steady_clock::now();
337 const bool in = guild_.name() == side_->guild;
338 if (in && !joined_) {
341 charged_ = (in && guild_.members_size() >= side_->size) ||
342 (joined_ && now - *joined_ >= kMuster);
344 Trip camp{.to_x = side_->camp_x, .to_z = side_->camp_z, .there = 1.0f};
345 Send(
Travel(camp, x_, z_).value_or(protocol::Input()));
346 WanderIn(std::chrono::seconds(1));
352 if (side_ && guild_.name() == side_->guild) {
358 protocol::Input attack;
359 attack.set_attack(
true);
360 attack.set_target_player(enemy_);
362 WanderIn(std::chrono::seconds(1));
367 if (!trip_ && stay_ == 0) {
368 const protocol::World seen = parts_.world();
372 errand_ = !swore_ && !
Sworn(seen)
373 ?
Oath(content_, faction_, seen,
static_cast<int>(land_))
376 errand_ =
NextErrand(content_, quests_, seen, x_, z_);
380 Trip{.to_x = errand_->x,
382 .there = errand_->kind == Errand::Kind::kHunt ? kSwing : kTalk};
388 if (!trip_ && stay_ == 0) {
390 storyteller_ && std::bernoulli_distribution(kAskForAStory)(random_);
391 trip_ = asking_ ? Trip{.to_x = storyteller_->x(), .to_z = storyteller_->z()}
393 RandomGate(random_,
static_cast<int>(land_)));
395 std::optional<protocol::Input> input;
397 std::optional<protocol::Talk> talk;
399 input =
Travel(*trip_, x_, z_);
400 if (!input && errand_) {
404 if (std::hypot(trip_->to_x - x_, trip_->to_z - z_) < trip_->there) {
406 if (errand_->kind == Errand::Kind::kHunt) {
407 input->set_attack(
true);
409 input->set_target(errand_->monster);
410 hunting_ = errand_->monster;
411 }
else if (errand_->kind == Errand::Kind::kTake) {
412 *input->mutable_take() = errand_->quest;
413 }
else if (errand_->kind == Errand::Kind::kSwear) {
416 const std::optional<Errand> oath =
417 errand_->herald != 0 ? errand_
418 :
Oath(content_, faction_, parts_.world(),
419 static_cast<int>(land_));
420 if (oath && oath->herald != 0) {
421 input->set_enlist(oath->herald);
425 *input->mutable_turn_in() = errand_->quest;
428 stay_ = std::uniform_int_distribution<int>(5, 15)(random_);
434 stay_ = std::uniform_int_distribution<int>(5, 15)(random_);
435 if (asking_ && storyteller_) {
438 talk->set_npc(storyteller_->id());
439 talk->set_words(RandomWords(random_));
440 }
else if (std::bernoulli_distribution(0.25)(random_)) {
441 say = kLines[std::uniform_int_distribution<std::size_t>(
442 0, kLines.size() - 1)(random_)];
449 if (!skills_.empty() && std::bernoulli_distribution(kUseASkill)(random_)) {
450 input->set_skill(skills_[std::uniform_int_distribution<std::size_t>(
451 0, skills_.size() - 1)(random_)]);
456 const auto now = std::chrono::steady_clock::now();
457 if (
const std::optional<protocol::ItemAction> item =
458 Tend(content_.items, bag_, health_, max_health_,
459 now - drank_ >= kDrinkEvery)) {
460 *input->mutable_item() = *item;
461 if (item->has_use()) {
467 *input->mutable_talk() = *talk;
470 WanderIn(trip_ ? std::chrono::seconds(1) :
RandomHold(random_));
473void Bot::Send(
const protocol::Input& input) {
474 keys_.set_x(input.x());
475 keys_.set_z(input.z());
476 keys_.set_run(input.run());
477 keys_.set_attack(input.attack());
478 keys_.set_target(input.target());
479 keys_.set_target_player(input.target_player());
481 protocol::Input with = input;
482 with.set_seen(parts_.whole());
491 protocol::Input keys = keys_;
492 keys.set_seen(parts_.whole());
494 tick_timer_.expires_after(std::chrono::milliseconds(50));
495 tick_timer_.async_wait([
this](std::error_code error) {
502void Bot::Write(std::string frame) {
503 outbox_.push_back(std::move(frame));
505 if (outbox_.size() > 1) {
508 const auto next = [
this](
const auto& self) ->
void {
509 asio::async_write(stream_, asio::buffer(outbox_.front()),
510 [
this, self](std::error_code error, std::size_t) {
517 if (!outbox_.empty()) {
525void Bot::WanderIn(std::chrono::milliseconds wait) {
526 timer_.expires_after(wait);
527 timer_.async_wait([
this](std::error_code error) {
528 if (!error && connected_) {
536 std::error_code ignored;
537 stream_.lowest_layer().close(ignored);
543 hello_timer_.cancel();
544 tick_timer_.cancel();
545 std::error_code ignored;
546 udp_socket_.close(ignored);
const std::optional< protocol::Move > & move() const
Where the bot's world told it to go, once it hands its players over.
void Start(const asio::ip::tcp::resolver::results_type &server, const std::string &token)
void Leave()
Closes the connection, as a player who goes elsewhere does.
Bot(asio::io_context &io, asio::ssl::context &tls, uint32_t seed, bool udp, const Content &content, std::optional< Side > side=std::nullopt)
Trip RandomTrip(std::mt19937 &random, const Place &gate)
std::optional< protocol::Input > Travel(Trip &trip, float x, float z)
Place RandomGate(std::mt19937 &random, int land)
One of the land's gates, at random, as players go through each of them.
bool Sworn(const protocol::World &seen)
void Wander(Monster &monster, const Terrain &terrain, std::chrono::nanoseconds time, std::mt19937 &random)
std::optional< Errand > Oath(const Content &content, uint32_t faction, const protocol::World &seen, int land)
uint32_t NearestEnemy(const Side &side, const protocol::World &seen, float x, float z)
std::optional< protocol::GuildAction > Enlist(const Side &side, const protocol::Guild &guild, std::size_t &next)
protocol::Input RandomDirection(std::mt19937 &random)
std::string Frame(const google::protobuf::MessageLite &message)
The size goes in front, as four bytes in network byte order.
constexpr std::array< Land, 3 > kLands
std::optional< protocol::Input > StepOut(const MonsterTable &table, const protocol::World &world, float x, float z)
std::chrono::milliseconds RandomHold(std::mt19937 &random)
std::optional< protocol::ItemAction > Tend(const ItemTable &items, const protocol::Inventory &bag, int health, int max_health, bool can_drink)
void ExpectName(TlsStream &stream, const std::string &host)
bool Dead(const protocol::World &seen, uint32_t monster)
uint32_t FactionFor(const Content &content, uint32_t seed)
std::optional< Errand > NextErrand(const Content &content, const protocol::Quests &quests, const protocol::World &seen, float x, float z)