nanoMMO

MMORPG gold and player trading in C++

Monsters in our C++ MMORPG drop gold, kept in the bag's message and saved with it, and two players trade items and gold in a window, in a simple version the server swaps all or nothing.

Watch on YouTube

Gold and player trading for our MMORPG, in C++. Monsters drop a few coins each, which go in the bag's message, outside its slots, so gold changes with the bag's revision: the server sends it with the bag, Redis keeps it in the bag's bytes, and MySQL gets a column for it, written when the bag is. Then trading: /trade and a name asks a player within four metres, and once they ask back, the world keeps the trade, each side offers stacks from their bag and gold, a change to either offer makes neither side ready, and once both are, the two bags swap in copies, all of it or none. The server sends each side the trade's news over TCP, and the client gets a trade window you drag items into, with what you offer locked in the bag. It's the simple version, which trusts what was offered to stay where it was. This is episode 74 of a series about building an MMORPG from scratch in C++, with the focus on the engineering around the game.

Topics: Databases, Gameplay

The code

Each step on screen is a tag in the game's repository. The code at the end of the episode is ep074/end.

  1. 3:01ep074/step-1Gold from monstersBrowseChanges
  2. 9:22ep074/step-2Gold in the bagBrowseChanges
  3. 16:48ep074/step-3Trades in the worldBrowseChanges
  4. 38:42ep074/step-4Over the networkBrowseChanges
  5. 47:48ep074/step-5A trade windowBrowseChanges
  6. 56:51ep074/endWrap-upBrowseChanges

Transcript

Intro

0:00 Pretty grey and rainy out today, so a good day to stay in and write some code! And this time, our game finally gets gold, and a way to trade with other players.

0:13 Hello and welcome back to episode seventy-four, where the monsters start paying out a few coins each, and two players can swap items and gold in a window, with the server deciding each step. In my opinion, trading is where an MMO's server has to be at its most careful, as one click changes two players' bags at once. So we're going to build a simple version of it first, which keeps the code short enough to follow. Let's begin with a quick look at where we're going to be by the end of the episode.

0:41 By the end of the episode, gwen and arthur trade items and gold, as any two players standing near each other can. Seven bones go onto our side, with forty gold, which monsters drop now, for gwen's Ash Blade, and once she's had a moment to look, she says she's ready, so her side lights green. When both sides are ready, the server swaps the two offers, all of it or none, and the trade is over for both players, so the window closes.

1:06 The code for all of this is open source, on GitHub, and the series' website links to it, with a page for each episode, where you can browse its code at each of its steps.

Last time

1:16 Now, before we get to today's work, let's quickly go over what we did last time. Each way the game is built, from the release build to the sanitizers, the fuzzers and coverage, got a CMake preset, with a build folder of its own, and the Dockerfile and CI build with those presets now. Then the code moved to C++23, and its libraries with it, after a bit of trial and error with the compilers. The server's timer lambdas take their own object as self, so they hand themselves back to Asio without a std function, and the terrain's grids read by row and column. They go through a grid class of our own, which checks each index. And decision record twenty-six says why we made the move.

Today

1:57 Here's the game as the last episode left it. The bag holds what we carry, in its twenty-four slots, and so far, that's items and nothing else. When a skeleton dies, the world rolls the loot of its kind, bones now and then, or a potion, puts what it rolled in the killer's bag, and the chat says what went in. So the bones pile up in the bag, quite a few of them by now, and today they're going to start being worth something.

2:24 So, today, monsters drop gold, a few coins each, which goes in the bag, in a field of its own, outside the slots, and MySQL keeps it with the bag. Then trading, where each world keeps the trades between its players, and the server sends each side the trade's news, over TCP, while the client gets a window to drag what you offer into. It's the simple version of trading, which takes a couple of things on trust, and I'll point them out when we get there. I'm pretty excited about this one, as it's the first time something from one player's bag ends up in another's! Right, let's start with how much gold each kind of monster drops.

Gold from monsters

3:01 First, in the top CMake file, the game's version goes up to zero point seventy-four, for this episode's code. The monsters are content, so how much gold each kind drops goes in the monsters' proto file, next to its loot. Gold is a message of its own, with a min and a max, like the counts of a drop. Over it, we write how it works: a kind drops gold each time, from min to max, which goes to its killer without a slot of the bag, and without it, none. Each kind gets its gold as field nine. In the monsters file, a skeleton drops one to five, an Ash Skeleton three to nine, and a Crypt Skeleton six to fourteen, so the higher the monster's level, the more each kill pays. I've kept the numbers pretty small on purpose, a handful of coins a kill, so that gold is worth something once players start trading it. In the monsters' header file, the description of Parse monsters adds gold from more to less to the mistakes it refuses. And in monsters, after the checks of each kind's loot, a kind whose gold has a max below its min is refused, with an invalid argument error that names the kind and both numbers, as the loot's checks do. That way, a slip in the file stops the servers as they start, where a draw from nine down to two would be undefined behaviour in the random number generator.

