nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
bot.cc
Go to the documentation of this file.
1#include "bot/bot.h"
2
3#include <algorithm>
4#include <array>
5#include <chrono>
6#include <cmath>
7#include <cstddef>
8#include <iostream>
9#include <iterator>
10#include <optional>
11#include <random>
12#include <string>
13#include <utility>
14#include <vector>
15
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"
22#include "bot/bag.h"
23#include "bot/factions.h"
24#include "protocol/nanommo.pb.h"
25#include "terrain/lands.h"
26
27namespace nanommo {
28
29namespace {
30
31// What a bot says now and then, when it gets where it was going.
32constexpr std::array<const char*, 6> kLines = {
33 "hi all",
34 "anyone up for the Ashlands?",
35 "careful, skeletons over here",
36 "nice view from up here",
37 "where is everyone going?",
38 "brb",
39};
40
41// What a bot asks the storyteller for a story about: three words from the
42// game, which the model knows.
43constexpr std::array<const char*, 12> kWords = {
44 "sword", "gate", "skeleton", "meadow", "ash", "knight",
45 "dragon", "castle", "forest", "river", "island", "gold",
46};
47
48constexpr double kAskForAStory = 0.125;
49
50// While it wanders around somewhere, a bot uses a skill it knows with one
51// direction in four, as players do in a fight.
52constexpr double kUseASkill = 0.25;
53
54// A potion's cooldown, so that a bot doesn't ask for one the server refuses.
55constexpr std::chrono::seconds kDrinkEvery{10};
56
57// How close a bot gets for an errand, in metres. For a monster, near enough to
58// swing at it: the server runs it in the rest of the way, as it does a player
59// who clicks one, so a big monster that moves, like a boss, still gets hit.
60// For an NPC, within the four metres it hears you from.
61constexpr float kSwing = 6.0f;
62constexpr float kTalk = 3.0f;
63// The longest a bot at war waits at its camp for the rest of its side.
64constexpr auto kMuster = std::chrono::seconds(90);
65
66// How soon a bot thinks again once the monster it hunts is dead: soon, but
67// not before what it sent last has gone out.
68constexpr std::chrono::milliseconds kRethink{100};
69
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, " ");
74}
75
76} // namespace
77
78Bot::Bot(asio::io_context& io, asio::ssl::context& tls, uint32_t seed, bool udp,
79 const Content& content, std::optional<Side> side)
80 : stream_(io, tls),
81 udp_socket_(io),
82 timer_(io),
83 hello_timer_(io),
84 tick_timer_(io),
85 random_(seed),
86 udp_(udp),
87 content_(content),
88 side_(std::move(side)),
89 faction_(FactionFor(content, seed)) {}
90
91void Bot::Start(const asio::ip::tcp::resolver::results_type& server,
92 const std::string& token) {
93 // The resolver keeps the name we looked up, which the certificate must have.
94 const std::string host = server.begin()->host_name();
95 ExpectName(stream_, host);
96 asio::async_connect(
97 stream_.lowest_layer(), server,
98 [this, token, host](std::error_code error, const auto&) {
99 if (error) {
100 std::cerr << "nanommo bot: couldn't connect: " << error.message()
101 << '\n';
102 return;
103 }
104 std::error_code ignored;
105 stream_.lowest_layer().set_option(asio::ip::tcp::no_delay(true),
106 ignored);
107 stream_.async_handshake(asio::ssl::stream_base::client,
108 [this, token, host](std::error_code error) {
109 Greet(token, host, error);
110 });
111 });
112}
113
114void Bot::Greet(const std::string& token, const std::string& host,
115 std::error_code error) {
116 if (error) {
117 std::cerr << "nanommo bot: couldn't shake hands: "
118 << HandshakeError(stream_, host, error) << '\n';
119 return;
120 }
121 // Blocking is fine: a hello this small fits in the socket's buffer.
122 protocol::Hello hello;
123 hello.set_token(token);
124 asio::write(stream_, asio::buffer(Frame(hello)), error);
125 if (error) {
126 return;
127 }
128 connected_ = true;
129 Read();
130 Wander();
131 Tick();
132 if (udp_) {
133 const asio::ip::tcp::endpoint server =
134 stream_.lowest_layer().remote_endpoint(error);
135 if (!error) {
136 udp_socket_.connect({server.address(), server.port()}, error);
137 }
138 if (!error) {
139 token_ = token;
140 HelloOverUdp();
141 ReceiveOverUdp();
142 }
143 }
144}
145
146// Reading every world keeps the server's writes to us from backing up.
147void Bot::Read() {
148 stream_.async_read_some(asio::buffer(buffer_),
149 [this](std::error_code error, std::size_t size) {
150 if (error) {
151 Stop();
152 return;
153 }
154 reader_.Append({buffer_.data(), size});
155 while (const auto message = reader_.Next()) {
156 Receive(*message);
157 }
158 if (!reader_.status().ok()) {
159 Stop();
160 return;
161 }
162 Read();
163 });
164}
165
166void Bot::HelloOverUdp() {
167 if (!connected_ || udp_worlds_) {
168 return;
169 }
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) {
176 if (!error) {
177 HelloOverUdp();
178 }
179 });
180}
181
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) {
186 return;
187 }
188 if (!error) {
189 udp_worlds_ = true;
190 Receive({datagram_.data(), size});
191 }
192 ReceiveOverUdp();
193 });
194}
195
196void Bot::Receive(std::string_view bytes) {
197 protocol::World world;
198 // Chat and events have no land in them, which would read as the Meadows,
199 // and neither does a move. The bot goes by the world, so it skips events.
200 if (!world.ParseFromArray(bytes.data(), static_cast<int>(bytes.size())) ||
201 !world.chat().empty() || !world.events().empty()) {
202 return;
203 }
204 if (world.has_move()) {
205 move_ = world.move();
206 return;
207 }
208 // Our bag comes on its own too, with nothing of the world in it.
209 if (world.has_inventory()) {
210 bag_ = world.inventory();
211 return;
212 }
213 if (world.has_quests()) {
214 quests_ = world.quests();
215 return;
216 }
217 // A bot doesn't say yes to a duel, nor to a guild that asks it in, unless
218 // it's at war and that's its side's guild. It keeps its guild's news, for
219 // the war.
220 if (world.has_guild()) {
221 guild_ = world.guild();
222 return;
223 }
224 if (world.has_invite()) {
225 asked_in_ = side_ && world.invite().guild() == side_->guild;
226 return;
227 }
228 if (world.has_duel()) {
229 return;
230 }
231 parts_.Add(world);
232 // Once the monster it hunts is dead, the bot thinks again, and doesn't swing
233 // at the body for as long as it holds its input.
234 if (hunting_ != 0 && Dead(world, hunting_)) {
235 hunting_ = 0;
236 WanderIn(kRethink);
237 }
238 // And so does one at war once the enemy it's after is dead.
239 if (enemy_ != 0 &&
240 std::ranges::any_of(world.players(),
241 [this](const protocol::Player& player) {
242 return player.id() == enemy_ &&
243 player.motion() == protocol::MOTION_DEAD;
244 })) {
245 enemy_ = 0;
246 WanderIn(kRethink);
247 }
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());
252 }
253 for (const protocol::Player& player : world.players()) {
254 if (player.id() == world.you()) {
255 x_ = player.x();
256 z_ = player.z();
257 dead_ = player.motion() == protocol::MOTION_DEAD;
258 can_respawn_ = dead_ && world.respawn() == 0;
259 health_ = static_cast<int>(player.health());
260 // The most comes once a second, with the names.
261 if (player.max_health() != 0) {
262 max_health_ = static_cast<int>(player.max_health());
263 }
264 }
265 }
266 skills_ = {world.skills().begin(), world.skills().end()};
267 // In a monster's skill on its way, the bot runs out of it, as players learn
268 // to, and doesn't think of anything else until it's clear. Then it thinks
269 // again from where it is: the trip it was on counted on getting closer, and
270 // a boss's skills come one after another.
271 if (const std::optional<protocol::Input> out =
272 dead_ ? std::nullopt
273 : StepOut(content_.monsters, parts_.world(), x_, z_)) {
274 if (!stepping_out_) {
275 hunting_ = 0;
276 trip_.reset();
277 errand_.reset();
278 Send(*out);
279 }
280 stepping_out_ = true;
281 WanderIn(kRethink);
282 } else {
283 stepping_out_ = false;
284 }
285 // Through a gate: the trip was for the land we left.
286 if (world.land() != land_ && world.land() < kLands.size()) {
287 land_ = world.land();
288 trip_.reset();
289 storyteller_.reset();
290 asking_ = false;
291 errand_.reset();
292 }
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()) {
296 storyteller_ = npc;
297 }
298 }
299}
300
301void Bot::Wander() {
302 hunting_ = 0;
303 enemy_ = 0;
304 // At war, a bot does one thing at a time about its guild, with its keys as
305 // they are: says yes to its side's, once it's asked, or as its leader,
306 // founds it, takes it to war and asks the rest of its side in.
307 if (side_) {
308 std::optional<protocol::GuildAction> action;
309 if (asked_in_) {
310 asked_in_ = false;
311 action.emplace().set_accept(true);
312 } else {
313 action = Enlist(*side_, guild_, recruit_);
314 }
315 if (action) {
316 protocol::Input keys = keys_;
317 *keys.mutable_guild() = *action;
318 Send(keys);
319 }
320 }
321 // A dead bot comes back as soon as it can, as most players do.
322 if (dead_) {
323 if (can_respawn_) {
324 protocol::Input respawn;
325 respawn.set_respawn(true);
326 Send(respawn);
327 }
328 WanderIn(std::chrono::seconds(1));
329 return;
330 }
331 // At war, a bot waits at its side's camp until all its side is in the
332 // guild, so that the two sides charge each other in lines, rather than
333 // fighting where each of them comes into the world. A minute and a half
334 // after it joined, it goes anyway, for a side whose bots don't all log in.
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_) {
339 joined_ = now;
340 }
341 charged_ = (in && guild_.members_size() >= side_->size) ||
342 (joined_ && now - *joined_ >= kMuster);
343 if (!charged_) {
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));
347 return;
348 }
349 }
350 // In its guild, it goes for the nearest enemy it can see, before anything
351 // else, and the server runs it up to them.
352 if (side_ && guild_.name() == side_->guild) {
353 enemy_ = NearestEnemy(*side_, parts_.world(), x_, z_);
354 }
355 if (enemy_ != 0) {
356 trip_.reset();
357 errand_.reset();
358 protocol::Input attack;
359 attack.set_attack(true);
360 attack.set_target_player(enemy_);
361 Send(attack);
362 WanderIn(std::chrono::seconds(1));
363 return;
364 }
365 // Quests come first: a bot hunts what they ask for, and takes and turns them
366 // in, as players do, whenever its world has some of that around it.
367 if (!trip_ && stay_ == 0) {
368 const protocol::World seen = parts_.world();
369 // Before them, it swears to its faction, at its herald, where it sees them
370 // or where they stand in its land, as a new player might on their first
371 // day.
372 errand_ = !swore_ && !Sworn(seen)
373 ? Oath(content_, faction_, seen, static_cast<int>(land_))
374 : std::nullopt;
375 if (!errand_) {
376 errand_ = NextErrand(content_, quests_, seen, x_, z_);
377 }
378 if (errand_) {
379 trip_ =
380 Trip{.to_x = errand_->x,
381 .to_z = errand_->z,
382 .there = errand_->kind == Errand::Kind::kHunt ? kSwing : kTalk};
383 }
384 }
385 // Otherwise, like players, a bot goes somewhere on the island, and stays
386 // around there for a while. One trip in eight goes to the storyteller, once
387 // the bot has seen it, for a story.
388 if (!trip_ && stay_ == 0) {
389 asking_ =
390 storyteller_ && std::bernoulli_distribution(kAskForAStory)(random_);
391 trip_ = asking_ ? Trip{.to_x = storyteller_->x(), .to_z = storyteller_->z()}
392 : RandomTrip(random_,
393 RandomGate(random_, static_cast<int>(land_)));
394 }
395 std::optional<protocol::Input> input;
396 std::string say;
397 std::optional<protocol::Talk> talk;
398 if (trip_) {
399 input = Travel(*trip_, x_, z_);
400 if (!input && errand_) {
401 // There, unless it stopped getting closer, at the sea or a lake, when it
402 // wanders around for a while instead. The next errand goes after
403 // whatever's nearest then, as monsters move.
404 if (std::hypot(trip_->to_x - x_, trip_->to_z - z_) < trip_->there) {
405 input.emplace();
406 if (errand_->kind == Errand::Kind::kHunt) {
407 input->set_attack(true);
408 // Picked first, as a player clicks it, so the swings go for it.
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) {
414 // A bot that set off before it saw the herald sees them here, or
415 // gives up, as nobody stands there.
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);
422 }
423 swore_ = true;
424 } else {
425 *input->mutable_turn_in() = errand_->quest;
426 }
427 } else {
428 stay_ = std::uniform_int_distribution<int>(5, 15)(random_);
429 }
430 trip_.reset();
431 errand_.reset();
432 } else if (!input) {
433 trip_.reset();
434 stay_ = std::uniform_int_distribution<int>(5, 15)(random_);
435 if (asking_ && storyteller_) {
436 asking_ = false;
437 talk.emplace();
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_)];
443 }
444 }
445 }
446 if (!input) {
447 --stay_;
448 input = RandomDirection(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_)]);
452 }
453 }
454 // As a player would, a bot drinks a potion when it's hurt, and wears what
455 // it finds, which keeps the servers saving and sending bags.
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()) {
462 drank_ = now;
463 }
464 }
465 input->set_say(say);
466 if (talk) {
467 *input->mutable_talk() = *talk;
468 }
469 Send(*input);
470 WanderIn(trip_ ? std::chrono::seconds(1) : RandomHold(random_));
471}
472
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());
480 // With the newest world it has whole, as the client does.
481 protocol::Input with = input;
482 with.set_seen(parts_.whole());
483 Write(Frame(with));
484}
485
486void Bot::Tick() {
487 if (!connected_) {
488 return;
489 }
490 // The keys alone, so that nothing else it did happens again.
491 protocol::Input keys = keys_;
492 keys.set_seen(parts_.whole());
493 Write(Frame(keys));
494 tick_timer_.expires_after(std::chrono::milliseconds(50));
495 tick_timer_.async_wait([this](std::error_code error) {
496 if (!error) {
497 Tick();
498 }
499 });
500}
501
502void Bot::Write(std::string frame) {
503 outbox_.push_back(std::move(frame));
504 // One write at a time on a stream: the next starts as this one ends.
505 if (outbox_.size() > 1) {
506 return;
507 }
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) {
511 outbox_.pop_front();
512 if (error) {
513 connected_ = false;
514 outbox_.clear();
515 return;
516 }
517 if (!outbox_.empty()) {
518 self(self);
519 }
520 });
521 };
522 next(next);
523}
524
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_) {
529 Wander();
530 }
531 });
532}
533
535 Stop();
536 std::error_code ignored;
537 stream_.lowest_layer().close(ignored);
538}
539
540void Bot::Stop() {
541 connected_ = false;
542 timer_.cancel();
543 hello_timer_.cancel();
544 tick_timer_.cancel();
545 std::error_code ignored;
546 udp_socket_.close(ignored);
547}
548
549} // namespace nanommo
const std::optional< protocol::Move > & move() const
Where the bot's world told it to go, once it hands its players over.
Definition bot.h:48
void Start(const asio::ip::tcp::resolver::results_type &server, const std::string &token)
Definition bot.cc:91
void Leave()
Closes the connection, as a player who goes elsewhere does.
Definition bot.cc:534
Bot(asio::io_context &io, asio::ssl::context &tls, uint32_t seed, bool udp, const Content &content, std::optional< Side > side=std::nullopt)
Definition bot.cc:78
Definition chat.cc:9
Trip RandomTrip(std::mt19937 &random, const Place &gate)
Definition wander.cc:47
std::optional< protocol::Input > Travel(Trip &trip, float x, float z)
Definition wander.cc:60
Place RandomGate(std::mt19937 &random, int land)
One of the land's gates, at random, as players go through each of them.
Definition wander.cc:35
bool Sworn(const protocol::World &seen)
Definition factions.cc:46
void Wander(Monster &monster, const Terrain &terrain, std::chrono::nanoseconds time, std::mt19937 &random)
Definition monsters.cc:162
std::optional< Errand > Oath(const Content &content, uint32_t faction, const protocol::World &seen, int land)
Definition factions.cc:21
uint32_t NearestEnemy(const Side &side, const protocol::World &seen, float x, float z)
Definition war.cc:43
std::optional< protocol::GuildAction > Enlist(const Side &side, const protocol::Guild &guild, std::size_t &next)
Definition war.cc:15
protocol::Input RandomDirection(std::mt19937 &random)
Definition wander.cc:20
std::string Frame(const google::protobuf::MessageLite &message)
The size goes in front, as four bytes in network byte order.
Definition framing.cc:14
constexpr std::array< Land, 3 > kLands
Definition lands.h:31
std::optional< protocol::Input > StepOut(const MonsterTable &table, const protocol::World &world, float x, float z)
Definition wander.cc:80
std::chrono::milliseconds RandomHold(std::mt19937 &random)
Definition wander.cc:30
std::optional< protocol::ItemAction > Tend(const ItemTable &items, const protocol::Inventory &bag, int health, int max_health, bool can_drink)
Definition bag.cc:10
void ExpectName(TlsStream &stream, const std::string &host)
Definition tls.cc:52
bool Dead(const protocol::World &seen, uint32_t monster)
Definition quests.cc:89
uint32_t FactionFor(const Content &content, uint32_t seed)
Definition factions.cc:12
std::optional< Errand > NextErrand(const Content &content, const protocol::Quests &quests, const protocol::World &seen, float x, float z)
Definition quests.cc:30