4:18 A player's gold could live in a few places, and I went back and forth on it quite a bit before settling on the bag. The decision record at the end of the episode has the others I weighed. In our proto file, it goes in the bag's message, Inventory, as field four, after the bag's revision. Over it, we write why: gold is in no slot, and it changes with the bag, as a trade is going to give items and gold together, and they should change as one. In the inventory's header file, the most gold a player carries is a constant, a billion, with C++14's digit separators, so you can count the zeros, which I can't do reliably without them. Above it, we say why a billion: an unsigned thirty-two-bit number holds a little over four billion, so adding any two amounts under a billion stays inside it, and can't wrap round to a small number. Gold hands back what the bag's message has, and add gold adds some, up to the most, and returns how much didn't fit, the way Add does for a stack. In the inventory, add gold works out the room left under the most, or zero for a bag that's at it already. Added is the smaller of the amount and the room. If that's anything at all, the message gets the new total, and Changed takes the bag to its next revision, as a move between slots does. So the server sends the bag to its client when the revision moves, and saves it to Redis in its bytes, gold and all, without any code of its own for the gold. MySQL needs a column for it, which comes in a moment. Last, add gold returns whatever didn't fit, which is zero nearly all the time. In the world's header file, Loot's description adds the monster's gold. In the world, Loot rolls each drop of the dead monster's kind into the killer's bag, and collects what was kept, for the line in the chat. After the drops, an if with an initialiser declares gold for the if alone, and goes on when the kind has a max above zero. Over it, we note that gold takes no slot, so a full bag takes it too. Coins is a uniform draw from min to max, from the world's random engine, like the drops' counts. Carried is the coins, less what didn't fit under the billion, and if that's anything, it goes on the list of what was kept, as so many gold. So the line in the chat now ends with the gold, as the last thing the monster dropped.

6:34 Now, let's pin this down with a few quick tests. In the content's tests, the test that reads the game's content checks that a skeleton drops some gold, with a max above zero. The one that refuses loot that doesn't add up gets a skeleton whose gold goes from nine down to two, and its error has to say the Skeleton drops from nine to two gold. In the inventory's tests, a test that it carries gold up to the most. Forty gold all fit, so nothing comes back, and the bag says forty. The revision goes to one: gold changes the bag, so it goes with the bag's revision. Then a billion more: the bag fills up to the most, and the forty that didn't fit come back. What doesn't fit under the most comes back, and adding none isn't a change. So five more don't fit at all, all five come back, and the revision stays at two, from the billion. And in the world's tests, we bring in Abseil's str cat, to build the line we expect. The test that monsters drop gold starts from the looted skeleton the tests before it use, which always drops two bones and a blade, and gives it four to nine gold. A world with the test gear and that monster has a player join, who kills one. Carried, the gold in their bag, has to be from four to nine, and when we take the notices, there's one, which says what dropped, with the bones, the blade, and as much gold as they carried at the end. Then a second player comes in, with a sword in hand. Gold takes no slot, so a player whose bag is full gets it anyway. They fill all twenty-four slots with caps, join, and kill one too. They still get at least four gold, though their bag has no room left. And of their two notices, the first, about what dropped, ends with the gold, while the second says the bones and the blade were left behind.

8:18 We build the game at this step and run the four tests, the content's two and the server's two. None of them needs a server or a database, so dash dash no deps leaves MySQL and Redis out, and grep keeps the lines of the tests that passed. The build takes a while, as the image builds the whole game from the top, with this step's code. All four pass: the content refuses gold from more to less, the bag stops at a billion, and monsters drop gold, into a full bag too.

Gold in the bag

8:47 Next, the gold goes on screen, in the bag window, where we bring in Font Awesome's icons, which the client merges into its text font, so an icon can sit in a line of text. Under the slots, a line in the theme's gold shows a coin and how much gold the bag has, from the message the server sends each time the bag changes. And above it, we write that gold takes no slot, so it goes under them. And that's pretty much it for the client side of the gold. It keeps nothing of its own for the gold, as the bag arrives whole, with its gold in it, each time it changes.

9:22 At this step, arthur starts out without any gold. The bag shows it under the slots, with the coin, at nought for now. When a skeleton dies, the world draws its gold along with its loot, and adds it to arthur's bag, which takes the bag to its next revision. So after the tick, the server sends the whole bag to arthur's client, over TCP, and the line in the chat ends with the gold, while the bag window shows the new total, from the bag it's sent. It's pretty satisfying to watch the first coins come in!

Saving the gold

9:53 The gold has been saved in Redis since the last step, inside the bag's bytes, so what's left is MySQL, which gets a migration of its own, the twelfth, which runs like the others before the servers start. At its top, we write that a player's gold is in their bag's message, with the bag's revision, so the saver writes it as it does the bag, when that's changed. Then it alters the players table, adding a gold column, an unsigned int, which can be null, for a player whose bag hasn't been saved since the column came in. Algorithm instant changes the table's definition without copying its rows, like our earlier columns. In players, Bag of builds a player's bag from its rows in MySQL, and its description now says it takes its revision and its gold from the player's row. It takes the gold as a string, as the database hands us each column. Coins starts at zero, for a player saved before the column existed, whose gold is null and comes back empty. Anything that isn't a number is an internal error, as our saver is what writes that column. The bag gets its gold, from coins, next to its revision. Load's select reads the gold after the quests, as the ninth column, and passes it on to Bag of, with the revision. Then Flush, the saver's side, which writes the unsaved players to MySQL in one statement. A bag that hasn't changed keeps the revision and the gold MySQL has, so each row gets one more placeholder, for the gold. A row whose bag hasn't changed gets two empty strings, which NULLIF turns into nulls, while a changed bag gets its revision and its gold, read from the bag's bytes in Redis. The table of saved values gets a gold column, and the update sets the players' gold with COALESCE, which takes the saved one, or keeps what MySQL had when the saved one is null. I like that the gold is written when the bag is, and at no other time, so the two can't drift apart.

11:46 Next, a quick test that the gold is saved with the bag. It goes in the players' tests, which run against MySQL and Redis, with a fixture that makes an account and a character for each test and cleans them up afterwards. It makes our players class on the fixture's database and Redis, and keeps the character's id as a string, for the SQL further down. The fixture's Bag helper gives a bag of twelve bones and an Ash Blade, at revision two, and we give it a hundred and twenty gold. Save is what the server calls after a tick, for the players who changed, and here it writes the player's hash to Redis, with this bag in it, at revision two. Then we load the player straight back, as the server does when they log in again. Redis has the gold in the bag's bytes, so it comes back as a hundred and twenty, before MySQL has seen any of it. Then a flush, which is the saver's job, and MySQL keeps the gold in the player's row, with the bag's revision. We select both columns for this player, and the one row has to say two and a hundred and twenty, side by side, as strings, which is how the database hands its values back. Last, a save of where they are, two metres along, at the bag's revision but without a bag, and another flush. That's the common case, a player who moved and changed nothing in their bag, and it has to leave the gold where it was. Then we delete the player's hash in Redis, as if Redis had lost it, so that Load has to read the player from MySQL. The gold comes back from there, a hundred and twenty, and the whole bag matches the one we saved, with its debug string printed if it doesn't.

13:23 We run all of the players' tests at this step, as Load and Flush both changed. They need MySQL and Redis, so this time Compose starts them first, with the migrations, twelve of them now, and the tests connect to both. The build comes first, as the server's code has changed. The gold is saved with the bag and comes back from MySQL, and the players' other tests pass as before.

Trading

13:48 Here's the game as the last episode left it again, with gwen a couple of metres ahead of arthur. The client has no slash trade command yet, so the line goes to the world, as something said to everyone in Ember. And dragging the bones out of the bag, and letting go of them over gwen, doesn't hand them to her: letting go over the world asks whether to throw them away, so they stay in the bag. I've clicked Keep it on that question more often than I'd like to admit. In most other games, two players trade in a window where each puts in what they'll give, and nothing moves until both of them agree, which is what we're going to build.

14:23 A trade starts with a player asking another by name, standing close, within the four metres we use for talking to an NPC. It opens once the other asks back, so nobody gets a window they didn't want. Each side then offers stacks from their bag, by where they are in it, and some gold. Whenever an offer changes, neither side is ready any more, as there's something new to look at. That rule matters a lot, and I mean a lot, as it keeps an offer from changing after you've said you're ready for it. Once both are ready, the server gives each side what the other offered, working on copies of both bags, so that either all of it happens or none of it does. As with the rest of the game, the server decides each step, while the client draws the trade and sends what you do.

15:05 First, the messages a trade needs, in our proto file. The client's input gets a trade, a trade action, as field eighteen. We note over it that it's something to do about a trade with another player, sent once, like an item's. And the World message gets your trade, as field twenty-six, which comes on its own, over TCP, as it opens and as it changes, and with nobody in it as it ends. At the end of the file, a trade offer is what one side offers: places in their bag, as numbers, and some gold. Over it, we write that the stacks at those places are offered whole, which keeps the window simple, without splitting a stack inside a trade. A trade action is a oneof, as a player does one of these at a time. Ask names a player, near you in your land, to ask them to trade, or to say yes to them asking you first. Offer is what you offer, in place of what you offered before, so the client sends the whole offer each time, and the server has nothing to merge. Ready says whether you'll trade what's offered, both ways, and once both of you will, you trade. And cancel calls the trade off, for both of you. Over the message, we note that the server says why not in a line from nobody, as it does for an item. What the client is told about is a trade side, a map from places in the bag to stacks, the gold, and whether that side is ready. Above it, we write that the stacks are copies, by their places in the bag they came from, so the other side sees them as they were offered. And a trade is who it's with, by their name, then your side and theirs. Over it, we write that it's your trade, with nobody in it once it's over, and what each of you offers.

Trades in the world

16:49 The trades get a header file of their own, in the server, called trades. We bring in c std int, map and set from the standard library, then Abseil's status and status or, the items, for the item table, our protocol, and the inventory, as a trade moves things between two of them. Trades are the trades between the players in one copy of a land, which its World keeps. I consider the World the right home for them, as both players are always in that copy, so a gate or a log out reaches the trade through the world they leave. Over the class, we write how a trade goes. A player asks another to trade, and the trade opens once the other asks them back. Each side offers stacks from their bag, by their places, and gold, and once both sides are ready, each gets what the other offered. Then a second paragraph, which says that this is the simple version. An offer keeps a copy of each stack as it was offered, and the trade gives those copies, and takes as many as were offered off each place, trusting that what was offered is still there. Our client doesn't move what it's offered, so with our client, that holds. Keep that sentence in mind, as what this version takes on trust is where the next episode starts. Ask takes the player asking and the one they ask, by their ids, in place of anyone they asked before. If the other asked them first, the trade between them opens, and it returns true. Neither of them may be trading with someone already. With says who a player's trading with, by their id, or zero for nobody, and side of hands back what they offer, and whether they're ready, while they trade. Offer takes the player's bag, the item table and the offer, and keeps copies of the stacks at the offer's places, whole, and gold they have, in place of what they offered before. Neither side is ready any more, as there's something new to look at, or the error says why not, in words for the player. Ready sets whether the player's ready to trade what's offered, both ways, and returns whether both sides are now, or the error if they aren't trading. Complete does the trade, once both sides are ready. Each bag gives up what it offered and gets what the other offered, all of it or none, and the trade's over. If a bag hasn't room, or a side hasn't the gold it offered, neither side is ready any more, and the error says why, in words for both players. End ends the player's trade, if they're in one, along with their asking, and anyone's asking them, and returns who they were trading with. And take news hands over the players whose trade has opened, changed or ended since the last time, for the server to tell them. In private, one player's side of a trade is who it's with, by their id, and their offer. Asked maps each player to who they've asked to trade, by their ids, as a player asks one other at a time. Sides holds both sides of each trade, by each player's id, so one trade is two entries, and news is the set of players with news.

19:44 Before the trades' code, the inventory needs two more ways to take things out of a bag. In the inventory's header file, Take takes a count off the stack at a place, as trading some does, or the error says there aren't that many there. And take gold takes some gold away, or the error says there isn't that much. In the inventory, Take gets the stack at the place, as one it can change, and refuses when there's no stack there, or fewer than the count, with a not found error, in words for the player. With more than the count, the stack keeps the rest, and otherwise the place is cleared, so an empty stack doesn't sit in the bag. Either way, Changed moves the bag on to its next revision, as a change the client and the saver need to hear about. Take gold refuses an amount over the gold the bag has, as a failed precondition, and takes any other amount off, as a change. Taking zero changes nothing, so the revision stays where it is. Now for the code of the trades, in trades. We bring in array, c std def and c std int, map, set and utility, and places, from the protocol, for in bag, which makes a place in the bag from a slot's number. Ask starts by looking up who the other player has asked, if anyone. If they haven't asked anyone, or they've asked someone else, this player's asking is kept, in place of any before it, and nothing opens yet, so it returns false. Otherwise, each has asked the other, so both askings go, and each player gets a side that names the other, with designated initialisers, which name the field they set. Both have news, as the trade has opened, and it returns true. With finds the player's side, and hands back who it's with, or zero without one, and side of hands back the offer on the player's side. Offer starts by finding the player's side, and refusing a player who isn't trading with anyone, as a failed precondition, which the player sees as a line in the chat. Then it builds up what they offer, in a trade side of its own, going through the places in the offer, one at a time. A place with nothing in it is refused, as there's nothing there, and so is an item the content doesn't have, which a bag keeps when a newer server put it there, and which this server can't trade. Each stack goes in by its place, as a copy of the stack as it is right now, with its count and its rolls. Gold they haven't got is refused, and gold they have goes in. The new offer is moved into their side, in place of the old one, and as it comes without a ready, their ready goes with it. There's something new to look at, so the other side isn't ready either, and both have news, so that both windows show the new offer. Ready finds the player's side as well, and refuses a player who isn't trading too. Otherwise, it sets their side's ready to what they said, and gives both of them news, as the other window shows who's ready. It returns whether both are ready now, which is this player saying yes while the other side already has. Then comes Complete, which is where the trade happens, once the world has seen both sides ready. It finds who the player's trading with, and offers holds pointers to both sides' offers, in an array, so that one loop can go over the two, side zero and side one. After holds copies of both bags, one for each side. We work on the copies, so that it's all of it or none: if anything fails halfway, the bags themselves haven't been touched, and there's nothing to undo. I reach for copies like this whenever two things have to change together. Refuse is a lambda, capturing by reference, that makes neither side ready, gives both news, and returns why, so each way a trade can fail reads as one line further down. First, each side gives up what it offered, so that its bag has that room for what it gets. Over the loop, we write it down plainly: as many as were offered come off each place, which trusts that what was offered is still there. So Take's error is ignored here, as this version takes the places on trust. Gold is checked, though: if the gold offered isn't all there any more, the trade is refused, with a line that says so. Then each side gets copies of what the other offered, into to, the other side's bag. Add puts a stack in, from the first slot it fits, and returns how many didn't fit, so anything left over means a bag hasn't room, and the trade is refused, for both. And gold that would take a player past the billion is refused too, with a line that says it's more than can be carried. If we get this far, the copies are moved into the real bags, both of them, each with its revision moved on, and the trade is over. End drops the player's asking, and, with C++20's erase if, anyone's asking them, so nobody is left asking a player who's gone. Without a trade, it returns zero, and with one, it erases both sides, gives both news, and returns who it was with. And take news hands the set over with std exchange, which leaves an empty one in its place. In the server's CMake file, trades goes into the server's core library, after the world, and its tests into the server's tests, which we're going to write in a moment.

24:47 Each World keeps the trades of the players in it, so most of the rules go in the world. In the world's header file, we bring in string view, for a name we're handed without copying it, and the trades' header. Trade reach is talk reach, four metres, the distance you can talk to an NPC from. Over it, we write why: two players trade within talking reach, as close as they'd stand to talk. Ask to trade takes the player asking, and the name of a player here, whatever its case, within trade reach. It asks them, or says yes to them asking first, which opens the trade, or the error says why not, in words for the player. Offer to trade is what the player offers in their trade, as the trades' Offer has it. Ready to trade says whether the player's ready to trade. Once both of them are, within trade reach, they trade, there and then, or the error says why not. Cancel trade calls the player's trade off, for both of them, and returns nothing, as calling a trade off can't fail. And in private, next to the notices and the events, the world gets its trades, between the players here, as both of them have to be. In the world, we bring in Abseil's match, which compares strings without their case, for the names. Distance gets an overload for two players, with hypot of the difference between them along x and z, like the one for a player and a monster above it. Leave used to erase the player and nothing more. Now, as both have to be here to trade, it ends their trade first, and if they were trading with someone, that player gets a notice with their name, saying they've gone, so the trade's off. Then the player is erased from the world, as before. Ask to trade finds the player asking, by their id, and with ranges find if, which takes the whole map, the player whose name equals the one asked, ignoring case, from a lambda that captures the name. If either is missing, nobody of that name is here, as a not found error, and a player who asks themselves can't trade with themselves, as an invalid argument. We keep both names, by reference, for the lines further down. Further away than trade reach, the player's too far away to trade with them, with the other player's name in the line, as an out of range error. A player who's trading already can't ask anyone else, and nor can anyone ask a player who's trading with someone already, which the asker hears with that player's name. When the asking doesn't open a trade, both players get a notice. The one asked hears who asks to trade, with the slash trade that says yes, so they know what to type, and the one asking hears that they asked. When the asking does open a trade, the trade's news does the telling, as both windows open. Offer to trade takes the player and their offer. It finds the player, or says there's nobody to trade, and hands the offer to the trades, with the player's bag and the content's items, as the world is what holds both of them. Ready to trade starts by finding who they're trading with, and refuses a player who isn't trading with anyone, with the line the trades would give. With both players in hand, saying ready from further than trade reach is refused, as they could have walked off since the trade opened, and it's up to the server to say they're too far away. Both is what the trades' Ready returns: whether both of them are ready now, and until they are, or if the trades refused it, we return its status, and there's nothing more to do. Once they are, they trade, here and now, as the second ready comes in, with both players' bags and the content's items. Over it, we note that both are ready, so they trade. If that fails, the other player hears why too, as a notice, and the one who said ready gets the error, which the server tells them. And if it worked, each of them hears who they traded with, the one who was ready last first. Last, cancel trade ends the player's trade, and if there was one, tells the other player who called it off.

28:37 Now, let's write some quick tests, starting with the inventory's two new ways to take things out of a bag. It starts from the test gear's items and an empty bag, which gets nine bones in its first slot, and thirty gold. Taking four bones works, and leaves five in the first place, which Holds checks as a pair of the item and the count. Six more aren't there, so that's refused, with its message, and nothing is taken. Taking the last five works, and empties the place, so it holds nothing at all, which comes back as zeros. Then the gold: twenty come off, eleven more aren't there, which is refused with its message, and ten are left. Then the trades get a test file of their own. We bring in the trades' header first, as the style guide puts a file's own header at the top, then c std int, set, string and vector from the standard library. Then gtest, places, for in bag, the server's test content, the world and the terrain, as the last test runs a trade through a world. In an unnamed namespace go the test items' ids: two for a potion, three for a bone, and four for a cap, as the test gear has them. Of makes a stack of an item, with a count that's one by default, which keeps the tests short. The next helper takes a list of places and some gold, none by default, and starts from an empty trade offer, to which it adds the places in one go, and then the gold. And Open makes a trade between players one and two, as each asked the other, and takes the news that made, so each test starts from a quiet, open trade. The first test checks that a trade opens once each player has asked the other, and not before. One asking two opens nothing, and one isn't trading with anyone. Then one asks three, which takes back the asking of two, so when two asks one, nothing opens either, and nobody has any news. Now one asks two again, and as two had asked one, it opens: one is trading with two, two with one, and both have news. Next, that changing an offer makes neither side ready. This is the rule I care about most here, as without it, someone could swap their offer for a worse one after the other side has said they're ready, and then say yes themselves. alice has five bones and thirty gold, and bob has a cap, and they've opened a trade. alice offers her bones and twenty gold, so her side holds the five bones, as a copy, and twenty gold. Then bob offers his cap and says he's ready, which doesn't make both of them ready yet, so Ready returns false, with bob's side ready, and both have news. Then alice offers ten gold, in place of the twenty, with her bones again, which bob hasn't seen. So bob has something new to look at, and he isn't ready any more. An empty place, the fourth, can't be offered, as there's nothing there to copy, and the error says so, nor can thirty-one gold she doesn't have, and an offer that's refused leaves the one before, ten gold. And player three, who isn't trading, is told so when they offer anything. Then the trade goes through, once both sides are ready. alice has five bones and thirty gold, and bob has three potions in his first place and a cap in his second. alice offers the bones and twenty gold, and bob offers the cap, from his second place. alice's ready isn't both of them, and bob's is, so Complete trades them, from bob's side this time. Each takes what they get into the first place it goes, which can be the one the other's offer left, so the cap goes where alice's bones were, and she has ten gold left. For bob, the five bones go where his cap was, his potions stay in his first place, and he has twenty gold. And then the trade is over, for both of them. Then, that a trade gives nothing until both bags have room for what they get. alice has five bones, and bob has a cap in each of his twenty-four slots, so his bag is full. alice offers her bones, bob offers nothing, and both say they're ready. We note both bags' revisions first, alice's and bob's, to check them afterwards, and Complete is refused, as there isn't room for the trade in one of the bags. Neither revision moves, so neither bag changed, as Complete worked on copies. They're still trading, and neither of them is ready any more, so they can change their offers. So bob offers a cap of his for the bones, which leaves him the room for them, as his cap goes out first. Both say they're ready again, and it goes through: alice has the cap, and bob the bones, where his cap was. The next one pins down what this version does when a stack grows after it's offered. alice has five bones, bob has an empty bag, and their trade is open. alice offers her bones, which the offer copies as five, and then a kill puts ten more onto the stack she offered, which stay hers, as she didn't offer them. Both are ready, and the trade takes the five that were offered, and leaves her ten, so bob gets five. I wanted this written down as a test: an offer is how many, and not whatever's in that place by the end. Then a test that ending a trade ends the asking too. One asks two, and ending one's trade, which hasn't opened, returns zero, as there's nobody it was with. One's asking went with it, so two asking one opens nothing, until one asks two again, which opens it. Ending two's trade returns one, who isn't trading with anyone any more, and both have news. Last, a trade through a world, with players in it, on an empty terrain, with the test gear. alice joins in the middle, and bob five metres along x, each with the kit, a sword in hand and three potions in their first slot. Five metres is further than trade reach, so alice is too far away to trade with bob, and nobody called carol is here at all. So bob leaves, and joins again two metres along. alice asks bob in capitals, as a name matches whatever its case, and when we take the notices, there are two of them. The first is bob's, which says alice asks to trade, and that he types slash trade alice to say yes. He asks her back, by her name, which opens the trade. alice offers her potions, and both of them say they're ready, so her first place is empty, and her three potions went onto his, which makes six, as potions stack. Then we take the notices, and there are two of them again, one for each player. So bob, who was ready last, hears first that he traded with alice, and then she hears that she traded with bob. Then, as leaving calls a trade off, they ask each other again, which opens another trade, and we take its notices. Then bob leaves, which tells alice in one notice that bob has gone, so the trade's off, and when she says she's ready, she isn't trading with anyone.

35:07 We run the trades' tests and the inventory's new one at this step, without the databases, as none of them needs MySQL or Redis, and the world's test runs a world in the test process. The build comes first, as the server has a new library file and a new test file. An offer is how many were offered, and two players trade through a world, so all eight pass.

Over the network

35:28 Next, the trades go over the network, starting in the world's header file, where trade of gives a player's trade as their client gets it: who it's with, by name, and what each side offers, or nobody, once it's over. And take trade news hands over the players whose trade has opened, changed or ended since the last time, so the server knows who to send a trade to after each tick. In the world, we bring in set, for the news. Then trade of starts from an empty trade. While the player is trading, it fills in the partner's name, from their player, and copies in both sides, the player's as yours and the partner's as theirs, so a trade without a partner means it's over. Take trade news passes the trades' news on, for the copies to gather. The server runs several copies of a land, each with a world of its own, so in the copies' header file, take trade news gives the players with news in any of them, as one set. The server sends those players their trades after the tick. In copies, we bring in set, and take trade news starts from an empty set, then goes through each copy, by reference, and merges its world's news into one set, which moves the ids across, without copying them. In the server's header file, the server gets Trade, for a player's trade action, next to Item and Guild, and send trades, for each player whose trade opened, changed or ended this tick. In the server, where a message from a client is handled, an input with a trade goes to Trade straight away, as a move in the bag does. So a trade happens as the second ready arrives, without waiting for the tick. Trade starts with two refusals, before it asks the world anything. While the server hands its players over to its next instance, nothing trades. Over it, we write why: a trade changes two bags, which the next instance loads as they were last saved, so a trade now would be lost. A trade moves things too, so it's on the bag's token bucket, ten at once and then ten a second, which we note over it, and past that, the player hears they're moving things too fast. In my opinion, that's the right limit for it, as a trade is one more way of moving items about. Then we take the world of the copy the player's in, and a switch on the action's case, which protobuf generates for a oneof, calls the world. Ask asks the player named, offer hands the world the new offer, ready says ready, or takes it back, and the world trades if both are. Cancel calls the trade off, which can't fail, so it leaves done as it is, an OK status. An action with nothing set in it does nothing at all, and returns. Whatever the world refused, the player hears why, in a line from nobody, with the message the world wrote for them. In the tick, after the guilds, the server sends the trades, once the world has stepped. Send trades goes through the players with news, in all the copies. Over the loop, we write why it's sent this way: a trade has to arrive, as a bag does, so it goes on its own, over TCP, to each side, and with nobody in it once it's over. For each player, we find their session and the world they're in, and skip a player who's gone, as their partner hears it from a notice. Their trade goes in a World message of its own, as their world has it for them, framed with its length in front, counted in the bytes we've sent, for the metrics, and sent on their session, which is TCP.

38:42 Next, a quick test that two players trade over the network, with the real server, in the server's tests. Their test player connects over TLS and keeps what the server sends it, so first, it gets somewhere to keep a trade. It's an optional, empty until the server has sent one, as we write over it, so that a test can wait for it to come. Where the test player reads its messages, a World message with a trade in it is kept as its trade, in an optional, next to its guild and its invite. The test makes a server of its own, which it calls market, whose content is the test gear alone, so both players join with the kit, a sword in hand and three potions in their first place. It's made the way the fixture makes its server, on a port of its own, with fifty-millisecond ticks and the fixture's databases, and we assert that it started. alice and bob connect to it, each with a token for their account, as any client would, and we run the event loop until both of them have their bags, at a revision past zero. Otherwise, alice might ask before bob's even in the world. alice asks bob by his name, in an input with a trade, and asked is the line bob should hear: alice's name, asking to trade, with the slash trade that says yes. We run the loop until that's the last notice bob has. Then he asks her back, and we run until both of them have a trade, each with the other as the partner, by name, which is what the client's window puts in its title. Next, alice offers the potions in her first place, with an input whose trade has an offer of place zero and no gold. We run until bob's trade shows them on her side, all three of them, as a copy of her stack, at a count of three. Then she says she's ready, and we wait for bob's trade to show her side as ready, as a player would look before saying yes, and then he says he's ready too. That's both of them, so the server trades them, and we run until bob's first place holds six potions, his three and her three, and alice's first place is empty. And last, we run until both get a trade with nobody in it, as it's over for both of them.

40:43 We run it at this step, against MySQL and Redis in Compose, as both players log in for real, with the test's server on a port of its own. The build comes first, as the server's code has changed again. The potions go across, the trade ends for both, and it passes.

A trade window

41:01 On the client, the trade gets a window, in a new header file, trade window. It brings in c std int, optional and utility, the items, and our protocol. Offer of turns a side of a trade, as the server sent it, back into an offer that asks for it again: its places in the bag, in order, and its gold. The window changes an offer by sending all of it again, so that's where each change starts. A trade window is a trade with another player, in a window of its own, which is open while the trade is, and over it, we write how it works. What you offer is on the left: you drag items onto it from the bag, click one to take it back, and type the gold, while what they offer is on the right. A side's slots light green once it's ready, Ready says you are, a change to either offer makes neither side ready, and closing the window calls the trade off. Its constructor takes the item table, for the icons and the tooltips, by value, moved in, and it's explicit, like the bag window's. Build is what the client's main calls once each frame. It draws the window while there's a trade, and returns what the player does, which the server does, or says in the chat why not. The window doesn't talk to the network, so main sends what it returns, as it does for the guild window. In private, it keeps the items, and then two things for the gold field. Gold is the number in the field, which follows our offer's gold until we click into it, and typing says whether we're in the field right now. Neither is sent anywhere, as they're the window's own state. In trade window, we bring in ImGui first, then algorithm, for sort and max, c std def and c std int, optional, string and vector. Then come Abseil's str cat, the bag window, for its slots and for accepting an item, our theme, and Font Awesome's icons, for the coin. In an unnamed namespace, a slot is forty-six points, a little smaller than the bag's fifty-two, with twenty-eight points between the two sides. Over them, we note that they're in points, at a scale of one, as the interface's scale multiplies them. Each side shows eight slots, or as many as it offers, four to a row, which we write down over them. Places of lists the places a side offers in the bag, in order, starting from an empty vector. It loops over the side's map with a structured binding, and pushes each place. Then it sorts them with ranges sort, as a protobuf map's come in no order at all, and the slots would shuffle about from one message to the next otherwise. Slots for is how many slots a side shows: eight, or the places offered rounded up to a whole row of four, whichever is more. Outside the unnamed namespace, as the header declares it, offer of builds an offer from a side: its places, sorted, added to the offer's bag in one go, and its gold, which is all an offer has. Build takes our trade, as the server last sent it. Without a partner, there's no trade, so it draws nothing, forgets that we were typing any gold, and returns no action. With one, yours and theirs are the two sides, by reference, partner is their name as a C string, for ImGui's formatting, and the action starts out empty. The window opens the first time in the middle across, and a little above the middle down, centred there by its pivot, with the bag to its right. Open stays true until the window's cross is clicked. The title says who the trade's with, and the three hashes give the window an ID that doesn't change with the name, so ImGui keeps one window for any partner, as we write over it. It's one of our panels, sized to what's in it, and left out of the settings file, and its close button sets open to false. The slots are at the interface's scale, with five points between them, pushed onto ImGui's style for the two sides. Our side starts from an offer of what we offer now, and over it, we write that what's dragged onto it from the bag goes in, and a click on one takes it back. Each change is a new offer, in place of this one, and changed says whether there's been one this frame. Our side is a group, so that the other side can go beside it, headed You offer. Each slot goes on the line of the one before, but for the first of each row of four, with an ID of its own from its index, as ImGui tells its widgets apart by them. Its stack is the offer's, at the place for that slot, or none past what's offered. Each is a stack slot, the slot the bag draws, lit green while we're ready. Clicking one with a stack in it takes it back: the offer's places are cleared, and all the places but that one go back in, and changed is set. Each slot is also a drag and drop target, and an item let go of over it, from the bag, that isn't offered already, goes onto the offer, as one more place. What you wear isn't offered, so the place has to be in the bag. Offering an item takes nothing more than the drop, which sends the whole new offer to the server, as main gets it back from Build. Under the slots goes the field, and over the if, we note that what's typed stays as it's typed, and goes once it's done with. So while we're not typing, the field follows the offer the server sent, and once we are, it's left alone. First, in the theme's gold, goes Font Awesome's coin, like the bag's, and the field beside it is a hundred and ten points wide. It's ImGui's input scalar, which edits a number in place, here an unsigned thirty-two-bit one. Typing is whether the field has the keyboard, and once it loses the focus after an edit, with Enter or a click elsewhere, the gold goes into the offer. That way, typing a hundred doesn't send one, then ten, then a hundred, and take the other side's ready back three times, which would drive them a bit mad. If anything changed, the action is the new offer, whole. Their side goes on the right, twenty-eight points over, to look at, as we note over it, in a group of its own, headed with their name. Their places, sorted, go in slots the way ours do, in rows of four, with IDs from a hundred, so they don't clash with ours. They're stack slots that do nothing when they're clicked, as their side is theirs to change, and they light green once they're ready. Their slots aren't drop targets, and their gold is a line under them, with the coin, in the theme's gold. After a little space, a button a hundred and fifty points wide says Ready, in the fire's colours, as it's what the window is for, or Not ready once we are. Clicking it sends the opposite of our ready, so it says yes, or takes it back. Beside it, a line says they're ready, in green, or that they aren't yet, muted. And after the panel ends, a window that was closed calls the trade off, with a cancel. In the client's CMake file, trade window goes into the client's core library, and its test, which we write in a moment, into the client's tests.

47:48 The bag window has to keep what's offered in place, as the trade takes it from the place it was offered from, for a player using our client. In the bag window's header file, item slot's description gets a sentence: a slot that's locked, as one offered in a trade is, does none of the dragging, using or wearing, and shows its item faint. So item slot takes a locked flag, false by default, as the character window's slots aren't offered. Next, a new function, stack slot, takes the items, a stack or none, the size, and an edge colour. It draws a stack, or nothing, in a slot of the size that doesn't drag. It shows its icon, how many there are, and its lines when the mouse is over it, with the edge lit in a colour, if there's one. It returns whether it was clicked, and it's what the trade window's slots are. Accept item, called inside a drag and drop target, gives where the item that's let go of over it was dragged from, in the bag or worn, once it's let go of. Then the bag window's Build takes what's offered in a trade, with an empty side by default, and we note over it that what's offered stays in its slot until the trade's over. In the bag window, item slot takes the locked flag. Where an item that's taken hold of starts a drag, so that it follows the mouse, a locked one doesn't. We add to the note over it that an item offered in a trade stays, as the trade takes it from here. Nor does anything dragged over a locked slot fit there, so it lights red, as a slot does where an item can't go. The icon's alpha is a quarter while it's being dragged, as before, a little under half while it's offered, and whole otherwise. Over it, we write that what's offered in a trade is faint until it's over. A double click on a locked item doesn't use it or wear it, and its tooltip gets a last line, in muted text, that says it's offered in the trade, so a player knows why it won't move. Right-clicking it opens no menu, so it can't be thrown away either. Then stack slot, which is an invisible button the size of a slot. That way, ImGui tells us when it's clicked, and where it is on screen, with the theme's slot drawn in its place, and its edge in the colour, if there's one. An empty slot has nothing more to draw, so it returns there, as not clicked. With a stack, it finds the item in the table, and draws its icon in the item's tint, or a question mark for an item the content doesn't have. With more than one, the count goes in the bottom right corner. It's in the bold face, fourteen points high at a scale of one, measured so that it sits in from the corner, with a shadow under it, in paper white, like the bag's counts. While the mouse is over it, a tooltip shows the item's lines, which item lines builds from the item and its rolls. The first, its name, is in the title face at fifteen points, in light gold, so the name stands out from its stats. The rest of its lines are muted, its stats and its rolls, as the bag's tooltip shows them, so an item reads alike in the bag and in a trade. Accept item asks ImGui for a payload of the bag's kind, which a drag from the bag or the character window carries, let go of over the target, and returns nothing without one. With one, it copies its bytes into a Dragged, the plain struct a drag carries, as ImGui copies payloads byte for byte, and gives back the place it says. Last, Build takes what's offered, and each slot of the bag is locked while its place is in the offer.

51:14 A trade starts from the chat, so the chat comes first, in its header file, where trade name gives who a line typed in the chat asks to trade with, when it starts with slash trade and a space. Any other line gets nothing, as guild line does for slash g. In the chat window, trade name checks that the line starts with the command, with C++20's starts with, and hands back the rest, as the name. The server looks the name up, so the client doesn't check it any further. In the connection's header file, trade returns our trade, with nobody in it for none, which the connection keeps. In the connection, our trade joins the list of what comes on its own, with nothing of the world in it. So a World message with a trade in it is kept as our trade, and doesn't go through the parts that build up the world. In the client's main, we bring in the trade window's header, and make one next to the guild window, with the content's items. Trading says whether we were trading last frame, and over it, we write that it's there so that the bag opens as a trade does. A line from the chat that names someone after slash trade goes in the input as a trade's ask, in place of something said to the world. Each frame, a trade that has just opened opens the bag too, to drag what's offered from, and trading remembers it for the next frame. The bag window gets our side of the trade, to lock what's offered. And the trade window is built from our trade. What it returns goes to the server in a copy of the last input we sent, with the trade in it, so we keep moving as we were.

52:45 Now, two quick tests on the client, one for each new piece. In the chat window's tests, slash trade bob asks bob, and trade bob, without the slash, is a line to the world, while slash trader isn't the command at all, as the command needs its space. And the trade window gets a test file of its own, with gtest, that it asks for an offer again in the order of the bag. A side offers places five and two, with thirty gold, and it's ready. The offer made from it has to list two and then five, sorted, with the thirty gold.

53:19 We run the chat's tests and the trade window's at this step, without the databases, as they're about the client alone. The build comes first, as the client has a new window and a new test file. Slash guild and slash trade go where they should, the offer comes back in the order of the bag, and all three pass.

53:37 Let's trade in the game, at this step, with gwen a couple of metres ahead. Slash trade and her name, typed into the chat, go to the server as the input's trade, and the world sends gwen a notice, with the slash trade that says yes. Once she asks back, the world opens the trade, and after the tick, its news goes to both players over TCP, so the window opens, with the bag beside it. Her offer arrives as a copy of a stack in her bag, an Ash Blade. The bones dragged onto our side go out as a new offer, by their place in the bag, and forty gold typed into the field go once Enter takes the focus away. The bag keeps the offered bones where they are, faint, and their tooltip says they're offered. Once gwen has had a look, she says she's ready, so her side lights green. Thirty-five in place of forty is a new offer, so the server takes her ready back, as she hasn't seen this one yet, until she's had a look at it and says she's ready again. Our ready makes two, and the server swaps the offers between copies of both bags, then sends both players a trade with nobody in it. So the window closes, with a line in the chat that says who we traded with. The Ash Blade is in the place the bones left, and the bag has eighty-five gold, which I'd call a pretty good deal for seven bones!

Writing it down

54:51 Last, the game's docs, starting with the gameplay page. Under items, a paragraph says where gold comes from, how much each kind drops, and that it's part of the bag's message. The page gets a section on trading, from asking by name within four metres, to how the window works, and that both bags change or neither does. And it ends on what the simple version trusts: that what was offered is still where it was, and that a side that's ready saw the offer that's there now. Each player's bag is then saved as any changed bag is, with its own player. I've written that down on purpose, as it's what the next episode picks apart. Where gold lives gets a decision record of its own, number twenty-seven. Gold goes in the bag's message, with its revision. Its context is that the bag was already one message, with a revision that the server sends it by and the saver writes it by, while the rest of a player goes to Redis with each tick that changes it. The decision is a field of the bag's message, in no slot, so adding or taking gold moves the bag's revision. So it goes where the bag goes: to the client over TCP, into Redis in the bag's bytes, and into MySQL's players table, from migration twelve. A billion at most keeps any two amounts inside a thirty-two-bit number. The first alternative I weighed is gold as an item, a stack of coins in the bag, which would take a slot, and drag, split and get thrown away like an item, none of which gold should do. Gold as a field of the player, next to their experience, would change in a different place from the items, so a trade would send and save the two apart. And gold in MySQL alone, as guilds are, would have the world's tick wait for MySQL at each kill. What it costs us is that each kill now changes the bag, so the server sends the whole bag and the saver writes its rows again, though most kills did already, for what they dropped. Keep in mind that a trade changes two players, and each one's bag is saved with its own player, as any bag is. It goes in the index too, as the twenty-seventh row.

Wrap-up

56:51 Today, monsters started dropping gold, a few coins a kill, which goes in the bag's message, outside its slots, so it changes with the bag's revision, and the saver writes it to MySQL when it writes the bag. Then trading, where each world keeps the trades between its players, who ask each other by name and offer stacks and gold, and the server sends both sides each change over TCP, after the tick. Slash trade asks a player, and once they ask back, a window opens, where you drag in what you offer and say you're ready. Once both sides are, the two bags swap in copies, all of it or none, in a simple version that takes what was offered on trust.

Playing it

58:21 Let me know in the comments what you'd like to see next, and if you want to follow along with the series, subscribe to the channel. I hope you find this useful, and thanks for watching.